summaryrefslogtreecommitdiffstats
path: root/sdo-java/branches/emf-2.5/java5tools/src/main/java/org/apache/tuscany/sdo/generate/Interface2JavaGenerator.java
blob: 4d09c2da8ba2d8a0ab06934584e991305fc7df8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/**
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package org.apache.tuscany.sdo.generate;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.tuscany.sdo.util.DataObjectUtil;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.impl.EPackageRegistryImpl;

import commonj.sdo.helper.TypeHelper;

public class Interface2JavaGenerator extends JavaGenerator
{
  /**
   * Generate static SDOs from Java interfaces
   *
   *   Usage arguments: see JavaGenerator
   *
   *     [ -targetDirectory <target-root-directory> ]
   *     [ -javaPackage <java-package-name> ]
   *     [ -namespace <xsd-namespace> ]
   *     [ other options ... ]
   *     interface-names
   *
   *   Options:
   *
   *     -namespace
   *         Set the namespaceURI of the generated SDO Types to the specified value.
   *
   *     NOTE: see the base class JavaGenerator for other options.
   *
   *   Example:
   *
   *     generate somepackage.InterfaceA somepackage.InterfaceB
   *
   */
  public static void main(String args[])
  {
    try
    {
      JavaGenerator generator = new Interface2JavaGenerator();
      generator.processArguments(args);
      generator.run(args);
    }
    catch (IllegalArgumentException e)
    {
      printUsage();
    }
  }

  protected String namespace = null;

  protected int handleArgument(String args[], int index)
  {
    if (args[index].equalsIgnoreCase("-namespace"))
    {
      namespace = args[++index];
    }
    else
    {
      return super.handleArgument(args, index);
    }

    return index + 1;
  }

  protected void run(String args[])
  {
    List javaInterfaces=new ArrayList();

    for (int index = inputIndex; index < args.length; ++index)
    {
      javaInterfaces.add(args[index]);
    }

    ClassLoader classLoader=JavaGenerator.class.getClassLoader();
    generateFromJavaInterfaces(classLoader, javaInterfaces, namespace, targetDirectory, javaPackage, prefix, genOptions);
  }

  public static void generateFromJavaInterfaces(ClassLoader classLoader, List javaInterfaces, String packageURI, String targetDirectory, String javaPackage, String prefix, int genOptions)
  {
    try
    {
      // Initialize the SDO runtime
      DataObjectUtil.initRuntime();
      EPackage.Registry packageRegistry = new EPackageRegistryImpl(EPackage.Registry.INSTANCE);

      // Create an EPackage for the generated SDO
      if (packageURI == null)
        packageURI = "http://" + javaPackage;
      EPackage implEPackage = EcoreFactory.eINSTANCE.createEPackage();
      implEPackage.setNsURI(packageURI);
      String shortName = shortName(packageURI);
      implEPackage.setName(shortName);
      implEPackage.setNsPrefix(shortName.toLowerCase());
      packageRegistry.put(packageURI, implEPackage);

      // Create EClasses for all the given Java interfaces
      Map eClasses = new HashMap();
      for (Iterator iter = javaInterfaces.iterator(); iter.hasNext();)
      {
        String interfaceName = (String)iter.next();
        Class instanceClass = Class.forName(interfaceName, true, classLoader);

        EClass implEClass = EcoreFactory.eINSTANCE.createEClass();
        String className = shortName(instanceClass.getName());
        implEClass.setName(className);
        implEClass.setInstanceClass(instanceClass);

        eClasses.put(instanceClass, implEClass);
        implEPackage.getEClassifiers().add(implEClass);
      }

      // Populate the EClasses with EAttributes and EReferences for their properties
      for (Iterator iter = implEPackage.getEClassifiers().iterator(); iter.hasNext();)
      {
        EClass implEClass = (EClass)iter.next();
        Class instanceClass = implEClass.getInstanceClass();
        Method[] methods = instanceClass.getMethods();
        for (int m = 0; m < methods.length; m++)
        {
          Method method = methods[m];
          String propertyName = null;
          if (method.getName().startsWith("get"))
            propertyName = method.getName().substring(3);
          else if (method.getName().startsWith("is"))
            propertyName = method.getName().substring(2);

          if (propertyName != null)
          {
            if (propertyName.length() > 1)
              propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);

            Class propertyClass = method.getReturnType();
            EClass propertyEClass = (EClass)eClasses.get(propertyClass);

            if (propertyEClass != null)
            {
              // The property is another SDO, create an EReference to represent the property
              EReference reference = EcoreFactory.eINSTANCE.createEReference();
              reference.setName(propertyName);
              reference.setContainment(true);
              reference.setEType(propertyEClass);
              implEClass.getEStructuralFeatures().add(reference);

            }
            else
            {
              // The property is a List<T> and T is an SDO, created a 0..many EReference to represent the property
              if (propertyClass == List.class)
              {
                Type genericType = method.getGenericReturnType();
                if (genericType instanceof ParameterizedType)
                {
                  ParameterizedType parameterizedType = (ParameterizedType)genericType;
                  Type[] targs = parameterizedType.getActualTypeArguments();
                  if (targs.length != 0 && eClasses.containsKey(targs[0]))
                  {
                    propertyEClass = (EClass)eClasses.get(targs[0]);
                    if (propertyEClass != null)
                    {
                      EReference reference = EcoreFactory.eINSTANCE.createEReference();
                      reference.setName(propertyName);
                      reference.setContainment(true);
                      reference.setEType(propertyEClass);
                      reference.setUpperBound(-1);
                      implEClass.getEStructuralFeatures().add(reference);
                    }
                  }
                }
                continue;
              }

              // The property is a regular Java type / not an SDO, create an EAttribute to represent it
              EAttribute attribute = EcoreFactory.eINSTANCE.createEAttribute();
              attribute.setName(propertyName);
              EDataType dataType = (EDataType)TypeHelper.INSTANCE.getType(propertyClass);
              attribute.setEType(dataType);
              implEClass.getEStructuralFeatures().add(attribute);
            }
          }
        }
      }

      generatePackages(packageRegistry.values(), packageURI, shortName, targetDirectory, javaPackage, prefix, genOptions);
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
    }
  }

  protected static void printUsage()
  {
    System.out.println("Usage arguments:");
    System.out.println("  [ -targetDirectory <target-root-directory> ]");
    System.out.println("  [ -javaPackage <java-package-name> ]");
    System.out.println("  [ -prefix <prefix-string> ]");
    System.out.println("  [ -namespace <xsd-namespace> ]");
    System.out.println("  [ -noInterfaces ]");
    System.out.println("  [ -noContainment ]");
    System.out.println("  [ -noNotification ]");
    System.out.println("  [ -noUnsettable ]");
    /* Future Option: System.out.println("  [ -sparsePattern | -storePattern ]"); */
    /* Future Option: System.out.println("  [ -arrayAccessors ]"); */
    /* Future Option: System.out.println("  [ -generateLoader ]"); */
    System.out.println("  interface-names");
    System.out.println("");
    System.out.println("For example:");
    System.out.println("");
    System.out.println("  generate somepackage.InterfaceA somepackage.InterfaceB");
  }

}