Java源码示例:com.orientechnologies.orient.core.Orient

示例1
@Before
public void setUp() throws Exception {
  entityHook = new EntityHook(eventManager);

  Orient.instance().addDbLifecycleListener(entityHook);

  OrientCapabilityStorageItemEntityAdapter entityAdapter = new OrientCapabilityStorageItemEntityAdapter();
  entityAdapter.enableObfuscation(new HexRecordIdObfuscator());
  entityAdapter.enableEntityHook(entityHook);

  this.underTest = new OrientCapabilityStorage(
      database.getInstanceProvider(),
      entityAdapter
  );

  underTest.start();
}
 
示例2
public static void main(final String[] args) throws Exception {

    // tweak levels to provide a smoother console experience
    LogManager.getLogManager().readConfiguration(Main.class.getResourceAsStream("/logging.properties"));

    OLogManager.instance().installCustomFormatter();

    // support property-based configuration of PbeCompression
    Injector injector = Guice.createInjector(new WireModule(binder -> {
      binder.bind(PbeCipherFactory.class).to(PbeCipherFactoryImpl.class);
      binder.bind(CryptoHelper.class).to(CryptoHelperImpl.class);
      binder.bind(PbeCompression.class);
    }));

    // register support for PBE compression; needed to work with the security database
    OCompressionFactory.INSTANCE.register(injector.getInstance(PbeCompression.class));

    // register 'ConflictHook' strategy but leave it disabled; needed to load databases that set it as a strategy
    Orient.instance().getRecordConflictStrategy().registerImplementation(ConflictHook.NAME, new ConflictHook(false));

    OConsoleDatabaseApp.main(args);
  }
 
示例3
@Test(enabled = false)
public void initDB() {

  try {
    server = OServerMain.create();
    server.startup(ClassLoader.getSystemResourceAsStream("orientdb-server-config.xml"));
    server.activate();
  } catch (Exception e) {
    e.printStackTrace();
  }
  databaseDocumentTx = new ODatabaseDocumentTx(url);
  if (!databaseDocumentTx.exists()) {
    databaseDocumentTx = Orient.instance().getDatabaseFactory().createDatabase("graph", url);
    databaseDocumentTx.create();
  } else {
    databaseDocumentTx.open("admin", "admin");
  }
}
 
示例4
@Before
public void setUp() throws Exception {
  entityHook = new EntityHook(eventManager);

  Orient.instance().addDbLifecycleListener(entityHook);

  OrientCleanupPolicyEntityAdapter entityAdapter = new OrientCleanupPolicyEntityAdapter();
  entityAdapter.enableObfuscation(new HexRecordIdObfuscator());
  entityAdapter.enableEntityHook(entityHook);

  underTest = new OrientCleanupPolicyStorage(database.getInstanceProvider(), entityAdapter);
  underTest.start();

  item = createPolicy();
}
 
示例5
private void registerConflictStrategies(final Iterable<ORecordConflictStrategy> strategies) {
  ORecordConflictStrategyFactory strategyFactory = Orient.instance().getRecordConflictStrategy();
  for (ORecordConflictStrategy strategy : strategies) {
    log.debug("Registering OrientDB conflict strategy {} as '{}'", strategy, strategy.getName());
    strategyFactory.registerImplementation(strategy.getName(), strategy);
  }
}
 
示例6
@Override
protected void doStop() throws Exception {
  try {
    // instance shutdown
    orientServer.shutdown();
    orientServer = null;
  }
  finally {
    // global shutdown
    Orient.instance().shutdown();
  }

  log.info("Shutdown");
}
 
