KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > ejbcore > ui > logicalview > entres > ServiceLocatorStrategy


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.ejbcore.ui.logicalview.entres;
21
22 import com.sun.source.tree.ClassTree;
23 import com.sun.source.tree.MethodTree;
24 import com.sun.source.tree.VariableTree;
25 import java.io.IOException JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.Set JavaDoc;
28 import javax.lang.model.element.ExecutableElement;
29 import javax.lang.model.element.Modifier;
30 import javax.lang.model.element.TypeElement;
31 import javax.lang.model.util.ElementFilter;
32 import org.netbeans.api.java.classpath.ClassPath;
33 import org.netbeans.api.java.project.JavaProjectConstants;
34 import org.netbeans.api.java.source.CompilationController;
35 import org.netbeans.api.java.source.JavaSource;
36 import org.netbeans.api.java.source.TreeMaker;
37 import org.netbeans.api.java.source.WorkingCopy;
38 import org.netbeans.api.project.FileOwnerQuery;
39 import org.netbeans.api.project.Project;
40 import org.netbeans.api.project.ProjectUtils;
41 import org.netbeans.api.project.SourceGroup;
42 import org.netbeans.api.project.Sources;
43 import org.netbeans.modules.j2ee.common.method.MethodModel;
44 import org.netbeans.modules.j2ee.common.method.MethodModelSupport;
45 import org.netbeans.modules.j2ee.common.source.AbstractTask;
46 import org.netbeans.spi.java.classpath.ClassPathProvider;
47 import org.netbeans.spi.java.classpath.PathResourceImplementation;
48 import org.netbeans.spi.java.classpath.support.ClassPathSupport;
49 import org.openide.ErrorManager;
50 import org.openide.filesystems.FileObject;
51
52 /**
53  *
54  * @author Chris Webster
55  * @author Martin Adamek
56  */

