com.orientechnologies.orient.core.db.document.ODatabaseDocument Java Examples

The following examples show how to use com.orientechnologies.orient.core.db.document.ODatabaseDocument. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocumentPool.java    From guice-persist-orient with MIT License 6 votes vote down vote up
@Override
public ODatabaseDocument get() {
    // lazy get: pool transaction will start not together with TransactionManager one, but as soon as
    // connection requested to avoid using connections of not used pools
    Preconditions.checkNotNull(pool, String.format("Pool %s not initialized", getType()));
    if (transaction.get() == null) {
        Preconditions.checkState(transactionManager.isTransactionActive(), String.format(
                "Can't obtain connection from pool %s: no transaction defined.", getType()));
        if (transactionManager.isExternalTransaction()) {
            // external mode: use already created connection
            transaction.set(ODatabaseRecordThreadLocal.instance().get());
            logger.trace("Pool {} use bound to thread connection (external mode)", getType());
        } else {
            // normal mode: create connection
            final ODatabaseDocument db = checkAndAcquireConnection();

            db.begin(transactionManager.getActiveTransactionType());
            transaction.set(db);
            logger.trace("Pool {} transaction started", getType());
        }
    }
    return (ODatabaseDocument) checkOpened(transaction.get()).activateOnCurrentThread();
}
 
Example #2
Source File: OTaskSession.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public void atomicChange(final String field, final Object value,final String changeCommand){
	new DBClosure<Boolean>() {
		@Override
		protected Boolean execute(ODatabaseDocument db) {
			int maxRetries = 50;
			OCommandSQL command = new OCommandSQL("update "+document.getIdentity()+" "+changeCommand);
			int retry = 0;					
			while(true){
				try {
					command.execute(value);
					break;
				} catch (OConcurrentModificationException  e) {
					retry++;
					try { Thread.sleep((long) (Math.random()*150));} catch (InterruptedException e1) {}
					if (retry>=maxRetries){
						throw e;//if all retries failed
					}
				}
			}
			document.reload();
			return true;
		}
	}.execute();
}
 
Example #3
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Ignore //TODO: Uncomment when OrientDB issue will be fixed: https://github.com/orientechnologies/orientdb/issues/8067
@Test
public void testLinkToOUser() {
	ODatabaseDocument db = wicket.getTester().getDatabase();
	OSchema schema = db.getMetadata().getSchema();
	final OClass classA = schema.createClass("TestLinkToOUser");
	classA.createProperty("name", OType.STRING);
	classA.createProperty("user", OType.LINK).setLinkedClass(schema.getClass("OUser"));
	ORID userRid = new ORecordId("#5:0");
	ODocument doc = new ODocument(classA);
	wicket.getTester().signIn("writer", "writer");
	db = wicket.getTester().getDatabase();
	db.begin();
	ODocument userDoc = userRid.getRecord();
	userDoc.field("roles");
	doc.field("Admin");
	doc.field("user", userDoc);
	doc.save();
	db.commit();
}
 
Example #4
Source File: DBClosure.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
/**
 * @return result of execution
 */
public final V execute()
{
	ODatabaseDocument db = null;
	ODatabaseRecordThreadLocal orientDbThreadLocal = ODatabaseRecordThreadLocal.instance();
	ODatabaseDocument oldDb = orientDbThreadLocal.getIfDefined();
	if(oldDb!=null) orientDbThreadLocal.remove(); //Required to avoid stack of transactions
	try
	{
		db = getSettings().getDatabasePoolFactory().get(getDBUrl(), getUsername(), getPassword()).acquire();
		db.activateOnCurrentThread();
		return execute(db);
	} 
	finally
	{
		if(db!=null) db.close();
		if(oldDb!=null) orientDbThreadLocal.set((ODatabaseDocumentInternal)oldDb);
		else orientDbThreadLocal.remove();
	}
}
 
