public OSchemaShared(boolean clustersCanNotBeSharedAmongClasses) {
    super(new ODocument().setTrackingChanges(false));
    this.clustersCanNotBeSharedAmongClasses = clustersCanNotBeSharedAmongClasses;

    Orient.instance().registerWeakOrientStartupListener(this);
    Orient.instance().registerWeakOrientShutdownListener(this);
  }
 public ODatabasePoolAbstract(
     final Object iOwner, final int iMinSize, final int iMaxSize, final int iTimeout) {
   maxSize = iMaxSize;
   timeout = iTimeout;
   owner = iOwner;
   Orient.instance().registerListener(this);
 }
 /** Pre-loads OrientDB using empty (system) TCCL so javax.script engines can be found. */
 private static void preloadOrientEngine() {
   ClassLoader tccl = Thread.currentThread().getContextClassLoader();
   try {
     Thread.currentThread().setContextClassLoader(null);
     com.orientechnologies.orient.core.Orient.instance();
   } finally {
     Thread.currentThread().setContextClassLoader(tccl);
   }
 }
  @Override
  public void deinit() {
    final long endRecords = database.countClass("Account");
    System.out.println(
        "Total accounts: " + endRecords + ". Expected: " + (beginRecords + data.getCycles()));

    System.out.println(Orient.instance().getProfiler().dump());

    if (database != null) database.close();
    super.deinit();
  }
  @Override
  public void init() {
    Orient.instance().getProfiler().startRecording();

    database = new ODatabaseDocumentTx(System.getProperty("url")).open("admin", "admin");
    record = database.newInstance();

    database.declareIntent(new OIntentMassiveInsert());
    database.begin(TXTYPE.NOTX);

    beginRecords = database.countClass("Account");
    System.out.println("Total accounts: " + beginRecords);
  }
  /**
   * Register statistic information about usage of index in {@link OProfilerStub}.
   *
   * @param index which usage is registering.
   */
  private void updateStatistic(OIndex<?> index) {

    final OProfiler profiler = Orient.instance().getProfiler();
    if (profiler.isRecording()) {
      Orient.instance()
          .getProfiler()
          .updateCounter(
              profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"),
              "Used index in query",
              +1);

      final int paramCount = index.getDefinition().getParamCount();
      if (paramCount > 1) {
        final String profiler_prefix =
            profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed");
        profiler.updateCounter(profiler_prefix, "Used composite index in query", +1);
        profiler.updateCounter(
            profiler_prefix + "." + paramCount,
            "Used composite index in query with " + paramCount + " params",
            +1);
      }
    }
  }
Exemple #7
0
  /**
   * Drops a database from a remote server instance.
   *
   * @param iDatabaseName The database name
   * @param storageType Storage type between "plocal" or "memory".
   * @return The instance itself. Useful to execute method in chain
   * @throws IOException
   */
  public synchronized OServerAdmin dropDatabase(
      final String iDatabaseName, final String storageType) throws IOException {

    boolean retry = true;
    while (retry) {
      retry =
          networkAdminOperation(
              new OStorageRemoteOperation<Boolean>() {
                @Override
                public Boolean execute(
                    final OChannelBinaryAsynchClient network, OStorageRemoteSession session)
                    throws IOException {
                  try {
                    try {
                      storage.beginRequest(
                          network, OChannelBinaryProtocol.REQUEST_DB_DROP, session);
                      network.writeString(iDatabaseName);
                      network.writeString(storageType);
                    } finally {
                      storage.endRequest(network);
                    }

                    storage.getResponse(network, session);
                    return false;
                  } catch (OModificationOperationProhibitedException oope) {
                    return handleDBFreeze();
                  }
                }
              },
              "Cannot delete the remote storage: " + storage.getName());
    }

    final Set<OStorage> underlyingStorages = new HashSet<OStorage>();

    for (OStorage s : Orient.instance().getStorages()) {
      if (s.getType().equals(storage.getType()) && s.getName().equals(storage.getName())) {
        underlyingStorages.add(s.getUnderlying());
      }
    }

    for (OStorage s : underlyingStorages) {
      s.close(true, true);
    }

    ODatabaseRecordThreadLocal.INSTANCE.remove();

    return this;
  }
  public OServerNetworkListener(
      final OServer iServer,
      final OServerSocketFactory iSocketFactory,
      final String iHostName,
      final String iHostPortRange,
      final String iProtocolName,
      final Class<? extends ONetworkProtocol> iProtocol,
      final OServerParameterConfiguration[] iParameters,
      final OServerCommandConfiguration[] iCommands) {
    super(
        Orient.instance().getThreadGroup(),
        "OrientDB " + iProtocol.getSimpleName() + " listen at " + iHostName + ":" + iHostPortRange);
    server = iServer;

    socketFactory = iSocketFactory == null ? OServerSocketFactory.getDefault() : iSocketFactory;

    // DETERMINE THE PROTOCOL VERSION BY CREATING A NEW ONE AND THEN THROW IT AWAY
    // TODO: CREATE PROTOCOL FACTORIES INSTEAD
    try {
      protocolVersion = iProtocol.newInstance().getVersion();
    } catch (Exception e) {
      OLogManager.instance()
          .error(
              this,
              "Error on reading protocol version for %s",
              e,
              ONetworkProtocolException.class,
              iProtocol);
    }

    listen(iHostName, iHostPortRange, iProtocolName);
    protocolType = iProtocol;

    readParameters(iServer.getContextConfiguration(), iParameters);

    if (iCommands != null) {
      for (int i = 0; i < iCommands.length; ++i) {
        if (iCommands[i].stateful)
          // SAVE STATEFUL COMMAND CFG
          registerStatefulCommand(iCommands[i]);
        else
          // EARLY CREATE STATELESS COMMAND
          registerStatelessCommand(OServerNetworkListener.createCommand(server, iCommands[i]));
      }
    }

    start();
  }
  @BeforeClass
  public void beforeClass() throws IOException {

    OGlobalConfiguration.FILE_LOCK.setValue(Boolean.FALSE);

    String buildDirectory = System.getProperty("buildDirectory");
    if (buildDirectory == null) buildDirectory = ".";

    storageLocal =
        (OLocalPaginatedStorage)
            Orient.instance()
                .loadStorage("plocal:" + buildDirectory + "/ReadWriteCacheConcurrentTest");
    storageLocal.create(null);

    prepareFilesForTest(FILE_COUNT);
  }
