Java Code Examples for com.orientechnologies.orient.core.db.document.ODatabaseDocument#begin()

The following examples show how to use com.orientechnologies.orient.core.db.document.ODatabaseDocument#begin() . 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: SaveODocumentsCommand.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(Optional<AjaxRequestTarget> targetOptional) {
	table.visitChildren(OrienteerDataTable.MetaContextItem.class, new IVisitor<OrienteerDataTable.MetaContextItem<ODocument, ?>, Void>() {

		@Override
		public void component(MetaContextItem<ODocument, ?> rowItem, IVisit<Void> visit) {
			ODocument doc = rowItem.getModelObject();
			if(doc.isDirty()) {
				if(doc.getIdentity().isNew()) SaveODocumentCommand.realizeMandatory(doc);
				doc.save();
			}
			visit.dontGoDeeper();
		}
	});
	if(forceCommit) {
		ODatabaseDocument db = getDatabase();
		boolean active = db.getTransaction().isActive();
		db.commit();
		if(active) db.begin();
	}
	super.onClick(targetOptional);
}
 
Example 2
Source File: OPropertyMetaPanel.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
@Override
protected void setValue(OProperty entity, String critery, V value) {
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
	db.commit();
	try
	{
		CustomAttribute custom;
		if(OPropertyPrototyper.COLLATE.equals(critery))
		{
			entity.setCollate((String)value);
		}
		else if((custom = CustomAttribute.getIfExists(critery))!=null)
		{
			custom.setValue(entity, value);
		}
		else
		{
			PropertyResolver.setValue(critery, entity, value, null);
		}
	} finally
	{
		db.begin();
	}
}
 
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: 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 5
Source File: NotificationService.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
private void updateNotificationStatus(ODatabaseDocument db, IONotification notification, ODocument status) {
  for (int i = 1; i <= 10; i++) {
    try {
      db.begin();
      notification.addStatusHistory(IONotificationStatusHistory.create(new Date(), status));
      notification.setStatus(status);
      notification.save();
      db.commit();
      break;
    } catch (Exception e) {
      if (i == 10) {
         LOG.error("Couldn't save notification: {}", notification.getDocument(), e);
      } else {
        notification.reload();
      }
    }
  }
}
 
Example 6
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 7
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 8
Source File: DeleteODocumentCommand.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void performMultiAction(AjaxRequestTarget target, List<ODocument> objects) {
	super.performMultiAction(target, objects);
	ODatabaseDocument db = getDatabase();
	db.commit(true);
	db.begin();
	DBClosure.sudoConsumer(sudoDb -> sudoDb.getMetadata().reload());
}
 
Example 9
Source File: SaveODocumentCommand.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void onClick(Optional<AjaxRequestTarget> targetOptional) {
	ODocument doc = getModelObject();
	if(doc.getIdentity().isNew()) realizeMandatory(doc);
	doc.save();
	if(forceCommit) {
		ODatabaseDocument db = getDatabase();
		boolean active = db.getTransaction().isActive();
		db.commit();
		if(active) db.begin();
	}
       super.onClick(targetOptional);
}
 
Example 10
Source File: OClassMetaPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setValue(OClass entity, String critery, V value) {
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
	db.commit();
	try
	{
		CustomAttribute custom;
		if(OClassPrototyper.CLUSTER_SELECTION.equals(critery))
		{
			if(value!=null) entity.setClusterSelection(value.toString());
		}
		else if((CustomAttribute.ON_CREATE_FIELDS.getName().equals(critery)) && (custom = CustomAttribute.getIfExists(critery)) != null)
		{
			custom.setValue(entity, value!=null?Joiner.on(",").join((List<String>) value):null);
		}
		else if((custom = CustomAttribute.getIfExists(critery))!=null)
		{
			custom.setValue(entity, value);
		}
		else if (OClassPrototyper.SUPER_CLASSES.equals(critery))
		{
			if(value!=null) entity.setSuperClasses((List<OClass>) value);
		}
		else
		{
			PropertyResolver.setValue(critery, entity, value, new PropertyResolverConverter(Application.get().getConverterLocator(),
					Session.get().getLocale()));
		}
	} finally
	{
		db.begin();
	}
}
 