Example #5
Source File: OMetricsModule.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
	public void onInitialize(OrienteerWebApplication app, ODatabaseDocument db) {
		super.onInitialize(app, db);
		DefaultExports.initialize();
		OMetricsRequestCycleListener.install(app);
		OMetricSessionListener.install(app);
		new OMetricsOrientDB().register();
//		OPerformanceStatisticManager psm = OMetricsOrientDB.getPerformanceStatisticManager();
		//WorkAround to avoid NPEs in logs
		//TODO: Remove when https://github.com/orientechnologies/orientdb/issues/9169 will be fixed
//		psm.startThreadMonitoring();
//		psm.getSessionPerformanceStatistic().startWALFlushTimer();
//		psm.getSessionPerformanceStatistic().stopWALFlushTimer();
//		psm.stopThreadMonitoring();
		//End of block to delete after issue fixing
		
//		psm.startMonitoring();
		app.mountPackage(OMetricsModule.class.getPackage().getName());
	}
 
Example #6
Source File: GoogleUserManager.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public OrienteerUser createUser(ODatabaseDocument db, JsonNode node) {
    String email = node.get(FIELD_EMAIL).textValue();

    OrienteerUser user = new OrienteerUser();
    user.setFirstName(node.get(FIELD_GIVEN_NAME).textValue())
            .setLastName(node.get(FIELD_FAMILY_NAME).textValue())
            .setEmail(email);
    user.setName(email);
    user.setPassword(UUID.randomUUID().toString());
    user.setAccountStatus(OSecurityUser.STATUSES.ACTIVE);
    user.save();

    OUsersCommonUtils.createOUserSocialNetworkIfNotExists(db, OAuth2Provider.GOOGLE, getGoogleId(node), user);

    return user;
}
 
Example #7
Source File: TestNotificationFactories.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@After
@Sudo
public void destroy() {
  ODatabaseDocument db = ODatabaseRecordThreadLocal.instance().get();
  for (int i = 1; i <= 10; i++) {
    try {
      db.begin();
      db.delete(testNotification.getDocument());
      db.commit();
      break;
    } catch (Exception e) {
      if (i == 10) {
        throw new IllegalStateException(e);
      }
    }
  }
}
 
Example #8
Source File: OrienteerLocalizationModule.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public String loadStringResource(final String key, Locale locale, final String style, final String variation)
{
	if(Strings.isEmpty(key)) {
		System.out.println("Empty!");
	}

	final String language = locale!=null?locale.getLanguage():null;
	return new DBClosure<String>() {

		@Override
		protected String execute(ODatabaseDocument db) {
			String ret = sudoLoadStringResource(db, true, key, language, style, variation);
			return ret!=null || DEFAULT_LANGUAGE.equals(language) ? ret : sudoLoadStringResource(db, false, key, DEFAULT_LANGUAGE, style, variation);
		}
	}.execute();
}
 
Example #9
Source File: OLoggerModuleRepository.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
public static OLoggerModule.Module getModule(ODatabaseDocument db) {
    String sql = String.format("select from %s where %s = ?", OLoggerModule.Module.CLASS_NAME, OLoggerModule.OMODULE_NAME);
    List<OIdentifiable> identifiables = db.query(new OSQLSynchQuery<>(sql, 1), OLoggerModule.NAME);
    return CommonUtils.getDocument(identifiables)
            .map(OLoggerModule.Module::new)
            .orElseThrow(() -> new IllegalStateException("There is no module with name: " + OLoggerModule.NAME + " in database"));
}
 
Example #10
Source File: TestSendNotificationTask.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Before
@Sudo
public void init() {
  ONotificationScheduler.stopAll();

  ODatabaseDocument db = ODatabaseRecordThreadLocal.instance().get();

  ODocument mailTransport = notificationDAO.findTransportByAlias(TestDataModule.TRANSPORT_MAIL);

  if (mailTransport == null) {
    throw new IllegalStateException("There is no transport with alias: " + TestDataModule.TRANSPORT_MAIL);
  }

  OMail mail = OMailUtils.getOMailByName(TestDataModule.MAIL_TEST)
          .orElseThrow(IllegalStateException::new);

  notifications = new LinkedList<>();

  for (int i = 0; i < NOTIFICATIONS; i++) {
    db.begin();
    OPreparedMail preparedMail = new OPreparedMail(mail);
    IOMailNotification notification = DAO.create(IOMailNotification.class);
    notification.fromStream(new ODocument(IOMailNotification.CLASS_NAME));
    notification.setTransport(mailTransport);
    notification.setPreparedMail(preparedMail.getDocument());
    preparedMail.addRecipient("[email protected]");
    preparedMail.save();
    notification.save();
    notifications.add(notification);
    db.commit();
  }
}
 
