1 /*******************************************************************************
2 * Copyright (c) 2007, 2012 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.browsing.ui.swt.widgets.impl;
14 import org.eclipse.jface.viewers.ISelection;
15 import org.simantics.db.ReadGraph;
16 import org.simantics.db.common.request.UnaryRead;
17 import org.simantics.db.common.utils.Logger;
18 import org.simantics.db.exception.DatabaseException;
19 import org.simantics.db.management.ISessionContext;
20 import org.simantics.db.procedure.Listener;
21 import org.simantics.utils.ReflectionUtils;
22 import org.simantics.utils.datastructures.Pair;
23 import org.simantics.utils.ui.ISelectionUtils;
26 * @author Antti Villberg
28 * @param <Input> expected and checked input type
29 * @param <Output> result type of factory
31 public abstract class ReadFactoryImpl<Input, Output> implements ReadFactory<Input, Output> {
33 final Class<?> inputClass;
36 protected ReadFactoryImpl() {
40 protected ReadFactoryImpl(boolean sync) {
41 inputClass = ReflectionUtils.getSingleParameterType(getClass());
45 public Object getIdentity(Object inputContents) {
46 return new Pair<Object, Class<?>>(inputContents, getClass());
49 private Object getInputContents(Object input, Class<?> inputClass) {
50 if (inputClass.isInstance(input))
52 if (input instanceof ISelection)
53 return ISelectionUtils.filterSingleSelection(input, inputClass);
58 public void listen(ISessionContext context, Object input, Listener<Output> listener) {
59 final Object inputContents = getInputContents(input, inputClass);
60 if (inputContents != null) {
61 UnaryRead<Object, Output> read = new UnaryRead<Object, Output>(getIdentity(inputContents)) {
62 @SuppressWarnings("unchecked")
64 public Output perform(ReadGraph graph) throws DatabaseException {
65 return ReadFactoryImpl.this.perform(graph, (Input) inputContents);
68 public String toString() {
69 return getIdentity(inputContents).toString();
74 Output out = context.getSession().syncRequest(read, listener);
75 listener.execute(out);
76 } catch (DatabaseException e) {
77 Logger.defaultLogError(e);
80 context.getSession().asyncRequest(read, listener);
84 abstract public Output perform(ReadGraph graph, Input input) throws DatabaseException;