Beispiel #1
0
  @SuppressWarnings("unchecked")
  public <T extends ORecord<?>> T getRecord() {
    if (!isValid()) return null;

    final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
    if (db == null)
      throw new ODatabaseException(
          "No database found in current thread local space. If you manually control databases over threads assure to set the current database before to use it by calling: ODatabaseRecordThreadLocal.INSTANCE.set(db);");

    return (T) db.load(this);
  }
Beispiel #2
0
  public ORawBuffer readRecord(
      final ORecordId iRid, final String iFetchPlan, final ORecordCallback<ORawBuffer> iCallback) {
    checkConnection();

    if (OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting)
      // PENDING NETWORK OPERATION, CAN'T EXECUTE IT NOW
      return null;

    do {
      try {

        OChannelBinaryClient network = null;
        try {
          network = beginRequest(OChannelBinaryProtocol.REQUEST_RECORD_LOAD);
          network.writeRID(iRid);
          network.writeString(iFetchPlan != null ? iFetchPlan : "");

        } finally {
          endRequest(network);
        }

        try {
          beginResponse(network);

          if (network.readByte() == 0) return null;

          final ORawBuffer buffer =
              new ORawBuffer(network.readBytes(), network.readInt(), network.readByte());

          final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get();
          ORecordInternal<?> record;
          while (network.readByte() == 2) {
            record = (ORecordInternal<?>) readIdentifiable(network);

            // PUT IN THE CLIENT LOCAL CACHE
            database.getLevel1Cache().updateRecord(record);
          }
          return buffer;
        } finally {
          endResponse(network);
        }

      } catch (OException e) {
        // PASS THROUGH
        throw e;
      } catch (Exception e) {
        handleException("Error on read record " + iRid, e);
      }
    } while (true);
  }
  protected ODatabaseDocumentTx openDatabase() {
    inheritedDatabase = true;

    final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
    if (db != null && db.getName().equals(databaseName) && !db.isClosed()) {
      if (db instanceof ODatabaseDocumentTx) return (ODatabaseDocumentTx) db;
      else if (db.getDatabaseOwner() instanceof ODatabaseDocumentTx)
        return (ODatabaseDocumentTx) db.getDatabaseOwner();
    }

    inheritedDatabase = false;
    return (ODatabaseDocumentTx)
        OServerMain.server()
            .openDatabase("document", databaseName, replicatorUser.name, replicatorUser.password);
  }
Beispiel #4
0
  public static ODatabaseDocumentTx getGraphDatabase(final ODatabaseRecord iCurrentDatabase) {
    ODatabaseRecord currentDb = ODatabaseRecordThreadLocal.INSTANCE.get();
    if (currentDb == null && iCurrentDatabase != null)
      // GET FROM THE RECORD
      currentDb = iCurrentDatabase;

    currentDb = (ODatabaseRecord) currentDb.getDatabaseOwner();

    final ODatabaseDocumentTx db;
    if (currentDb instanceof ODatabaseDocumentTx) db = (ODatabaseDocumentTx) currentDb;
    else if (currentDb instanceof ODatabaseDocumentTx) {
      db = new ODatabaseDocumentTx((ODatabaseRecordTx) currentDb.getUnderlying());
      ODatabaseRecordThreadLocal.INSTANCE.set(db);
    } else if (currentDb instanceof ODatabaseRecordTx) {
      db = new ODatabaseDocumentTx((ODatabaseRecordTx) currentDb);
      ODatabaseRecordThreadLocal.INSTANCE.set(db);
    } else
      throw new OCommandExecutionException(
          "Cannot find a database of type ODatabaseDocumentTx or ODatabaseRecordTx");
    return db;
  }
  @Override
  public boolean execute(final OHttpRequest iRequest) throws Exception {
    if (!iRequest.isMultipart) {
      sendTextContent(
          iRequest,
          OHttpUtils.STATUS_INVALIDMETHOD_CODE,
          "Request is not multipart/form-data",
          null,
          OHttpUtils.CONTENT_TEXT_PLAIN,
          "Request is not multipart/form-data");
    } else if (iRequest.multipartStream == null || iRequest.multipartStream.available() <= 0) {
      sendTextContent(
          iRequest,
          OHttpUtils.STATUS_INVALIDMETHOD_CODE,
          "Content stream is null or empty",
          null,
          OHttpUtils.CONTENT_TEXT_PLAIN,
          "Content stream is null or empty");
    } else {
      database = getProfiledDatabaseInstance(iRequest);
      try {
        parse(
            iRequest,
            new OHttpMultipartContentBaseParser(),
            new OHttpMultipartDatabaseImportContentParser(),
            database);
        //
        // FileOutputStream f = new FileOutputStream("C:/temp/backup.gz");
        // while (importData.available() > 0) {
        // f.write(importData.read());
        // }
        // f.close()

        ODatabaseImport importer =
            new ODatabaseImport(getProfiledDatabaseInstance(iRequest), importData, this);
        importer.importDatabase();
        sendTextContent(
            iRequest,
            OHttpUtils.STATUS_OK_CODE,
            "OK",
            null,
            OHttpUtils.CONTENT_JSON,
            "{\"responseText\": \"Database imported Correctly, see server log for more informations.\"}");
      } catch (Exception e) {
        sendTextContent(
            iRequest,
            OHttpUtils.STATUS_INTERNALERROR_CODE,
            e.getMessage() + ": " + e.getCause() != null ? e.getCause().getMessage() : "",
            null,
            OHttpUtils.CONTENT_JSON,
            "{\"responseText\": \""
                + e.getMessage()
                + ": "
                + (e.getCause() != null ? e.getCause().getMessage() : "")
                + "\"}");
      } finally {
        if (database != null) database.close();
        database = null;
        if (importData != null) importData.close();
        importData = null;
      }
    }
    return false;
  }