Example #11
Source File: GitHubUserManager.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private OrienteerUser getUserByGitHubId(ODatabaseDocument db, JsonNode node) {
    String id = getGitHubId(node);
    if (id != null) {
        return OUserSocialNetworkRepository.getSocialNetworkByUserId(db, OAuth2Provider.GITHUB, id)
                .map(OUserSocialNetwork::getUser)
                .orElse(null);
    }
    return null;
}
 
Example #12
Source File: ModuledDataInstallator.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onBeforeDestroyed(Application application) {
	super.onBeforeDestroyed(application);
	OrienteerWebApplication app = (OrienteerWebApplication)application;
	ODatabaseDocument db = (ODatabaseDocument)getDatabase(app);
	try
	{
		Map<String, ODocument> installedModules = getInstalledModules(db);
		for(IOrienteerModule module: app.getRegisteredModules())
		{
			try
			{
				db.begin();
				module.onDestroy(app, db, installedModules.get(module.getName()));
				db.commit();
			} catch (Exception e)
			{
				LOG.error("Exception during destroying module '"+module.getName()+"'", e);
				db.rollback();
			}
		}
	} 
	finally
	{
		db.close();
	}
}
 
Example #13
Source File: OCamelTaskSession.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
/**
 * Register fields in db 
 */
public static final void onInstallModule(OrienteerWebApplication app, ODatabaseDocument db){
	OSchemaHelper helper = OSchemaHelper.bind(db);
	helper.oClass(TASK_SESSION_CLASS,OTaskSessionRuntime.TASK_SESSION_CLASS);
		helper.oProperty(ITaskSession.Field.THREAD_NAME.fieldName(),OType.STRING,10).markAsDocumentName();
		helper.oProperty(Field.CONFIG.fieldName(),Field.CONFIG.type(),35).markAsLinkToParent();
		helper.oProperty(Field.OUTPUT.fieldName(),Field.OUTPUT.type(),37).assignVisualization("textarea");
}
 
Example #14
Source File: OUsersCommonUtils.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
public static void createWidgetIfNotExists(ODatabaseDocument db, String typeId, String className, String domain, String tab) {
    ODocument dashboard = getOrCreateDashboard(db, className, domain, tab);
    if (!isWidgetExists(dashboard, typeId)) {
        ODocument doc = new ODocument(OCLASS_WIDGET);
        doc.field(OPROPERTY_TYPE_ID, typeId);
        doc.field(OPROPERTY_DASHBOARD, dashboard);
        doc.save();
    }
}
 
Example #15
Source File: NotificationService.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void send(List<ODocument> notifications) {
  if (notifications == null || notifications.isEmpty()) {
    return;
  }
  ODatabaseDocument db = ODatabaseRecordThreadLocal.instance().get();

  IONotification notification = DAO.create(IONotification.class);
  IONotificationTransport transportWrapper = DAO.create(IONotificationTransport.class);

  notifications.forEach(notificationDoc -> {
    notification.fromStream(notificationDoc);
    transportWrapper.fromStream(notification.getTransport());
    ITransport transport = transportPool.acquire(transportWrapper.getAlias(), transportWrapper::createTransportService);

    for (int i = 1; i <= ATTEMPTS; i++) {
      try {
        if (i == 1) {
          handleSendingNotificationStatus(db, notification);
        }
        LOG.info("Send notification: {} {}", Thread.currentThread().getName(), notification.getDocument());
        transport.send(notificationDoc);
        handleSentNotificationStatus(db, notification);
        transportPool.release(transportWrapper.getAlias(), transport);
        break;
      } catch (Exception e) {
        if (i == ATTEMPTS) {
          handleFailedNotificationStatus(db, notification, e);
        }
      }
    }
  });
}
 
Example #16
Source File: TestNotificationLifecycle.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@After
@Sudo
public void destroy() {
  ODatabaseDocument db = ODatabaseRecordThreadLocal.instance().get();
  for (int i = 0; i < 10; i++) {
    try {
      db.delete(testNotification.getDocument());
      break;
    } catch (Exception e) {
      testNotification.reload();
    }
  }

}
 