示例7
public static void main(final String[] args) throws SQLException, IOException {
  if (args.length < 2) {
    System.err.println("Usage: java -jar nexus-orient-migrator.jar <plocal:component-db-path> <jdbc:target-db>"); // NOSONAR
    System.exit(1);
  }

  LogManager.getLogManager().readConfiguration(Main.class.getResourceAsStream("/logging.properties"));

  // register placeholder so we can load databases that use our custom conflict hook
  Orient.instance().getRecordConflictStrategy().registerImplementation("ConflictHook",
      new OVersionRecordConflictStrategy());

  HikariConfig hikariConfig = new HikariConfig();
  hikariConfig.setJdbcUrl(args[1]);

  if (hikariConfig.getJdbcUrl().contains("postgresql")) {
    // workaround https://github.com/pgjdbc/pgjdbc/issues/265
    hikariConfig.getDataSourceProperties().setProperty("stringtype", "unspecified");
  }

  try (ODatabaseDocumentTx componentDb = new ODatabaseDocumentTx(args[0])) {
    componentDb.open("admin", "admin");
    try (HikariDataSource targetDb = new HikariDataSource(hikariConfig)) {
      ContentMigrator migrator = new ContentMigrator(componentDb, targetDb.getConnection(), false);

     migrator.extractAll();
    }
  }
}
 
示例8
@Test(expected=OStorageException.class)
@Ignore
public void testMemoryDBShouldDisapear() throws Exception
{
	try
	{
		testOrientDbLifeCycle(MEMORY_DB_NAME, true, false);
		testOrientDbLifeCycle(MEMORY_DB_NAME, false, true);
	} finally
	{
		OServer server = OServerMain.server();
		if(server!=null) server.shutdown();
		Orient.instance().shutdown();
	}
}
 
示例9
public void testOrientDbLifeCycle(String dbURL, boolean createDb, boolean dropDb) throws Exception
	{
		Orient.instance().startup();
		assertNotNull(ODatabaseRecordThreadLocal.instance());
		Orient.instance().removeShutdownHook();
		OServer server = OServerMain.create();
		server.startup(OrientDbTestWebApplication.class.getResource("db.config.xml").openStream());
		server.activate();
		if(createDb)
		{
			ODatabaseDocument dbToCreate = new ODatabaseDocumentTx(dbURL);
			if(!dbToCreate.exists()) dbToCreate.create();
			dbToCreate.close();
		}
		assertNotNull(ODatabaseRecordThreadLocal.instance());
		ODatabaseDocument db = new OPartitionedDatabasePoolFactory().get(dbURL, "admin", "admin").acquire();
		db.close();
		assertNotNull(ODatabaseRecordThreadLocal.instance());
		if(dropDb)
		{
			@SuppressWarnings("resource")
			ODatabaseDocument dbToDrop = new ODatabaseDocumentTx(dbURL);
			dbToDrop.open("admin", "admin");
			dbToDrop.drop();
		}
		server.shutdown();
		Orient.instance().shutdown();
//		Thread.sleep(50);
	}
 
示例10
protected void begin() {
  out(LOG_LEVELS.INFO, "BEGIN ETL PROCESSOR");

  final Integer cfgMaxRetries = (Integer) context.getVariable("maxRetries");
  if (cfgMaxRetries != null)
    maxRetries = cfgMaxRetries;

  final Integer dumpEveryMs = (Integer) context.getVariable("dumpEveryMs");
  if (dumpEveryMs != null && dumpEveryMs > 0) {
    dumpTask = new TimerTask() {
      @Override
      public void run() {
        dumpProgress();
      }
    };

    Orient.instance().scheduleTask(dumpTask, dumpEveryMs, dumpEveryMs);

    startTime = System.currentTimeMillis();
  }

  for (OBlock t : beginBlocks) {
    t.begin();
    t.execute();
    t.end();
  }

  if (source != null)
    source.begin();
  extractor.begin();
}
 
示例11
@Override
public void startup() {
  super.startup();
  Orient.instance().addDbLifecycleListener(this);

  OIndexes.registerFactory(new OLuceneIndexFactory(true));
  OSQLEngine.registerOperator(new OLuceneTextOperator());
  OSQLEngine.registerOperator(new OLuceneWithinOperator());
  OSQLEngine.registerOperator(new OLuceneNearOperator());
  OLogManager.instance().info(this, "Lucene index plugin installed and active. Lucene version: %s",
      OLuceneIndexManagerAbstract.LUCENE_VERSION);
}
 
