]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/reflection/AdaptingDynamicAdapter2.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.db.services / src / org / simantics / db / services / adaption / reflection / AdaptingDynamicAdapter2.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.services.adaption.reflection;
13
14 import java.util.ArrayList;
15 import java.util.Collection;
16
17 import org.simantics.db.ReadGraph;
18 import org.simantics.db.Resource;
19 import org.simantics.db.exception.AdaptionException;
20 import org.simantics.db.exception.DatabaseException;
21
22 public class AdaptingDynamicAdapter2 implements IDynamicAdapter2 {
23
24     IDynamicAdapter2 adapter;
25     Class<?> targetType;
26
27     public AdaptingDynamicAdapter2(IDynamicAdapter2 adapter, Class<?> targetType) {
28         this.adapter = adapter;
29         this.targetType = targetType;
30     }
31
32     @Override
33     public Object adapt(ReadGraph g, Resource r) throws DatabaseException {
34         Object obj = adapter.adapt(g, r);
35         if(obj == null)
36             return null;
37         if(obj instanceof Resource)
38             return g.adapt((Resource)obj, targetType);
39         if(obj instanceof Collection<?>) {
40             Collection<?> c = (Collection<?>)obj;
41             Collection<Object> ret = new ArrayList<Object>(c.size());
42             for(Object o : c)
43                 ret.add(g.adapt((Resource)o, targetType));
44             return ret;
45         }
46         throw new AdaptionException("Invalid type.");
47     }
48
49     @Override
50     public Class<?> getType() throws DatabaseException {
51         if(adapter.getType().equals(Resource.class))
52             return targetType;
53         else if(adapter.getType().equals(Collection.class))
54             return Collection.class;
55         else
56             throw new AdaptionException("Invalid type.");
57     }
58
59 }