+/*******************************************************************************
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.db.tests.api.write.request;
+
+import java.util.concurrent.Semaphore;
+
+import org.junit.Test;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.testing.base.ExistingDatabaseTest;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.datastructures.Callback;
+
+/**
+ * Checks that unexpected write callback failures do not crash the session and
+ * that the write request results were correctly committed.
+ *
+ * @author Tuukka Lehtonen
+ */
+public class WriteCallbackFailureTest extends ExistingDatabaseTest {
+
+ private static final String AN_ENTITY = "An entity";
+ Resource written;
+
+ @Test
+ public void testFailingWriteCallback() throws DatabaseException{
+ final Semaphore sem = new Semaphore(0);
+
+ getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 b = Layer0.getInstance(graph);
+ Resource test = graph.newResource();
+ graph.claim(test, b.InstanceOf, null, b.Entity);
+ Resource name = graph.newResource();
+ graph.claim(name, b.InstanceOf, null, b.String);
+ graph.claimValue(name, AN_ENTITY);
+ graph.claim(test, b.HasName, name);
+
+ written = test;
+ }
+ }, new Callback<DatabaseException>() {
+ @Override
+ public void run(DatabaseException parameter) {
+ try {
+ throw new NullPointerException("intentional failure");
+ } finally {
+ sem.release();
+ }
+ }
+ });
+
+ try {
+ sem.acquire();
+ } catch (InterruptedException e) {
+ throw new DatabaseException(e);
+ }
+
+ // This will block until the previous request has finished.
+ getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 b = Layer0.getInstance(graph);
+ // Ensure that the previously written data exists.
+ assertTrue(graph.hasStatement(written, b.InstanceOf, b.Entity));
+ Resource name = graph.getSingleObject(written, b.HasName);
+ assertTrue(graph.hasStatement(name, b.InstanceOf, b.String));
+ assertTrue(graph.hasStatement(written, b.HasName, name));
+ Object value = graph.getValue(name);
+ assertTrue(value.equals(AN_ENTITY));
+ }
+ });
+ }
+
+}