]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/reflection/AdaptingDynamicAdapter2.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.db.services / src / org / simantics / db / services / adaption / reflection / AdaptingDynamicAdapter2.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.db.services.adaption.reflection;\r
13 \r
14 import java.util.ArrayList;\r
15 import java.util.Collection;\r
16 \r
17 import org.simantics.db.ReadGraph;\r
18 import org.simantics.db.Resource;\r
19 import org.simantics.db.exception.AdaptionException;\r
20 import org.simantics.db.exception.DatabaseException;\r
21 \r
22 public class AdaptingDynamicAdapter2 implements IDynamicAdapter2 {\r
23 \r
24     IDynamicAdapter2 adapter;\r
25     Class<?> targetType;\r
26 \r
27     public AdaptingDynamicAdapter2(IDynamicAdapter2 adapter, Class<?> targetType) {\r
28         this.adapter = adapter;\r
29         this.targetType = targetType;\r
30     }\r
31 \r
32     @Override\r
33     public Object adapt(ReadGraph g, Resource r) throws DatabaseException {\r
34         Object obj = adapter.adapt(g, r);\r
35         if(obj == null)\r
36             return null;\r
37         if(obj instanceof Resource)\r
38             return g.adapt((Resource)obj, targetType);\r
39         if(obj instanceof Collection<?>) {\r
40             Collection<?> c = (Collection<?>)obj;\r
41             Collection<Object> ret = new ArrayList<Object>(c.size());\r
42             for(Object o : c)\r
43                 ret.add(g.adapt((Resource)o, targetType));\r
44             return ret;\r
45         }\r
46         throw new AdaptionException("Invalid type.");\r
47     }\r
48 \r
49     @Override\r
50     public Class<?> getType() throws DatabaseException {\r
51         if(adapter.getType().equals(Resource.class))\r
52             return targetType;\r
53         else if(adapter.getType().equals(Collection.class))\r
54             return Collection.class;\r
55         else\r
56             throw new AdaptionException("Invalid type.");\r
57     }\r
58 \r
59 }\r