Beispiel #6
0
  private void configureDocument(
      ORecordAbstract<?> document, ODatabaseRecord db, DefinitionGroup definition) {
    // configure document

    // as of OrientDB 1.0rc8 the database may no longer be set on the
    // document
    // instead the current database can be set using
    // ODatabaseRecordThreadLocal.INSTANCE.set(db);
    //		document.setDatabase(db);
    if (document instanceof ODocument) {
      // reset class name
      ODocument doc = (ODocument) document;
      /*
       * Attention: Two long class names cause problems as file names will
       * be based on them.
       */
      String className = null;
      if (definition != null) {
        className = ONamespaceMap.encode(determineName(definition));
      } else if (doc.containsField(OSerializationHelper.BINARY_WRAPPER_FIELD)
          || doc.containsField(OSerializationHelper.FIELD_SERIALIZATION_TYPE)) {
        className = OSerializationHelper.BINARY_WRAPPER_CLASSNAME;
      }

      if (className != null) {
        OSchema schema = db.getMetadata().getSchema();
        if (!schema.existsClass(className)) {
          // if the class doesn't exist yet, create a physical cluster
          // manually for it
          int cluster = db.addCluster(className, CLUSTER_TYPE.PHYSICAL);
          schema.createClass(className, cluster);
        }
        doc.setClassName(className);
      }

      // configure children
      for (Entry<String, Object> field : doc) {
        List<ODocument> docs = new ArrayList<ODocument>();
        List<ORecordAbstract<?>> recs = new ArrayList<ORecordAbstract<?>>();
        if (field.getValue() instanceof Collection<?>) {
          for (Object value : (Collection<?>) field.getValue()) {
            if (value instanceof ODocument && !getSpecialFieldNames().contains(field.getKey())) {
              docs.add((ODocument) value);
            } else if (value instanceof ORecordAbstract<?>) {
              recs.add((ORecordAbstract<?>) value);
            }
          }
        } else if (field.getValue() instanceof ODocument
            && !getSpecialFieldNames().contains(field.getKey())) {
          docs.add((ODocument) field.getValue());
        } else if (field.getValue() instanceof ORecordAbstract<?>) {
          recs.add((ORecordAbstract<?>) field.getValue());
        }

        if (definition != null) {
          for (ODocument valueDoc : docs) {
            ChildDefinition<?> child = definition.getChild(decodeProperty(field.getKey()));
            DefinitionGroup childGroup;
            if (child.asProperty() != null) {
              childGroup = child.asProperty().getPropertyType();
            } else if (child.asGroup() != null) {
              childGroup = child.asGroup();
            } else {
              throw new IllegalStateException(
                  "Document is associated neither with a property nor a property group.");
            }
            configureDocument(valueDoc, db, childGroup);
          }
        }

        for (ORecordAbstract<?> fieldRec : recs) {
          configureDocument(fieldRec, db, null);
        }
      }
    }
  }
  @SuppressWarnings("unchecked")
  public OCommandExecutorSQLInsert parse(final OCommandRequest iRequest) {
    final ODatabaseRecord database = getDatabase();
    database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);

    init((OCommandRequestText) iRequest);

    className = null;
    newRecords = null;
    content = null;

    parserRequiredKeyword("INSERT");
    parserRequiredKeyword("INTO");

    String subjectName =
        parserRequiredWord(true, "Invalid subject name. Expected cluster, class or index");
    if (subjectName.startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX))
      // CLUSTER
      clusterName = subjectName.substring(OCommandExecutorSQLAbstract.CLUSTER_PREFIX.length());
    else if (subjectName.startsWith(OCommandExecutorSQLAbstract.INDEX_PREFIX))
      // INDEX
      indexName = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_PREFIX.length());
    else {
      // CLASS
      if (subjectName.startsWith(OCommandExecutorSQLAbstract.CLASS_PREFIX))
        subjectName = subjectName.substring(OCommandExecutorSQLAbstract.CLASS_PREFIX.length());

      final OClass cls = database.getMetadata().getSchema().getClass(subjectName);
      if (cls == null) throwParsingException("Class " + subjectName + " not found in database");

      className = cls.getName();
    }

    parserSkipWhiteSpaces();
    if (parserIsEnded())
      throwSyntaxErrorException(
          "Set of fields is missed. Example: (name, surname) or SET name = 'Bill'");

    final String temp = parseOptionalWord(true);
    if (temp.equals("CLUSTER")) {
      clusterName = parserRequiredWord(false);

      parserSkipWhiteSpaces();
      if (parserIsEnded())
        throwSyntaxErrorException(
            "Set of fields is missed. Example: (name, surname) or SET name = 'Bill'");
    } else parserGoBack();

    newRecords = new ArrayList<Map<String, Object>>();
    if (parserGetCurrentChar() == '(') {
      parseValues();
    } else {
      parserNextWord(true, " ,\r\n");

      if (parserGetLastWord().equals(KEYWORD_CONTENT)) {
        newRecords = null;
        parseContent();
      } else if (parserGetLastWord().equals(KEYWORD_SET)) {
        final LinkedHashMap<String, Object> fields = new LinkedHashMap<String, Object>();
        newRecords.add(fields);
        parseSetFields(fields);
      }
    }

    return this;
  }