Example #17
Source File: Module.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onDestroy(OrienteerWebApplication app, ODatabaseDocument db) {
	super.onDestroy(app, db);
	app.unmountPages("org.orienteer.camel.web");
	//app.unregisterWidgets("org.orienteer.camel.widget");
	
	OMethodsManager.get().removeModule(Module.class);
	OMethodsManager.get().reload();
}
 
Example #18
Source File: OTwilioModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onDestroy(OrienteerWebApplication app, ODatabaseDocument db) {
  super.onDestroy(app, db);
  app.getOrientDbSettings().getORecordHooks().remove(OPreparedSMSHook.class);

  app.unmountPackage("org.orienteer.twilio.resource");
}
 
Example #19
Source File: UserManager.java    From guice-persist-orient with MIT License 5 votes vote down vote up
@Inject
public UserManager(final TransactionManager transactionManager,
                   final Provider<ODatabaseDocument> connectionProvider,
                   final OrientDBFactory dbInfo) {
    this.transactionManager = transactionManager;
    this.connectionProvider = connectionProvider;
    this.defaultUser = create(dbInfo.getUser(), dbInfo.getPassword());
}
 
Example #20
Source File: OTasksTest.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void consoleTaskTest() throws Exception{
	assertTrue(OrientDbWebSession.get().signIn("admin", "admin"));
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
	assertFalse(db.isClosed());
	db.commit();
	try
	{
		ODocument taskDocument = new ODocument(OConsoleTask.TASK_CLASS);
		taskDocument.field(OTask.Field.AUTODELETE_SESSIONS.fieldName(),false);
		taskDocument.field(OConsoleTask.Field.INPUT.fieldName(),CONSOLE_TEST_COMMAND);
		taskDocument.save();
		db.commit();
		OTask task = OTask.makeFromODocument(taskDocument);

		ODocument taskDocumentAD = new ODocument(OConsoleTask.TASK_CLASS);
		taskDocumentAD.field(OTask.Field.AUTODELETE_SESSIONS.fieldName(),true);
		taskDocumentAD.field(OConsoleTask.Field.INPUT.fieldName(),CONSOLE_TEST_COMMAND);
		taskDocumentAD.save();
		db.commit();
		OTask taskAD = OTask.makeFromODocument(taskDocumentAD);
		
		OTaskSessionRuntime taskSession = task.startNewSession();
		OTaskSessionRuntime taskSessionAD = taskAD.startNewSession();
		Thread.sleep(CONSOLE_TASK_DELAY);
		db.commit();
		ODocument taskSessionDoc = taskSession.getOTaskSessionPersisted().getDocument();
		taskSessionDoc.load();
		assertNull(taskSessionDoc.field(ITaskSession.Field.ERROR.fieldName()));
		assertNotNull(taskSessionDoc.field(ITaskSession.Field.FINISH_TIMESTAMP.fieldName()));
		assertEquals(12L, (Object) taskSessionDoc.field(ITaskSession.Field.PROGRESS_CURRENT.fieldName()));
		assertEquals(ITaskSession.Status.INTERRUPTED,taskSession.getStatus());
	} finally
	{
		OrientDbWebSession.get().signOut();
	}
}
 
Example #21
Source File: OrientDbUtils.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public static void dropClass(ODatabaseDocument database, String className) {
    OSchema schema = database.getMetadata().getSchema();
    if (schema.existsClass(className)) {
        database.command(new OCommandSQL("DELETE FROM " + className)).execute();
        schema.dropClass(className);
    }
}
 
Example #22
Source File: ODatabaseMetaPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setValue(ODatabase<?> entity, String critery, V value) {
    ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
    db.commit();
    try
    {
        if(ATTRIBUTES.CLUSTERSELECTION.name().equals(critery))
        {
            if(value!=null) entity.set(ATTRIBUTES.valueOf(critery), value.toString());
        } else if(ATTRIBUTES.CUSTOM.name().equals(critery)) { 
        	if(value!=null) {
        		String stringValue = value.toString();
        		String[] customs = stringValue.split("\\r?\\n");
        		for (String custom : customs) {
		if(custom.indexOf('=')>0) entity.set(ATTRIBUTES.CUSTOM, custom);
	}
        	} else {
        		entity.set(ATTRIBUTES.CUSTOM, "clear");
        	}
        }else {
            entity.set(ATTRIBUTES.valueOf(critery), value);
        }
    } finally
    {
        db.begin();
    }
}
 