示例12
protected void importGeometry(ODatabaseDocumentTx db, String file, final String clazz, String geomClazz) throws IOException {

    OClass points = db.getMetadata().getSchema().createClass(clazz);
    points.createProperty("geometry", OType.EMBEDDED, db.getMetadata().getSchema().getClass(geomClazz));
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    OIOUtils.copyStream(new FileInputStream(new File(file)), out, -1);
    ODocument doc = new ODocument().fromJSON(out.toString(), "noMap");
    List<ODocument> collection = doc.field("collection");

//    OShapeFactory builder = OShapeFactory.INSTANCE;

    final AtomicLong atomicLong = new AtomicLong(0);

    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        OLogManager.instance().info(this, clazz + " per second [%d]", atomicLong.get());
        atomicLong.set(0);
      }
    };
    Orient.instance().scheduleTask(task, 1000, 1000);
    for (ODocument entries : collection) {
      ODocumentInternal.removeOwner(entries, doc);
      ODocumentInternal.removeOwner(entries, (ORecordElement) collection);
      entries.setClassName(clazz);
      String wkt = entries.field("GeometryWkt");
      try {
//        ODocument location = builder.toDoc(wkt);
//        entries.field("geometry", location, OType.EMBEDDED);
//        db.save(entries);
//
//        atomicLong.incrementAndGet();
      } catch (Exception e) {

      }
    }
    task.cancel();
  }
 
示例13
protected static String getStoragePath(final String databaseName, final String storageMode) {
  final String path;
  if (storageMode.equals(OEngineLocalPaginated.NAME)) {
    path = storageMode + ":${" + Orient.ORIENTDB_HOME + "}/databases/" + databaseName;
  } else if (storageMode.equals(OEngineMemory.NAME)) {
    path = storageMode + ":" + databaseName;
  } else {
    return null;
  }
  return path;
}
 
示例14
public PageDelegate(WebPage page, ORID pageOrid, ORID docOrid) {
	this.page = page;
	this.pageDocumentModel = new ODocumentModel(pageOrid);
	ODocument doc = (ODocument)(docOrid!=null?docOrid.getRecord():pageDocumentModel.getObject().field(PagesModule.OPROPERTY_DOCUMENT));
	if(doc!=null) page.setDefaultModel(new ODocumentModel(doc));
	String script = pageDocumentModel.getObject().field(PagesModule.OPROPERTY_SCRIPT);
	if(!Strings.isEmpty(script)) {
		OScriptManager scriptManager = Orient.instance().getScriptManager();
		ODatabaseDocument db = OrienteerWebSession.get().getDatabase();
		final OPartitionedObjectPool.PoolEntry<ScriptEngine> entry = 
				scriptManager.acquireDatabaseEngine(db.getName(), "javascript");
		final ScriptEngine scriptEngine = entry.object;
		Bindings binding = null;
	    try {
			binding = scriptManager.bind(scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE), 
											(ODatabaseDocumentTx) db, null, null);
			binding.put("page", page);
			binding.put("pageDoc", pageDocumentModel.getObject());
			binding.put("doc", doc);
			try {
				scriptEngine.eval(script);
			} catch (ScriptException e) {
				scriptManager.throwErrorMessage(e, script);
			}
		} finally {
			if (scriptManager != null && binding != null) {
				scriptManager.unbind(binding, null, null);
				scriptManager.releaseDatabaseEngine("javascript", db.getName(), entry);
			}
		}
	}
}
 
示例15
private void startupIfEnginesAreMissing() {
    // Using a jdk which doesn't bundle a javascript engine
    // throws a NoClassDefFoundError while logging the warning
    // see https://github.com/orientechnologies/orientdb/issues/5855
    OLogManager.instance().setWarnEnabled(false);

    // If an instance of Orient was previously shutdown all engines are removed.
    // We need to startup Orient again.
    if (Orient.instance().getEngines().isEmpty()) {
        Orient.instance().startup();
    }
    OLogManager.instance().setWarnEnabled(true);
}
 
示例16
@Override
protected void doStart() throws Exception {
  Orient.instance().startup();
  Orient.instance().removeShutdownHook();
}
 
示例17
@Override
protected void doStop() throws Exception {
  Orient.instance().shutdown();
}
 