Example 11
Source File: OClusterMetaPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setValue(OCluster entity, String critery, V value) {
    ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
    db.commit();
    try
    {
        if(OClustersWidget.COMPRESSION.equals(critery)) {
            entity.set(OCluster.ATTRIBUTES.COMPRESSION, value);
        }
        else if(OClustersWidget.NAME.equals(critery)) {
            entity.set(OCluster.ATTRIBUTES.NAME, value);
        }
        else if(OClustersWidget.RECORD_GROW_FACTOR.equals(critery)) {
            entity.set(OCluster.ATTRIBUTES.RECORD_GROW_FACTOR, value);
        }
        else if(OClustersWidget.RECORD_OVERFLOW_GROW_FACTOR.equals(critery)) {
            entity.set(OCluster.ATTRIBUTES.RECORD_OVERFLOW_GROW_FACTOR, value);
        }
        else if(OClustersWidget.CONFLICT_STRATEGY.equals(critery)) {
            entity.set(OCluster.ATTRIBUTES.CONFLICTSTRATEGY, value);
        }
        else {
            entity.set(OCluster.ATTRIBUTES.valueOf(critery), value);
        }
    }
    catch(IOException e) {
        throw new WicketRuntimeException("Can't set attribute on a cluster", e);
    }
    finally
    {
        db.begin();
    }
}
 
Example 12
Source File: OIndexMetaPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
protected void setValue(OIndex<?> entity, String critery, V value) {
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
	db.commit();
	try
	{
		if(OIndexPrototyper.DEF_COLLATE.equals(critery))
		{
			if(value!=null)
			{
				String collate = value.toString();
				entity.getDefinition().setCollate(OSQLEngine.getCollate(collate));
			}
			else
			{
				entity.getDefinition().setCollate(null);
			}
		}
		else
		{
			PropertyResolver.setValue(critery, entity, value, null);
		}
	} finally
	{
		db.begin();
	}
}
 
Example 13
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 14
Source File: AbstractCustomValueModel.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public void setObject(V object) {
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase(); 
	boolean isActiveTransaction = db.getTransaction().isActive();
	if(isActiveTransaction) db.commit(); // Schema changes should be done outside of transaction
	try {
		setValue(objectModel.getObject(), parameterModel.getObject(), object);
	} finally {
		if(isActiveTransaction) db.begin();
	}
}
 
Example 15
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testLoosingLinkedClass() throws Exception
{
	ODatabaseDocument db = wicket.getTester().getDatabase();
	OSchema schema = wicket.getTester().getSchema();
	OClass mainClass = schema.createClass("LMainClass");
	OClass embeddedClass = schema.createClass("LEmbeddedClass");
	mainClass.createProperty("name", OType.STRING);
	mainClass.createProperty("embedded", OType.EMBEDDED).setLinkedClass(embeddedClass);
	embeddedClass.createProperty("name", OType.STRING);
	
	db.begin();
	ODocument main = new ODocument(mainClass);
	main.field("name", "main");
	ODocument embedded = new ODocument(embeddedClass);
	//embedded.field("name", "embedded");
	main.field("embedded", embedded);
	//NO Save here!
	db.commit();
	db.close();
	
	main.fromStream(main.toStream());
	
	db = wicket.getTester().getDatabase();
	db.begin();
	assertEmbeddedIsCorrect(main);
	main.save();
	ORID recordId = main.getIdentity();
	db.commit();
	db.close();
	
	db = wicket.getTester().getDatabase();
	db.begin();
	main = recordId.getRecord();
	assertEmbeddedIsCorrect(main);
	db.commit();
}
 
Example 16
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testTransactions2() throws Exception {
	ODatabaseDocument db = wicket.getTester().getDatabase();
	try {
		assertFalse(db.getTransaction().isActive());
		OSchema schema = db.getMetadata().getSchema();
		OClass classA = schema.createClass("TransB");
		classA.createProperty("name", OType.STRING);
		ODocument doc = new ODocument(classA);
		doc.field("name", "test1");
		doc.save();
		ORID orid = doc.getIdentity();
		
		db.begin();
		assertTrue(db.getTransaction().isActive());
		doc = orid.getRecord();
		assertEquals("test1", doc.field("name"));
		doc.field("name", "test2");
		doc.save();
		doc = orid.getRecord();
		assertEquals("test2", doc.field("name"));
		doc.field("name", "test3");
		assertEquals("test3", doc.field("name"));
		//There is NO SAVE!
		db.commit();
		db.getLocalCache().clear();
		/* COMMENT START */
		//db.close();
		//db = wicket.getTester().getDatabase();
		/* COMMENT STOP */
		doc = orid.getRecord();
		assertEquals("test2", doc.field("name"));
		
	} finally {
		db.commit();
	}
}
 
