View Javadoc

1   /*
2    * Copyright 2004-2006 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package com.isenshi.util.converter.function;
17  
18  import java.util.LinkedHashSet;
19  import java.util.Set;
20  
21  import org.seasar.tuigwaa.model.common.EntityUtils;
22  import org.seasar.tuigwaa.model.core.TgwAttribute;
23  import org.seasar.tuigwaa.model.core.TgwEntity;
24  import org.seasar.tuigwaa.model.core.impl.FkAttribute;
25  import org.seasar.tuigwaa.model.core.impl.SetAttribute;
26  import org.seasar.tuigwaa.util.TgwNameUtils;
27  
28  
29  public class ManyToManyConverterFunction extends ConverterFunction {
30  
31  	private SetAttribute getSetField() {
32  		return (SetAttribute) getEntity().getField(
33  				TgwNameUtils.toPropertyName(getTargetField()));
34  	}
35  
36  	public Object evaluate(Object obj) {
37  		SetAttribute attr = getSetField();
38  		if (!EntityUtils.manyToManyFlag(attr)) {
39  			return obj; // no convert
40  		}
41  
42  		String src = getSourceField();
43  		String target = getTargetField();
44  
45  		TgwEntity oneToManyEntity = getSetField().getRefEntity();
46  		//FkAttribute inverseAttr = getSetField().getInverseField();
47  
48  		TgwAttribute theOtherAttr = EntityUtils.getTheOtherAttribute(attr);
49  
50  		String[] array = (String[]) EntityUtils.getProperty(obj, src);
51  		Set set = new LinkedHashSet();
52  
53  		for (int i = 0; i < array.length; i++) {
54  			Object theOtherObj = createTheOtherObject(theOtherAttr, array[i]);
55  
56  			Object oneToManyObj = oneToManyEntity.newInstance();
57  			//EntityUtils.setProperty(oneToManyObj, inverseAttr, data);
58  			EntityUtils.setProperty(oneToManyObj, theOtherAttr, theOtherObj);
59  			set.add(oneToManyObj);
60  		}
61  		EntityUtils.setProperty(obj, target, set);
62  
63  		return obj;
64  	}
65  
66  	private Object createTheOtherObject(TgwAttribute theOther, String value) {
67  		Object refObject = null;
68  		if (theOther instanceof FkAttribute) {
69  			FkAttribute fk = (FkAttribute) theOther;
70  			TgwEntity refEntity = fk.getRefEntity();
71  			Long id = Long.valueOf(value);
72  			refObject = EntityUtils.newInstanceById(refEntity, id);
73  		} else {
74  			refObject = value;
75  		}
76  		return refObject;
77  	}
78  }