Example #23
Source File: OConsoleTasksModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public ODocument onInstall(OrienteerWebApplication app, ODatabaseDocument db) {
	OSchemaHelper helper = OSchemaHelper.bind(db);
	helper.oClass(OConsoleTask.TASK_CLASS,OTask.TASK_CLASS)
			.oProperty(OConsoleTask.Field.INPUT.fieldName(),OType.STRING,25);
	OTask.TASK_JAVA_CLASS_ATTRIBUTE.setValue(db.getMetadata().getSchema().getClass(OConsoleTask.TASK_CLASS), OConsoleTask.class.getName());
	
	helper.oClass(OConsoleTaskSession.TASK_SESSION_CLASS,OTaskSessionRuntime.TASK_SESSION_CLASS)
			.oProperty("in",OType.STRING,35).markAsDocumentName()
			.oProperty("out",OType.STRING,37).assignVisualization("textarea");
	return null;
}
 
Example #24
Source File: ModuledDataInstallator.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void installData(OrientDbWebApplication application, ODatabaseDocument database) {
	OrienteerWebApplication app = (OrienteerWebApplication)application;
	ODatabaseDocument db = (ODatabaseDocument)database;
	updateOModuleSchema(db);
	loadOrienteerModules(app, db);
	app.getOrientDbSettings().getORecordHooks().add(OModulesHook.class);
}
 
Example #25
Source File: OToursModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public ODocument onInstall(OrienteerWebApplication app, ODatabaseDocument db) {
	super.onInstall(app, db);
	OSchemaHelper helper = OSchemaHelper.bind(db);
	helper.describeAndInstallSchema(IOTour.class, IOTourStep.class);
	return null;
}
 
Example #26
Source File: ONotificationModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onInitialize(OrienteerWebApplication app, ODatabaseDocument db, ODocument moduleDoc) {
  super.onInitialize(app, db, moduleDoc);

  List<Class<? extends ORecordHook>> hooks = app.getOrientDbSettings().getORecordHooks();
  hooks.add(ONotificationHook.class);

  long period = new Module(moduleDoc).getSendPeriod();

  ONotificationScheduler.scheduleTask(new ONotificationSendTask(), period);
}
 
Example #27
Source File: BPMModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onInitialize(OrienteerWebApplication app, ODatabaseDocument db) {
	super.onInitialize(app, db);
	app.mountPages("org.orienteer.bpm.web");
	OProcessApplication processApplication = new OProcessApplication();
	processApplication.deploy();
	processApplicationReference = processApplication.getReference();
	app.registerWidgets("org.orienteer.bpm.component.widget");
	app.getOrientDbSettings().getORecordHooks().add(BpmnHook.class);
}
 
Example #28
Source File: GoogleUserManager.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private OrienteerUser getUserById(ODatabaseDocument db, String id) {
    if (id != null) {
        return OUserSocialNetworkRepository.getSocialNetworkByUserId(db, OAuth2Provider.GOOGLE, id)
                .map(OUserSocialNetwork::getUser)
                .orElse(null);
    }
    return null;
}
 
Example #29
Source File: OrienteerLocalizationModule.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onDestroy(OrienteerWebApplication app, ODatabaseDocument db) {
	Iterator<IStringResourceLoader> it = app.getResourceSettings().getStringResourceLoaders().iterator();
	while (it.hasNext()){
		if(it.next() instanceof OrienteerStringResourceLoader) it.remove();
	}
	app.getOrientDbSettings().getORecordHooks().remove(LocalizationInvalidationHook.class);
}
 
Example #30
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyRenaming()
{
	ODatabaseDocument db = wicket.getTester().getDatabase();
	OSchema schema = db.getMetadata().getSchema();
	OClass classA = schema.createClass("TestPropertyRenaming");
	OProperty property = classA.createProperty("propertyOld", OType.STRING);
	assertEquals(property, classA.getProperty("propertyOld"));
	assertNull(classA.getProperty("propertyNew"));
	property.setName("propertyNew");
	schema.reload();
	classA = schema.getClass("TestPropertyRenaming");
	assertNull(classA.getProperty("propertyOld"));
	assertEquals(property, classA.getProperty("propertyNew"));
}