Example 17
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactions() throws Exception {
	ODatabaseDocument db = wicket.getTester().getDatabase();
	try {
		assertFalse(db.getTransaction().isActive());
		OSchema schema = db.getMetadata().getSchema();
		OClass classA = schema.createClass("TransA");
		classA.createProperty("name", OType.STRING);
		ODocument doc = new ODocument(classA);
		doc.field("name", "test1");
		doc.save();
		ORID orid = doc.getIdentity();
		db.begin();
		assertTrue(db.getTransaction().isActive());
		doc = orid.getRecord();
		assertEquals("test1", doc.field("name"));
		doc.field("name", "test2");
		doc = orid.getRecord();
		assertEquals("test2", doc.field("name"));
		//There is NO SAVE!
		db.commit();
		db.getLocalCache().clear();
		/* COMMENT START */
		//db.close();
		//db = wicket.getTester().getDatabase();
		/* COMMENT STOP */
		doc = orid.getRecord();
		assertEquals("test1", doc.field("name"));
		
	} finally {
		db.commit();
	}
}
 
Example 18
Source File: HooksTest.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
@Test
@Sudo
public void testCalculableHook() throws Exception
{
	ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
	OSchema schema = db.getMetadata().getSchema();
	
	assertFalse(db.isClosed());
	db.commit();
	if(schema.existsClass(TEST_CLASS_A)) schema.dropClass(TEST_CLASS_A);
	OClass oClass = schema.createClass(TEST_CLASS_A);
	try
	{
		oClass.createProperty("a", OType.INTEGER);
		oClass.createProperty("b", OType.INTEGER);
		OProperty cProperty = oClass.createProperty("c", OType.INTEGER);
		OProperty dProperty = oClass.createProperty("d", OType.INTEGER);
		CustomAttribute.CALCULABLE.setValue(cProperty, true);
		CustomAttribute.CALCULABLE.setValue(dProperty, true);
		CustomAttribute.CALC_SCRIPT.setValue(cProperty, "select sum(a, b) as value from TestClassA where @rid = ?");
		CustomAttribute.CALC_SCRIPT.setValue(dProperty, "sum(a, b)");
		
		ODocument doc = new ODocument(oClass);
		doc.field("a", 2);
		doc.field("b", 2);
		doc.save();
		doc.reload();
		assertEquals(4, (Object) doc.field("c"));
		assertEquals(4, (Object) doc.field("d"));
		doc.field("a", 3);
		doc.field("b", 3);
		doc.save();
		doc.reload();
		assertEquals(6, (Object) doc.field("c"));
		assertEquals(6, (Object) doc.field("d"));
		db.begin();
		doc.field("a", 4);
		doc.field("b", 4);
		doc.save();
		doc.reload();
		assertEquals(8, (Object) doc.field("c"));
		assertEquals(8, (Object) doc.field("d"));
		db.commit();
		db.begin();
		doc.field("a", 5);
		doc.field("b", 5);
		doc.save();
		doc.reload();
		assertEquals(10, (Object) doc.field("c"));
		assertEquals(10, (Object) doc.field("d"));
		db.commit();
	} finally
	{
		if(db.getTransaction().isActive()) db.commit();
		schema.dropClass(TEST_CLASS_A);
	}
}
 
Example 19
Source File: TestInAppOrientDBCompatibility.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
@Test
public void testOFunctions() throws Exception
{
	ODatabaseDocument db = wicket.getTester().getDatabase();
	ODocument doc =  new ODocument(OFunction.CLASS_NAME);
	doc.field("name", "testResurection");
	doc.field("language", "JavaScript");
	doc.field("idempotent", true);
	doc.save();
	ORID orid = doc.getIdentity();
	for(int i=0;i<10;i++)
	{
		db = wicket.getTester().getDatabase();
		String signature = "signature"+RANDOM.nextLong();
		boolean isGoodCall = (i+1)%3 != 0;
		db.begin();
		doc = orid.getRecord();
		String code = isGoodCall?"return \""+signature+"\";":"return nosuchvar;";
		doc.field("code", code);
		doc.save();
		db.commit();
		db.close();
		if(isGoodCall)
		{
			String result;
			for(int j=0; j<3;j++)
			{
				result = wicket.getTester().executeUrl("orientdb/function/db/testResurection", "GET", null);
				assertContains(signature, result);
			}
		}
		else
		{
			try
			{
				wicket.getTester().executeUrl("orientdb/function/db/testResurection", "GET", null);
				assertFalse("We should be there, because function should have 400 response", true);
			} catch (Exception e)
			{
				//NOP
			}
		}
	}
}
 
Example 20
Source File: TestModels.java    From wicket-orientdb with Apache License 2.0 4 votes vote down vote up
private void interupt(ODatabaseDocument db, IModel<?> model) {
	model.detach();
	db.commit();
	db.getLocalCache().clear();
	db.begin();
}