示例18
/**
 * Stop underlying server outside of normal lifecycle in order to test failure situations.
 */
public void stopAbnormally() {
  Orient.instance().shutdown();
}
 
示例19
/**
 * Tests configuring the server w/o xml but configuring the JAXB objects directly.
 */
@SuppressWarnings("java:S2699") //sonar wants assertions, but this test is not run in CI
@Test
public void embeddedServerProgrammatic() throws Exception {
  File homeDir = util.createTempDir("orientdb-home").getCanonicalFile();
  System.setProperty("orient.home", homeDir.getPath());
  System.setProperty(Orient.ORIENTDB_HOME, homeDir.getPath());

  OServer server = new OServer();
  OServerConfiguration config = new OServerConfiguration();

  // Unsure what this is used for, its apparently assigned to xml location, but forcing it here
  config.location = "DYNAMIC-CONFIGURATION";

  File databaseDir = new File(homeDir, "db");
  config.properties = new OServerEntryConfiguration[] {
      new OServerEntryConfiguration("server.database.path", databaseDir.getPath())
  };

  config.handlers = Lists.newArrayList();

  config.hooks = Lists.newArrayList();

  config.network = new OServerNetworkConfiguration();
  config.network.protocols = Lists.newArrayList(
      new OServerNetworkProtocolConfiguration("binary", ONetworkProtocolBinary.class.getName())
  );

  OServerNetworkListenerConfiguration binaryListener = new OServerNetworkListenerConfiguration();
  binaryListener.ipAddress = "0.0.0.0";
  binaryListener.portRange = "2424-2430";
  binaryListener.protocol = "binary";
  binaryListener.socket = "default";

  config.network.listeners = Lists.newArrayList(
      binaryListener
  );

  config.storages = new OServerStorageConfiguration[] {};

  config.users = new OServerUserConfiguration[] {
      new OServerUserConfiguration("admin", "admin", "*")
  };

  config.security = new OServerSecurityConfiguration();
  config.security.users = Lists.newArrayList();
  config.security.resources = Lists.newArrayList();

  server.startup(config);

  // Dump config to log stream
  StringWriter buff = new StringWriter();
  OGlobalConfiguration.dumpConfiguration(new PrintStream(new WriterOutputStream(buff), true));
  log("Global configuration:\n{}", buff);

  server.activate();
  server.shutdown();
}
 
示例20
@Override
protected void doStart() throws Exception {

  // global startup
  Orient.instance().startup();

  // instance startup
  OServer server = new OServer(false)
  {
    @Override
    public Map<String, String> getAvailableStorageNames() {
      return getExistingDatabaseUrls();
    }
  };

  configureOrientMinimumLogLevel();
  server.setExtensionClassLoader(uberClassLoader);
  OServerConfiguration config = createConfiguration();
  server.startup(config);

  // remove Orient shutdown-hooks added during startup, we'll manage shutdown ourselves
  Orient.instance().removeShutdownHook();
  server.removeShutdownHook();

  // create default root user to avoid orientdb prompt on console
  server.addUser(OServerConfiguration.DEFAULT_ROOT_USER, null, "*");

  // Log global configuration
  if (log.isDebugEnabled()) {
    // dumpConfiguration() only accepts ancient stream api
    String encoding = StandardCharsets.UTF_8.name();
    ByteArrayOutputStream buff = new ByteArrayOutputStream();
    OGlobalConfiguration.dumpConfiguration(new PrintStream(buff, true, encoding));
    log.debug("Global configuration:\n{}", new String(buff.toByteArray(), encoding));
  }

  Orient.instance().addDbLifecycleListener(entityHook);

  server.activate();
  log.info("Activated");

  this.orientServer = server;
}
 