Beispiel #8
0
  /** Execute the command remotely and get the results back. */
  public Object command(final OCommandRequestText iCommand) {
    checkConnection();

    if (!(iCommand instanceof OSerializableStream))
      throw new OCommandExecutionException(
          "Cannot serialize the command to be executed to the server side.");

    OSerializableStream command = iCommand;
    Object result = null;

    final ODatabaseRecord database = ODatabaseRecordThreadLocal.INSTANCE.get();

    do {
      OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting = true;

      try {
        final OCommandRequestText aquery = iCommand;

        final boolean asynch = iCommand instanceof OCommandRequestAsynch;

        OChannelBinaryClient network = null;
        try {
          network = beginRequest(OChannelBinaryProtocol.REQUEST_COMMAND);

          network.writeByte((byte) (asynch ? 'a' : 's')); // ASYNC / SYNC
          network.writeBytes(OStreamSerializerAnyStreamable.INSTANCE.toStream(command));

        } finally {
          endRequest(network);
        }

        try {
          beginResponse(network);

          if (asynch) {
            byte status;

            // ASYNCH: READ ONE RECORD AT TIME
            while ((status = network.readByte()) > 0) {
              final ORecordSchemaAware<?> record =
                  (ORecordSchemaAware<?>) readIdentifiable(network);
              if (record == null) break;

              switch (status) {
                case 1:
                  // PUT AS PART OF THE RESULT SET. INVOKE THE LISTENER
                  try {
                    if (!aquery.getResultListener().result(record)) {
                      // EMPTY THE INPUT CHANNEL
                      while (network.in.available() > 0) network.in.read();

                      break;
                    }
                  } catch (Throwable t) {
                    // ABSORBE ALL THE USER EXCEPTIONS
                    t.printStackTrace();
                  }
                  database.getLevel1Cache().updateRecord(record);
                  break;

                case 2:
                  // PUT IN THE CLIENT LOCAL CACHE
                  database.getLevel1Cache().updateRecord(record);
              }
            }
          } else {
            final byte type = network.readByte();
            switch (type) {
              case 'n':
                result = null;
                break;

              case 'r':
                result = readIdentifiable(network);
                if (result instanceof ORecord<?>)
                  database.getLevel1Cache().updateRecord((ORecordInternal<?>) result);
                break;

              case 'l':
                final int tot = network.readInt();
                final Collection<OIdentifiable> list = new ArrayList<OIdentifiable>();
                for (int i = 0; i < tot; ++i) {
                  final OIdentifiable resultItem = readIdentifiable(network);
                  if (resultItem instanceof ORecord<?>)
                    database.getLevel1Cache().updateRecord((ORecordInternal<?>) resultItem);
                  list.add(resultItem);
                }
                result = list;
                break;

              case 'a':
                final String value = new String(network.readBytes());
                result =
                    ORecordSerializerStringAbstract.fieldTypeFromStream(
                        null, ORecordSerializerStringAbstract.getType(value), value);
                break;
            }
          }
          break;
        } finally {
          endResponse(network);
        }

      } catch (OException e) {
        // PASS THROUGH
        throw e;
      } catch (Exception e) {
        handleException("Error on executing command: " + iCommand, e);

      } finally {
        OStorageRemoteThreadLocal.INSTANCE.get().commandExecuting = false;
      }
    } while (true);

    return result;
  }