1 /*******************************************************************************
2 * Copyright (c) 2007, 2013 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.objmap.graph.annotations.factories;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Field;
17 import org.simantics.db.ReadGraph;
18 import org.simantics.db.Resource;
19 import org.simantics.db.exception.ResourceNotFoundException;
20 import org.simantics.db.exception.ServiceException;
21 import org.simantics.db.exception.ValidationException;
23 import org.simantics.objmap.bidirectional.IBidirectionalMappingRule;
24 import org.simantics.objmap.graph.annotations.RelatedValue;
25 import org.simantics.objmap.graph.rules.ValueRule;
26 import org.simantics.objmap.graph.rules.adapters.IdentityAdapter;
27 import org.simantics.objmap.graph.rules.adapters.ValueAdapter;
28 import org.simantics.objmap.graph.rules.domain.RelatedValueAccessor;
29 import org.simantics.objmap.graph.rules.factory.IFieldRuleFactory;
30 import org.simantics.objmap.graph.rules.range.AdaptedRangeAccessor;
31 import org.simantics.objmap.graph.rules.range.FieldAccessor;
32 import org.simantics.objmap.graph.rules.range.IRangeAccessor;
35 public class RelatedValueRuleFactory<Range> implements IFieldRuleFactory<Resource, Range> {
38 public IBidirectionalMappingRule<Resource, Range> create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException,
39 ValidationException, ServiceException {
40 RelatedValue annotation = (RelatedValue) _annotation;
41 Class<? extends ValueAdapter> adapterClass = annotation.adapter();
42 IRangeAccessor<Range,Object> rangeAccessor = new FieldAccessor<Range,Object>(field);
44 if (adapterClass == IdentityAdapter.class) {
45 valueType = DataTypeUtils.dataTypeOfClass(g, field.getType());
48 ValueAdapter adapter = adapterClass.newInstance();
49 rangeAccessor = new AdaptedRangeAccessor<Range>(rangeAccessor, adapter);
50 valueType = adapter.rangeTypeToDomainType(g, field.getType());
51 } catch (InstantiationException e) {
52 throw new RuntimeException(e);
53 } catch (IllegalAccessException e) {
54 throw new RuntimeException(e);
57 return new ValueRule<Resource,Range>(new RelatedValueAccessor(g.getResource(annotation.value()), valueType), rangeAccessor);