示例21
private OServerConfiguration createConfiguration() {
  File configDir = applicationDirectories.getConfigDirectory("fabric");

  // FIXME: Unsure what this directory is used for
  File orientDir = applicationDirectories.getWorkDirectory("orient");
  System.setProperty("orient.home", orientDir.getPath());
  System.setProperty(Orient.ORIENTDB_HOME, orientDir.getPath());

  OServerConfiguration config = new OServerConfiguration();

  // FIXME: Unsure what this is used for, its apparently assigned to xml location, but forcing it here
  config.location = "DYNAMIC-CONFIGURATION";

  File securityFile = new File(configDir, "orientdb-security.json");

  config.properties = new OServerEntryConfiguration[]{
      new OServerEntryConfiguration("server.database.path", databasesDir.getPath()),
      new OServerEntryConfiguration("server.security.file", securityFile.getPath()),
      new OServerEntryConfiguration("plugin.dynamic", String.valueOf(dynamicPlugins))
  };

  config.handlers = new ArrayList<>(injectedHandlers);
  config.hooks = new ArrayList<>();

  config.network = new OServerNetworkConfiguration();
  config.network.protocols = Lists.newArrayList(
      new OServerNetworkProtocolConfiguration("binary", ONetworkProtocolBinary.class.getName()),
      new OServerNetworkProtocolConfiguration("http", ONetworkProtocolHttpDb.class.getName())
  );

  config.network.listeners = new ArrayList<>();

  OServerNetworkListenerConfiguration binaryListener = null, httpListener = null;

  if (binaryListenerEnabled) {
    binaryListener = createBinaryListener(binaryPortRange);
    config.network.listeners.add(binaryListener);
  }

  if (httpListenerEnabled) {
    httpListener = createHttpListener(httpPortRange);
    config.network.listeners.add(httpListener);
  }

  config.storages = new OServerStorageConfiguration[]{};

  config.users = new OServerUserConfiguration[]{
      new OServerUserConfiguration("admin", "admin", "*")
  };

  config.security = new OServerSecurityConfiguration();
  config.security.users = new ArrayList<>();
  config.security.resources = new ArrayList<>();

  // latest advice is to disable DB compression as it doesn't buy much,
  // also snappy has issues with use of native lib (unpacked under tmp)
  OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.setValue("nothing");
  
  // ensure we don't set a file lock, which can behave badly on NFS https://issues.sonatype.org/browse/NEXUS-11289
  OGlobalConfiguration.FILE_LOCK.setValue(false);

  // disable auto removal of servers, SharedHazelcastPlugin removes gracefully shutdown nodes but for crashes and
  // especially network partitions we don't want the write quorum getting lowered and endanger consistency 
  OGlobalConfiguration.DISTRIBUTED_AUTO_REMOVE_OFFLINE_SERVERS.setValue(-1);

  // Apply customizations to server configuration
  configCustomizers.forEach((it) -> it.apply(config));

  if (binaryListener != null) {
    log.info("Binary listener enabled: {}:[{}]", binaryListener.ipAddress, binaryListener.portRange);
  }

  if (httpListener != null) {
    log.info("HTTP listener enabled: {}:[{}]", httpListener.ipAddress, httpListener.portRange);
  }

  return config;
}
 
示例22
@Override
public ODatabaseThreadLocalFactory getDatabaseThreadLocalFactory() {
	return Orient.instance().getDatabaseThreadFactory();
}
 
示例23
@Override
public void setDatabaseThreadLocalFactory(
		ODatabaseThreadLocalFactory factory) {
	Orient.instance().registerThreadDatabaseFactory(factory);
}
 
示例24
public String getOrientDBVersion() 
{
	return Orient.class.getPackage().getImplementationVersion();
}
 
示例25
public OLuceneIndexManagerAbstract() {
  super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), OGlobalConfiguration.MVRBTREE_TIMEOUT
      .getValueAsInteger(), true);
  Orient.instance().registerListener(this);
}
 
示例26
public OLuceneIndexFactory(boolean manual) {
  if (!manual) {
    Orient.instance().addDbLifecycleListener(this);
  }
}
 
示例27
public static void scheduleTask(ONotificationTask task, Date firstTime, long period) {
  stopTask(task.getName());
  TASKS.put(task.getName(), task);
  Orient.instance().scheduleTask(task, firstTime, period);
}
 
示例28
public static void scheduleTask(ONotificationTask task, long delay, long period) {
  stopTask(task.getName());
  TASKS.put(task.getName(), task);
  Orient.instance().scheduleTask(task, delay, period);
}