1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.common.procedure.single.wrapper;
14 import java.util.concurrent.atomic.AtomicBoolean;
16 import org.simantics.db.AsyncReadGraph;
17 import org.simantics.db.common.procedure.adapter.AsyncMultiProcedureAdapter;
18 import org.simantics.db.common.utils.Logger;
19 import org.simantics.db.exception.NoSingleResultException;
20 import org.simantics.db.procedure.AsyncProcedure;
22 final public class SingleOrErrorProcedure<Result> extends AsyncMultiProcedureAdapter<Result> {
24 private Result result = null;
25 final AsyncProcedure<Result> procedure;
26 final AtomicBoolean found = new AtomicBoolean(false);
27 final AtomicBoolean done = new AtomicBoolean(false);
29 public SingleOrErrorProcedure(AsyncProcedure<Result> procedure) {
30 this.procedure = procedure;
34 public void finished(AsyncReadGraph graph) {
36 // Shall fire exactly once!
37 if(done.compareAndSet(false, true)) {
40 procedure.exception(graph, new NoSingleResultException("No items " + procedure));
42 procedure.execute(graph, result);
44 } catch (Throwable t) {
45 Logger.defaultLogError(t);
51 public void execute(AsyncReadGraph graph, Result result) {
53 if(found.compareAndSet(false, true)) {
56 // Shall fire exactly once!
57 if(done.compareAndSet(false, true)) {
59 procedure.exception(graph, new NoSingleResultException("Multiple items " + this.result + " and " + result));
60 } catch (Throwable t) {
61 Logger.defaultLogError(t);
68 public void exception(AsyncReadGraph graph, Throwable t) {
69 // Shall fire exactly once!
70 if(done.compareAndSet(false, true)) {
72 procedure.exception(graph, t);
73 } catch (Throwable t2) {
74 Logger.defaultLogError(t2);
81 public String toString() {
82 return "SingleOrErrorProcedure -> " + procedure;