Exemple #10
0
  public void close(final boolean iForce) {
    lock.acquireExclusiveLock();

    OChannelBinaryClient network = null;
    try {
      if (networkPool.size() > 0) {
        try {
          network = beginRequest(OChannelBinaryProtocol.REQUEST_DB_CLOSE);
        } finally {
          endRequest(network);
        }

        getResponse(network);
      }

      setSessionId(-1);

      if (!checkForClose(iForce)) return;

      // CLOSE THE CHANNEL
      if (serviceThread != null) {
        serviceThread.sendShutdown();
        serviceThread.interrupt();
      }

      synchronized (networkPool) {
        for (OChannelBinaryClient n : networkPool) n.close();
        networkPool.clear();
      }

      level2Cache.shutdown();
      super.close(iForce);
      status = STATUS.CLOSED;

      Orient.instance().unregisterStorage(this);

    } catch (OException e) {
      // PASS THROUGH
      throw e;
    } catch (Exception e) {
      OLogManager.instance().debug(this, "Error on closing remote connection: %s", network);
    } finally {

      lock.releaseExclusiveLock();
    }
  }
Exemple #11
0
  static OIdentifiable readIdentifiable(final OChannelBinaryClient network) throws IOException {
    final int classId = network.readShort();
    if (classId == OChannelBinaryProtocol.RECORD_NULL) return null;

    if (classId == OChannelBinaryProtocol.RECORD_RID) {
      return network.readRID();
    } else {
      final ORecordInternal<?> record =
          Orient.instance().getRecordFactoryManager().newInstance(network.readByte());

      if (record instanceof ORecordSchemaAware<?>)
        ((ORecordSchemaAware<?>) record)
            .fill(network.readRID(), network.readInt(), network.readBytes(), false);
      else
        // DISCARD CLASS ID
        record.fill(network.readRID(), network.readInt(), network.readBytes(), false);

      return record;
    }
  }
  /** Called each time one of the security classes (OUser, ORole, OServerRole) is modified. */
  public void securityRecordChange(final String dbURL, final ODocument record) {

    // The point of this is to notify any matching (via URL) active database that its user
    // needs to be reloaded to pick up any changes that may affect its security permissions.

    // We execute this in a new thread to avoid blocking the caller for too long.
    Orient.instance()
        .submit(
            new Runnable() {
              @Override
              public void run() {
                try {
                  OClientConnectionManager ccm = server.getClientConnectionManager();

                  if (ccm != null) {
                    for (OClientConnection cc : ccm.getConnections()) {
                      try {
                        ODatabaseDocumentInternal ccDB = cc.getDatabase();
                        if (ccDB != null) {
                          ccDB.activateOnCurrentThread();
                          if (!ccDB.isClosed() && ccDB.getURL() != null) {
                            if (ccDB.getURL().equals(dbURL)) {
                              ccDB.reloadUser();
                            }
                          }
                        }
                      } catch (Exception ex) {
                        OLogManager.instance()
                            .error(this, "securityRecordChange() Exception: ", ex);
                      }
                    }
                  }
                } catch (Exception ex) {
                  OLogManager.instance().error(this, "securityRecordChange() Exception: ", ex);
                }
                ODatabaseRecordThreadLocal.INSTANCE.remove();
              }
            });
  }
 private OProfiler getProfilerInstance() throws Exception {
   return Orient.instance().getProfiler();
 }
  @Override
  public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    checkSyntax(iRequest.url, 1, "Syntax error: server");

    iRequest.data.commandInfo = "Server status";

    try {
      StringWriter jsonBuffer = new StringWriter();
      OJSONWriter json = new OJSONWriter(jsonBuffer);

      json.beginObject();

      json.beginCollection(1, true, "connections");

      String lastCommandOn;
      String connectedOn;

      final List<OClientConnection> conns = OClientConnectionManager.instance().getConnections();
      for (OClientConnection c : conns) {
        final ONetworkProtocolData data = c.data;

        synchronized (dateTimeFormat) {
          lastCommandOn = dateTimeFormat.format(new Date(data.lastCommandReceived));
          connectedOn = dateTimeFormat.format(new Date(c.since));
        }

        json.beginObject(2);
        writeField(json, 2, "connectionId", c.id);
        writeField(
            json,
            2,
            "remoteAddress",
            c.protocol.getChannel() != null ? c.protocol.getChannel().toString() : "Disconnected");
        writeField(json, 2, "db", data.lastDatabase != null ? data.lastDatabase : "-");
        writeField(json, 2, "user", data.lastUser != null ? data.lastUser : "******");
        writeField(json, 2, "totalRequests", data.totalRequests);
        writeField(json, 2, "commandInfo", data.commandInfo);
        writeField(json, 2, "commandDetail", data.commandDetail);
        writeField(json, 2, "lastCommandOn", lastCommandOn);
        writeField(json, 2, "lastCommandInfo", data.lastCommandInfo);
        writeField(json, 2, "lastCommandDetail", data.lastCommandDetail);
        writeField(json, 2, "lastExecutionTime", data.lastCommandExecutionTime);
        writeField(json, 2, "totalWorkingTime", data.totalCommandExecutionTime);
        writeField(json, 2, "connectedOn", connectedOn);
        writeField(json, 2, "protocol", c.protocol.getType());
        writeField(json, 2, "clientId", data.clientId);

        final StringBuilder driver = new StringBuilder();
        if (data.driverName != null) {
          driver.append(data.driverName);
          driver.append(" v");
          driver.append(data.driverVersion);
          driver.append(" Protocol v");
          driver.append(data.protocolVersion);
        }

        writeField(json, 2, "driver", driver.toString());
        json.endObject(2);
      }
      json.endCollection(1, false);

      json.beginCollection(1, true, "dbs");
      Map<String, OResourcePool<String, ODatabaseDocumentTx>> dbPool =
          OSharedDocumentDatabase.getDatabasePools();
      for (Entry<String, OResourcePool<String, ODatabaseDocumentTx>> entry : dbPool.entrySet()) {
        for (ODatabaseDocumentTx db : entry.getValue().getResources()) {

          json.beginObject(2);
          writeField(json, 2, "db", db.getName());
          writeField(json, 2, "user", db.getUser() != null ? db.getUser().getName() : "-");
          writeField(json, 2, "status", db.isClosed() ? "closed" : "open");
          writeField(json, 2, "type", db.getType());
          writeField(json, 2, "storageType", db.getStorage().getType());
          json.endObject(2);
        }
      }
      json.endCollection(1, false);

      json.beginCollection(1, true, "storages");
      Collection<OStorage> storages = Orient.instance().getStorages();
      for (OStorage s : storages) {
        json.beginObject(2);
        writeField(json, 2, "name", s.getName());
        writeField(json, 2, "type", s.getClass().getSimpleName());
        writeField(
            json,
            2,
            "path",
            s instanceof OStorageLocalAbstract
                ? ((OStorageLocalAbstract) s).getStoragePath().replace('\\', '/')
                : "");
        writeField(json, 2, "activeUsers", s.getUsers());
        json.endObject(2);
      }
      json.endCollection(1, false);

      json.beginCollection(2, true, "properties");
      for (OServerEntryConfiguration entry : OServerMain.server().getConfiguration().properties) {
        json.beginObject(3, true, null);
        json.writeAttribute(4, false, "name", entry.name);
        json.writeAttribute(4, false, "value", entry.value);
        json.endObject(3, true);
      }
      json.endCollection(2, true);
      json.endObject();

      iResponse.send(
          OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, jsonBuffer.toString(), null);

    } finally {
    }
    return false;
  }
 @Parameters(value = "url")
 public TransactionAtomicTest(String iURL) {
   Orient.instance().registerEngine(new OEngineRemote());
   url = iURL;
 }
 protected OServerShutdownHook(final OServer iServer) {
   server = iServer;
   Orient.instance().removeShutdownHook();
   Runtime.getRuntime().addShutdownHook(this);
 }
  public <RET extends ORecordInternal<?>> RET executeReadRecord(
      final ORecordId iRid,
      ORecordInternal<?> iRecord,
      final String iFetchPlan,
      final boolean iIgnoreCache) {
    checkOpeness();

    // setCurrentDatabaseinThreadLocal();

    try {
      checkSecurity(
          ODatabaseSecurityResources.CLUSTER,
          ORole.PERMISSION_READ,
          getClusterNameById(iRid.getClusterId()));

      // SEARCH IN LOCAL TX
      ORecordInternal<?> record = getTransaction().getRecord(iRid);
      if (record == null && !iIgnoreCache)
        // SEARCH INTO THE CACHE
        record = getLevel1Cache().findRecord(iRid);

      if (record != null) {
        OFetchHelper.checkFetchPlanValid(iFetchPlan);
        callbackHooks(TYPE.BEFORE_READ, record);

        if (record.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) record.reload();

        callbackHooks(TYPE.AFTER_READ, record);
        return (RET) record;
      }

      final ORawBuffer recordBuffer = underlying.read(iRid, iFetchPlan);
      if (recordBuffer == null) return null;

      if (iRecord == null || iRecord.getRecordType() != recordBuffer.recordType)
        // NO SAME RECORD TYPE: CAN'T REUSE OLD ONE BUT CREATE A NEW ONE FOR IT
        iRecord = Orient.instance().getRecordFactoryManager().newInstance(recordBuffer.recordType);

      iRecord.fill(iRid, recordBuffer.version, recordBuffer.buffer, false);

      callbackHooks(TYPE.BEFORE_READ, iRecord);

      iRecord.fromStream(recordBuffer.buffer);
      iRecord.setInternalStatus(ORecordElement.STATUS.LOADED);

      callbackHooks(TYPE.AFTER_READ, iRecord);

      if (!iIgnoreCache) getLevel1Cache().updateRecord(iRecord);

      return (RET) iRecord;
    } catch (OException e) {
      // RE-THROW THE EXCEPTION
      throw e;

    } catch (Exception e) {
      // WRAP IT AS ODATABASE EXCEPTION
      OLogManager.instance()
          .exception("Error on retrieving record " + iRid, e, ODatabaseException.class);
    }
    return null;
  }