57 public class ServiceLocatorStrategy {
58     private static final String JavaDoc CREATE_INVOCATION = ".create()"; //NOI18N
59

60     private ServiceLocatorStrategy() {
61     }
62     
63     public String JavaDoc genLocalEjbStringLookup(String JavaDoc jndiName, String JavaDoc homeName, FileObject fileObject, String JavaDoc className, boolean create) {
64         String JavaDoc initString = initString("getLocalHome", jndiName, fileObject, className, ""); //NOI18N
65
return "return " + addCast(create, homeName, initString, CREATE_INVOCATION) + ";"; // NOI18N
66
}
67     
68     public String JavaDoc genRemoteEjbStringLookup(String JavaDoc jndiName, String JavaDoc homeCls, FileObject fileObject, String JavaDoc className, boolean create) {
69         String JavaDoc initString = initString("getRemoteHome", jndiName, fileObject, className, "," + homeCls + ".class"); //NOI18N
70
return "return " + addCast(create, homeCls, initString, CREATE_INVOCATION) + ";"; //NOI18N
71
}
72     
73     public String JavaDoc genDestinationLookup(String JavaDoc jndiName, FileObject fileObject, String JavaDoc className) {
74         return initString("getDestination", jndiName, fileObject, className, ""); //NOI18N
75
}
76     
77     public String JavaDoc genJMSFactory(String JavaDoc jndiName, FileObject fileObject, String JavaDoc className) {
78         return initString("getConnectionFactory", jndiName, fileObject, className, ""); //NOI18N
79
}
80     
81     public String JavaDoc genDataSource(String JavaDoc jndiName, FileObject fileObject, String JavaDoc className) {
82         return initString("getDataSource", jndiName, fileObject, className, ""); //NOI18N
83
}
84     
85     public String JavaDoc genMailSession(String JavaDoc jndiName, FileObject fileObject, String JavaDoc className) {
86         return initString("getSession", jndiName, fileObject, className, ""); //NOI18N
87
}
88     
89     public static ServiceLocatorStrategy create(Project project, FileObject srcFile, String JavaDoc serviceLocator) {
90         return new ServiceLocatorStrategy();
91     }
92     
93     private ClassPath buildClassPathFromImportedProject(FileObject fileObject) {
94         Project project = FileOwnerQuery.getOwner(fileObject);
95         assert project != null : "cannot find project for file";
96         ClassPathProvider cpp = (ClassPathProvider)
97             project.getLookup().lookup(ClassPathProvider.class);
98         assert cpp != null: "project doesn't have class path provider";
99         Sources sources = ProjectUtils.getSources(project);
100         SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
101         ClassPath classPath = ClassPathSupport.createClassPath(Collections.<PathResourceImplementation>emptyList());
102         for (int i = 0; i < groups.length; i++) {
103             FileObject root = groups[i].getRootFolder();
104             if (root.getChildren().length > 0) {
105                 ClassPath tcp = cpp.findClassPath(root.getChildren()[0], ClassPath.SOURCE);
106                 classPath = ClassPathSupport.createProxyClassPath(new ClassPath[]{tcp,classPath});
107             }
108         }
109         return classPath;
110     }
111     
112     private String JavaDoc addCast(boolean cast, String JavaDoc clName, String JavaDoc current, String JavaDoc inv) {
113         String JavaDoc newValue = current;
114         newValue = "("+clName+") " + current; //NOI18N
115
if (cast) {
116             newValue = "(" + newValue + ")" + inv; //NOI18N
117
}
118         return newValue;
119     }
120     
121     private static String JavaDoc initString(String JavaDoc methodName, String JavaDoc jndiName, FileObject fileObject, String JavaDoc className, String JavaDoc otherParams) {
122         String JavaDoc initString = null;
123         try {
124             String JavaDoc staticCreation = getStaticLocator(fileObject, className);
125             if (staticCreation != null) {
126                 initString = className + "." + staticCreation + "()." + methodName + //NOI18N
127
"(\"java:comp/env/" + jndiName + "\""+ otherParams +")"; //NOI18N
128
} else {
129                     initString = findOrCreateArtifacts(fileObject, className) + "()." + methodName + //NOI18N
130
"(\"java:comp/env/" + jndiName + "\"" + otherParams + ")"; //NOI18N
131
}
132         } catch (IOException JavaDoc ioe) {
133             ErrorManager.getDefault().notify(ioe);
134         }
135         return initString;
136     }
137     
138     private static String JavaDoc findOrCreateArtifacts(FileObject fileObject, final String JavaDoc className) throws IOException JavaDoc {
139         JavaSource javaSource = JavaSource.forFileObject(fileObject);
140         final String JavaDoc[] methodName = new String JavaDoc[1];
141         javaSource.runModificationTask(new AbstractTask<WorkingCopy>() {
142             public void run(WorkingCopy workingCopy) {
143                 TypeElement target = workingCopy.getElements().getTypeElement(className);
144                 for (ExecutableElement executableElement : ElementFilter.methodsIn(target.getEnclosedElements())) {
145                     if (executableElement.getParameters().size() == 0 &&
146                             workingCopy.getTypes().isSameType(target.asType(), executableElement.getReturnType())) {
147                         methodName[0] = executableElement.getSimpleName().toString();
148                         break;
149                     }
150                 }
151                 TreeMaker treeMaker = workingCopy.getTreeMaker();
152                 TypeElement fieldTypeElement = workingCopy.getElements().getTypeElement(className);
153                 if (methodName[0] == null) {
154                     VariableTree variableTree = treeMaker.Variable(
155                             treeMaker.Modifiers(Collections.singleton(Modifier.PRIVATE)),
156                             "serviceLocator",
157                             treeMaker.QualIdent(fieldTypeElement),
158                             null
159                             );
160                     ClassTree classTree = workingCopy.getTrees().getTree(target);
161                     ClassTree newClassTree = treeMaker.addClassMember(classTree, variableTree);
162                     workingCopy.rewrite(classTree, newClassTree);
163
164                     MethodModel methodModel = MethodModel.create(
165                             "getServiceLocator",
166                             className,
167                             "if (serviceLocator == null) {\n" +
168                             "serviceLocator = new " + className + "();\n" +
169                             "}\n" +
170                             "return serviceLocator;\n",
171                             Collections.<MethodModel.Variable>emptyList(),
172                             Collections.<String JavaDoc>emptyList(),
173                             Collections.singleton(Modifier.PRIVATE)
174                             );
175                     MethodTree methodTree = MethodModelSupport.createMethodTree(workingCopy, methodModel);
176                     classTree = workingCopy.getTrees().getTree(target);
177                     newClassTree = treeMaker.addClassMember(classTree, methodTree);
178                     workingCopy.rewrite(classTree, newClassTree);
179                     
180                     methodName[0] = "getServiceLocator";
181                 }
182             }
183         }).commit();
184         return methodName[0];
185     }
186     
187     private static String JavaDoc getStaticLocator(FileObject fileObject, final String JavaDoc className) throws IOException JavaDoc {
188         JavaSource javaSource = JavaSource.forFileObject(fileObject);
189         final String JavaDoc[] methodName = new String JavaDoc[1];
190         javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
191             public void run(CompilationController controller) throws IOException JavaDoc {
192                 controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
193                 TypeElement typeElement = controller.getElements().getTypeElement(className);
194                 for (ExecutableElement executableElement : ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
195                     Set JavaDoc<Modifier> modifiers = executableElement.getModifiers();
196                     if (modifiers.contains(Modifier.STATIC) && modifiers.contains(Modifier.PUBLIC) &&
197                         controller.getTypes().isSameType(typeElement.asType(), executableElement.getReturnType())) {
198                             methodName[0] = executableElement.getSimpleName().toString();
199                     }
200                 }
201             }
202         }, true);
203         return methodName[0];
204     }
205     
206 }
207
Popular Tags