@SuppressWarnings("serial")
public abstract class ORecordSerializerStringAbstract implements ORecordSerializer, Serializable {
  protected static final OJVMProfiler PROFILER = Orient.instance().getProfiler();
  private static final char DECIMAL_SEPARATOR = '.';
  private static final String MAX_INTEGER_AS_STRING = String.valueOf(Integer.MAX_VALUE);
  private static final int MAX_INTEGER_DIGITS = MAX_INTEGER_AS_STRING.length();

  protected abstract StringBuilder toString(
      final ORecordInternal<?> iRecord,
      final StringBuilder iOutput,
      final String iFormat,
      final OUserObject2RecordHandler iObjHandler,
      final Set<Long> iMarshalledRecords,
      boolean iOnlyDelta,
      boolean autoDetectCollectionType);

  public abstract ORecordInternal<?> fromString(
      String iContent, ORecordInternal<?> iRecord, String[] iFields);

  public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat) {
    return toString(
        iRecord,
        new StringBuilder(),
        iFormat,
        ODatabaseRecordThreadLocal.INSTANCE.get(),
        OSerializationLongIdThreadLocal.INSTANCE.get(),
        false,
        true);
  }

  public StringBuilder toString(
      final ORecordInternal<?> iRecord,
      final String iFormat,
      final boolean autoDetectCollectionType) {
    return toString(
        iRecord,
        new StringBuilder(),
        iFormat,
        ODatabaseRecordThreadLocal.INSTANCE.get(),
        OSerializationLongIdThreadLocal.INSTANCE.get(),
        false,
        autoDetectCollectionType);
  }

  public StringBuilder toString(
      final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat) {
    return toString(
        iRecord,
        iOutput,
        iFormat,
        null,
        OSerializationLongIdThreadLocal.INSTANCE.get(),
        false,
        true);
  }

  public ORecordInternal<?> fromString(final String iSource) {
    return fromString(
        iSource,
        (ORecordInternal<?>) ODatabaseRecordThreadLocal.INSTANCE.get().newInstance(),
        null);
  }

  public ORecordInternal<?> fromStream(
      final byte[] iSource, final ORecordInternal<?> iRecord, final String[] iFields) {
    final long timer = PROFILER.startChrono();

    try {
      return fromString(OBinaryProtocol.bytes2string(iSource), iRecord, iFields);
    } finally {

      PROFILER.stopChrono(
          PROFILER.getProcessMetric("serializer.record.string.fromStream"),
          "Deserialize record from stream",
          timer);
    }
  }

  public byte[] toStream(final ORecordInternal<?> iRecord, boolean iOnlyDelta) {
    final long timer = PROFILER.startChrono();

    try {
      return OBinaryProtocol.string2bytes(
          toString(
                  iRecord,
                  new StringBuilder(),
                  null,
                  null,
                  OSerializationLongIdThreadLocal.INSTANCE.get(),
                  iOnlyDelta,
                  true)
              .toString());
    } finally {

      PROFILER.stopChrono(
          PROFILER.getProcessMetric("serializer.record.string.toStream"),
          "Serialize record to stream",
          timer);
    }
  }

  public static Object fieldTypeFromStream(
      final ODocument iDocument, OType iType, final Object iValue) {
    if (iValue == null) return null;

    if (iType == null) iType = OType.EMBEDDED;

    switch (iType) {
      case STRING:
      case INTEGER:
      case BOOLEAN:
      case FLOAT:
      case DECIMAL:
      case LONG:
      case DOUBLE:
      case SHORT:
      case BYTE:
      case BINARY:
      case DATE:
      case DATETIME:
      case LINK:
        return simpleValueFromStream(iValue, iType);

      case EMBEDDED:
        // EMBEDED RECORD
        return ((ODocument) OStringSerializerEmbedded.INSTANCE.fromStream((String) iValue))
            .addOwner(iDocument);

      case CUSTOM:
        // RECORD
        final Object result = OStringSerializerAnyStreamable.INSTANCE.fromStream((String) iValue);
        if (result instanceof ODocument) ((ODocument) result).addOwner(iDocument);
        return result;

      case EMBEDDEDSET:
      case EMBEDDEDLIST:
        {
          final String value = (String) iValue;
          return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionFromStream(
              iDocument, iType, null, null, value);
        }

      case EMBEDDEDMAP:
        {
          final String value = (String) iValue;
          return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapFromStream(
              iDocument, null, value, null);
        }
    }

    throw new IllegalArgumentException(
        "Type " + iType + " not supported to convert value: " + iValue);
  }

  public static Object convertValue(final String iValue, final OType iExpectedType) {
    final Object v = getTypeValue((String) iValue);
    return OType.convert(v, iExpectedType.getDefaultJavaType());
  }

  public static void fieldTypeToString(
      final StringBuilder iBuffer, OType iType, final Object iValue) {
    if (iValue == null) return;

    final long timer = PROFILER.startChrono();

    if (iType == null) {
      if (iValue instanceof ORID) iType = OType.LINK;
      else iType = OType.EMBEDDED;
    }

    switch (iType) {
      case STRING:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.string2string"),
            "Serialize string to string",
            timer);
        break;

      case BOOLEAN:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.bool2string"),
            "Serialize boolean to string",
            timer);
        break;

      case INTEGER:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.int2string"),
            "Serialize integer to string",
            timer);
        break;

      case FLOAT:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.float2string"),
            "Serialize float to string",
            timer);
        break;

      case DECIMAL:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.decimal2string"),
            "Serialize decimal to string",
            timer);
        break;

      case LONG:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.long2string"),
            "Serialize long to string",
            timer);
        break;

      case DOUBLE:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.double2string"),
            "Serialize double to string",
            timer);
        break;

      case SHORT:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.short2string"),
            "Serialize short to string",
            timer);
        break;

      case BYTE:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.byte2string"),
            "Serialize byte to string",
            timer);
        break;

      case BINARY:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.binary2string"),
            "Serialize binary to string",
            timer);
        break;

      case DATE:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.date2string"),
            "Serialize date to string",
            timer);
        break;

      case DATETIME:
        simpleValueToStream(iBuffer, iType, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.datetime2string"),
            "Serialize datetime to string",
            timer);
        break;

      case LINK:
        if (iValue instanceof ORecordId) ((ORecordId) iValue).toString(iBuffer);
        else ((ORecord<?>) iValue).getIdentity().toString(iBuffer);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.link2string"),
            "Serialize link to string",
            timer);
        break;

      case EMBEDDEDSET:
        ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(
            ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
            null,
            iBuffer,
            null,
            null,
            iValue,
            null,
            true);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.embedSet2string"),
            "Serialize embeddedset to string",
            timer);
        break;

      case EMBEDDEDLIST:
        ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(
            ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
            null,
            iBuffer,
            null,
            null,
            iValue,
            null,
            true);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.embedList2string"),
            "Serialize embeddedlist to string",
            timer);
        break;

      case EMBEDDEDMAP:
        ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapToStream(
            ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
            null,
            iBuffer,
            null,
            null,
            iValue,
            null,
            true);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.embedMap2string"),
            "Serialize embeddedmap to string",
            timer);
        break;

      case EMBEDDED:
        OStringSerializerEmbedded.INSTANCE.toStream(iBuffer, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.embed2string"),
            "Serialize embedded to string",
            timer);
        break;

      case CUSTOM:
        OStringSerializerAnyStreamable.INSTANCE.toStream(iBuffer, iValue);
        PROFILER.stopChrono(
            PROFILER.getProcessMetric("serializer.record.string.custom2string"),
            "Serialize custom to string",
            timer);
        break;

      default:
        throw new IllegalArgumentException(
            "Type " + iType + " not supported to convert value: " + iValue);
    }
  }

  /**
   * Parses a string returning the closer type. Numbers by default are INTEGER if haven't decimal
   * separator, otherwise FLOAT. To treat all the number types numbers are postponed with a
   * character that tells the type: b=byte, s=short, l=long, f=float, d=double, t=date.
   *
   * @param iUnusualSymbols Localized decimal number separators
   * @param iValue Value to parse
   * @return The closest type recognized
   */
  public static OType getType(final String iValue) {
    if (iValue.length() == 0) return null;

    final char firstChar = iValue.charAt(0);

    if (firstChar == ORID.PREFIX)
      // RID
      return OType.LINK;
    else if (firstChar == '\'' || firstChar == '"') return OType.STRING;
    else if (firstChar == OStringSerializerHelper.BINARY_BEGINEND) return OType.BINARY;
    else if (firstChar == OStringSerializerHelper.EMBEDDED_BEGIN) return OType.EMBEDDED;
    else if (firstChar == OStringSerializerHelper.LINK) return OType.LINK;
    else if (firstChar == OStringSerializerHelper.COLLECTION_BEGIN) return OType.EMBEDDEDLIST;
    else if (firstChar == OStringSerializerHelper.MAP_BEGIN) return OType.EMBEDDEDMAP;
    else if (firstChar == OStringSerializerHelper.CUSTOM_TYPE) return OType.CUSTOM;

    // BOOLEAN?
    if (iValue.equalsIgnoreCase("true") || iValue.equalsIgnoreCase("false")) return OType.BOOLEAN;

    // NUMBER OR STRING?
    boolean integer = true;
    for (int index = 0; index < iValue.length(); ++index) {
      final char c = iValue.charAt(index);
      if (c < '0' || c > '9')
        if ((index == 0 && (c == '+' || c == '-'))) continue;
        else if (c == DECIMAL_SEPARATOR) integer = false;
        else {
          if (index > 0)
            if (!integer && c == 'E') {
              // CHECK FOR SCIENTIFIC NOTATION
              if (index < iValue.length()) {
                if (iValue.charAt(index + 1) == '-')
                  // JUMP THE DASH IF ANY (NOT MANDATORY)
                  index++;
                continue;
              }
            } else if (c == 'f') return OType.FLOAT;
            else if (c == 'c') return OType.DECIMAL;
            else if (c == 'l') return OType.LONG;
            else if (c == 'd') return OType.DOUBLE;
            else if (c == 'b') return OType.BYTE;
            else if (c == 'a') return OType.DATE;
            else if (c == 't') return OType.DATETIME;
            else if (c == 's') return OType.SHORT;

          return OType.STRING;
        }
    }

    if (integer) {
      // AUTO CONVERT TO LONG IF THE INTEGER IS TOO BIG
      final int numberLength = iValue.length();
      if (numberLength > MAX_INTEGER_DIGITS
          || (numberLength == MAX_INTEGER_DIGITS && iValue.compareTo(MAX_INTEGER_AS_STRING) > 0))
        return OType.LONG;
    }

    return integer ? OType.INTEGER : OType.FLOAT;
  }

  /**
   * Parses the field type char returning the closer type. Default is STRING. b=binary if
   * iValue.lenght() >= 4 b=byte if iValue.lenght() <= 3 s=short, l=long f=float d=double a=date
   * t=datetime
   *
   * @param iValue Value to parse
   * @param iCharType Char value indicating the type
   * @return The closest type recognized
   */
  public static OType getType(final String iValue, final char iCharType) {
    if (iCharType == 'f') return OType.FLOAT;
    else if (iCharType == 'c') return OType.DECIMAL;
    else if (iCharType == 'l') return OType.LONG;
    else if (iCharType == 'd') return OType.DOUBLE;
    else if (iCharType == 'b') {
      if (iValue.length() >= 1 && iValue.length() <= 3) return OType.BYTE;
      else return OType.BINARY;
    } else if (iCharType == 'a') return OType.DATE;
    else if (iCharType == 't') return OType.DATETIME;
    else if (iCharType == 's') return OType.SHORT;

    return OType.STRING;
  }

  /**
   * Parses a string returning the value with the closer type. Numbers by default are INTEGER if
   * haven't decimal separator, otherwise FLOAT. To treat all the number types numbers are postponed
   * with a character that tells the type: b=byte, s=short, l=long, f=float, d=double, t=date. If
   * starts with # it's a RecordID. Most of the code is equals to getType() but has been copied to
   * speed-up it.
   *
   * @param iUnusualSymbols Localized decimal number separators
   * @param iValue Value to parse
   * @return The closest type recognized
   */
  public static Object getTypeValue(final String iValue) {
    if (iValue == null) return null;

    if (iValue.length() == 0) return "";

    if (iValue.length() > 1)
      if (iValue.charAt(0) == '"' && iValue.charAt(iValue.length() - 1) == '"')
        // STRING
        return OStringSerializerHelper.decode(iValue.substring(1, iValue.length() - 1));
      else if (iValue.charAt(0) == OStringSerializerHelper.BINARY_BEGINEND
          && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.BINARY_BEGINEND)
        // STRING
        return OStringSerializerHelper.getBinaryContent(iValue);
      else if (iValue.charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN
          && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.COLLECTION_END) {
        // COLLECTION
        final ArrayList<String> coll = new ArrayList<String>();
        OStringSerializerHelper.getCollection(iValue, 0, coll);
        return coll;
      } else if (iValue.charAt(0) == OStringSerializerHelper.MAP_BEGIN
          && iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.MAP_END) {
        // MAP
        return OStringSerializerHelper.getMap(iValue);
      }

    if (iValue.charAt(0) == ORID.PREFIX)
      // RID
      return new ORecordId(iValue);

    boolean integer = true;
    char c;

    for (int index = 0; index < iValue.length(); ++index) {
      c = iValue.charAt(index);
      if (c < '0' || c > '9')
        if ((index == 0 && (c == '+' || c == '-'))) continue;
        else if (c == DECIMAL_SEPARATOR) integer = false;
        else {
          if (index > 0) {
            if (!integer && c == 'E') {
              // CHECK FOR SCIENTIFIC NOTATION
              if (index < iValue.length()) index++;
              if (iValue.charAt(index) == '-') continue;
            }

            final String v = iValue.substring(0, index);

            if (c == 'f') return new Float(v);
            else if (c == 'c') return new BigDecimal(v);
            else if (c == 'l') return new Long(v);
            else if (c == 'd') return new Double(v);
            else if (c == 'b') return new Byte(v);
            else if (c == 'a' || c == 't') return new Date(Long.parseLong(v));
            else if (c == 's') return new Short(v);
          }
          return iValue;
        }
    }

    if (integer) {
      try {
        return new Integer(iValue);
      } catch (NumberFormatException e) {
        return new Long(iValue);
      }
    } else return new BigDecimal(iValue);
  }

  public static Object simpleValueFromStream(final Object iValue, final OType iType) {
    switch (iType) {
      case STRING:
        if (iValue instanceof String) {
          final String s = OStringSerializerHelper.getStringContent(iValue);
          return OStringSerializerHelper.decode(s);
        }
        return iValue.toString();

      case INTEGER:
        if (iValue instanceof Integer) return iValue;
        return new Integer(iValue.toString());

      case BOOLEAN:
        if (iValue instanceof Boolean) return iValue;
        return new Boolean(iValue.toString());

      case FLOAT:
        if (iValue instanceof Float) return iValue;
        return convertValue((String) iValue, iType);

      case DECIMAL:
        if (iValue instanceof BigDecimal) return iValue;
        return convertValue((String) iValue, iType);

      case LONG:
        if (iValue instanceof Long) return iValue;
        return convertValue((String) iValue, iType);

      case DOUBLE:
        if (iValue instanceof Double) return iValue;
        return convertValue((String) iValue, iType);

      case SHORT:
        if (iValue instanceof Short) return iValue;
        return convertValue((String) iValue, iType);

      case BYTE:
        if (iValue instanceof Byte) return iValue;
        return convertValue((String) iValue, iType);

      case BINARY:
        return OStringSerializerHelper.getBinaryContent(iValue);

      case DATE:
      case DATETIME:
        if (iValue instanceof Date) return iValue;
        return convertValue((String) iValue, iType);

      case LINK:
        if (iValue instanceof ORID) return iValue.toString();
        else if (iValue instanceof String) return new ORecordId((String) iValue);
        else return ((ORecord<?>) iValue).getIdentity().toString();
    }

    throw new IllegalArgumentException("Type " + iType + " is not simple type.");
  }

  public static void simpleValueToStream(
      final StringBuilder iBuffer, final OType iType, final Object iValue) {
    if (iValue == null || iType == null) return;
    switch (iType) {
      case STRING:
        iBuffer.append('"');
        iBuffer.append(OStringSerializerHelper.encode(iValue.toString()));
        iBuffer.append('"');
        break;

      case BOOLEAN:
        iBuffer.append(String.valueOf(iValue));
        break;

      case INTEGER:
        iBuffer.append(String.valueOf(iValue));
        break;

      case FLOAT:
        iBuffer.append(String.valueOf(iValue));
        iBuffer.append('f');
        break;

      case DECIMAL:
        if (iValue instanceof BigDecimal) iBuffer.append(((BigDecimal) iValue).toPlainString());
        else iBuffer.append(String.valueOf(iValue));
        iBuffer.append('c');
        break;

      case LONG:
        iBuffer.append(String.valueOf(iValue));
        iBuffer.append('l');
        break;

      case DOUBLE:
        iBuffer.append(String.valueOf(iValue));
        iBuffer.append('d');
        break;

      case SHORT:
        iBuffer.append(String.valueOf(iValue));
        iBuffer.append('s');
        break;

      case BYTE:
        if (iValue instanceof Character) iBuffer.append((int) ((Character) iValue).charValue());
        else if (iValue instanceof String)
          iBuffer.append(String.valueOf((int) ((String) iValue).charAt(0)));
        else iBuffer.append(String.valueOf(iValue));
        iBuffer.append('b');
        break;

      case BINARY:
        iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND);
        if (iValue instanceof Byte)
          iBuffer.append(OBase64Utils.encodeBytes(new byte[] {((Byte) iValue).byteValue()}));
        else iBuffer.append(OBase64Utils.encodeBytes((byte[]) iValue));
        iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND);
        break;

      case DATE:
        if (iValue instanceof Date) {
          // RESET HOURS, MINUTES, SECONDS AND MILLISECONDS
          Calendar calendar = Calendar.getInstance();
          calendar.setTime((Date) iValue);
          calendar.set(Calendar.HOUR_OF_DAY, 0);
          calendar.set(Calendar.MINUTE, 0);
          calendar.set(Calendar.SECOND, 0);
          calendar.set(Calendar.MILLISECOND, 0);

          iBuffer.append(calendar.getTimeInMillis());
        } else iBuffer.append(iValue);
        iBuffer.append('a');
        break;

      case DATETIME:
        if (iValue instanceof Date) iBuffer.append(((Date) iValue).getTime());
        else iBuffer.append(iValue);
        iBuffer.append('t');
        break;
    }
  }
}
 public void drop() {
   underlying.drop();
   Orient.instance().getDatabaseFactory().unregister(databaseOwner);
 }
 public <THISDB extends ODatabase> THISDB create() {
   underlying.create();
   Orient.instance().getDatabaseFactory().register(databaseOwner);
   return (THISDB) this;
 }
 public <THISDB extends ODatabase> THISDB open(
     final String iUserName, final String iUserPassword) {
   underlying.open(iUserName, iUserPassword);
   Orient.instance().getDatabaseFactory().register(databaseOwner);
   return (THISDB) this;
 }
Exemple #22
0
  private OClass doCreateClass(
      final String className, final int[] clusterIds, int retry, OClass... superClasses)
      throws ClusterIdsAreEmptyException {
    OClass result;

    final ODatabaseDocumentInternal db = getDatabase();
    final OStorage storage = db.getStorage();
    StringBuilder cmd = null;

    getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE);
    acquireSchemaWriteLock();
    try {

      final String key = className.toLowerCase();
      if (classes.containsKey(key) && retry == 0)
        throw new OSchemaException("Class " + className + " already exists in current database");

      if (!isDistributedCommand()) checkClustersAreAbsent(clusterIds);

      cmd = new StringBuilder("create class ");
      // if (getDatabase().getStorage().getConfiguration().isStrictSql())
      // cmd.append('`');
      cmd.append(className);
      // if (getDatabase().getStorage().getConfiguration().isStrictSql())
      // cmd.append('`');

      List<OClass> superClassesList = new ArrayList<OClass>();
      if (superClasses != null && superClasses.length > 0) {
        boolean first = true;
        for (OClass superClass : superClasses) {
          // Filtering for null
          if (superClass != null) {
            if (first) cmd.append(" extends ");
            else cmd.append(", ");
            cmd.append(superClass.getName());
            first = false;
            superClassesList.add(superClass);
          }
        }
      }

      if (clusterIds != null) {
        if (clusterIds.length == 1 && clusterIds[0] == -1) cmd.append(" abstract");
        else {
          cmd.append(" cluster ");
          for (int i = 0; i < clusterIds.length; ++i) {
            if (i > 0) cmd.append(',');
            else cmd.append(' ');

            cmd.append(clusterIds[i]);
          }
        }
      }

      if (isDistributedCommand()) {
        createClassInternal(className, clusterIds, superClassesList);

        final OAutoshardedStorage autoshardedStorage = (OAutoshardedStorage) storage;
        OCommandSQL commandSQL = new OCommandSQL(cmd.toString());
        commandSQL.addExcludedNode(autoshardedStorage.getNodeId());

        final Object res = db.command(commandSQL).execute();

      } else if (storage instanceof OStorageProxy) {
        db.command(new OCommandSQL(cmd.toString())).execute();
        reload();
      } else createClassInternal(className, clusterIds, superClassesList);

      result = classes.get(className.toLowerCase());

      // WAKE UP DB LIFECYCLE LISTENER
      for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners();
          it.hasNext(); ) it.next().onCreateClass(getDatabase(), result);

    } finally {
      releaseSchemaWriteLock();
    }

    return result;
  }
 public <RET extends Object> RET newInstance() {
   return (RET) Orient.instance().getRecordFactoryManager().newInstance(recordType);
 }
 protected ODatabaseDocumentTx createDatabaseInstance(String url) {
   return Orient.instance().getDatabaseFactory().createDatabase("graph", url);
 }