KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.beans.PropertyChangeEvent JavaDoc;
25 import java.beans.PropertyChangeListener JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28 import java.util.Arrays JavaDoc;
29 import java.util.Collections JavaDoc;
30 import java.util.List JavaDoc;
31 import javax.lang.model.element.ElementKind;
32 import javax.lang.model.element.Modifier;
33 import javax.lang.model.element.TypeElement;
34 import javax.swing.Action JavaDoc;
35 import org.netbeans.api.java.source.CompilationController;
36 import org.netbeans.api.java.source.ElementHandle;
37 import org.netbeans.api.java.source.JavaSource;
38 import org.netbeans.api.java.source.WorkingCopy;
39 import org.netbeans.api.project.FileOwnerQuery;
40 import org.netbeans.api.project.Project;
41 import org.netbeans.modules.j2ee.api.ejbjar.EnterpriseReferenceContainer;
42 import org.netbeans.modules.j2ee.common.method.MethodModel;
43 import org.netbeans.modules.j2ee.common.method.MethodModelSupport;
44 import org.netbeans.modules.j2ee.common.queries.api.InjectionTargetQuery;
45 import org.netbeans.modules.j2ee.common.source.AbstractTask;
46 import org.netbeans.modules.j2ee.dd.api.common.ResourceRef;
47 import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
48 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
49 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eePlatform;
50 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
51 import org.netbeans.modules.j2ee.ejbcore.Utils;
52 import org.netbeans.modules.j2ee.ejbcore._RetoucheUtil;
53 import org.openide.DialogDescriptor;
54 import org.openide.DialogDisplayer;
55 import org.openide.ErrorManager;
56 import org.openide.NotifyDescriptor;
57 import org.openide.filesystems.FileObject;
58 import org.openide.nodes.Node;
59 import org.openide.util.HelpCtx;
60 import org.openide.util.NbBundle;
61 import org.openide.util.actions.NodeAction;
62 import org.openide.util.Lookup;
63
64 /**
65  * Provide action for using an e-mail
66  *
67  * @author Petr Blaha
68  */

69 public class SendEmailAction extends NodeAction {
70     
71     protected void performAction(Node[] nodes) {
72         ElementHandle<TypeElement> beanClass = null;
73         try {
74             beanClass = _RetoucheUtil.getJavaClassFromNode(nodes[0]);
75         } catch (IOException JavaDoc ioe) {
76             ErrorManager.getDefault().notify(ioe);
77             return;
78         }
79         FileObject srcFile = nodes[0].getLookup().lookup(FileObject.class);
80         Project enterpriseProject = FileOwnerQuery.getOwner(srcFile);
81         
82         //make sure configuration is ready
83
J2eeModuleProvider pwm = (J2eeModuleProvider) enterpriseProject.getLookup().lookup(J2eeModuleProvider.class);
84         pwm.getConfigSupport().ensureConfigurationReady();
85         
86         EnterpriseReferenceContainer erc = (EnterpriseReferenceContainer)
87         enterpriseProject.getLookup().lookup(EnterpriseReferenceContainer.class);
88         
89         SendEmailPanel sendEmailPanel = new SendEmailPanel(erc.getServiceLocatorName()); //NOI18N
90
final DialogDescriptor dialogDescriptor = new DialogDescriptor(
91                 sendEmailPanel,
92                 NbBundle.getMessage(SendEmailAction.class, "LBL_SpecifyMailResource"),
93                 true,
94                 DialogDescriptor.OK_CANCEL_OPTION,
95                 DialogDescriptor.OK_OPTION,
96                 DialogDescriptor.DEFAULT_ALIGN,
97                 new HelpCtx(SendEmailPanel.class),
98                 null
99                 );
100         
101         sendEmailPanel.addPropertyChangeListener(new PropertyChangeListener JavaDoc() {
102             public void propertyChange(PropertyChangeEvent JavaDoc evt) {
103                 if (evt.getPropertyName().equals(SendEmailPanel.IS_VALID)) {
104                     Object JavaDoc newvalue = evt.getNewValue();
105                     if ((newvalue != null) && (newvalue instanceof Boolean JavaDoc)) {
106                         dialogDescriptor.setValid(((Boolean JavaDoc)newvalue).booleanValue());
107                     }
108                 }
109             }
110         });
111         sendEmailPanel.checkJndiName();
112         
113         Object JavaDoc option = DialogDisplayer.getDefault().notify(dialogDescriptor);
114         if (option == NotifyDescriptor.OK_OPTION) {
115             try {
116                 
117                 // TODO: for now I am leaving explicit creation of resource element in model here,
118
// because model builder doesn't handle @Resource annotation.
119
// Later it should be conditional - disabled for Java EE 5 projects
120
// and it should be autodiscovered by annotation listening.
121
String JavaDoc jndiName = generateJNDILookup(sendEmailPanel.getJndiName(), erc, srcFile, beanClass.getQualifiedName());
122                 if (jndiName != null) {
123                     String JavaDoc serviceLocator = sendEmailPanel.getServiceLocator();
124                     ServiceLocatorStrategy serviceLocatorStrategy = null;
125                     if (serviceLocator != null) {
126                         serviceLocatorStrategy = ServiceLocatorStrategy.create(enterpriseProject, srcFile, serviceLocator);
127                     }
128                     generateMethods(enterpriseProject, srcFile, beanClass.getQualifiedName(), jndiName, sendEmailPanel.getJndiName(), serviceLocatorStrategy);
129                     if (serviceLocator != null) {
130                         erc.setServiceLocatorName(serviceLocator);
131                     }
132                 }
133             } catch (IOException JavaDoc ioe) {
134                 NotifyDescriptor ndd = new NotifyDescriptor.Message(ioe.getMessage(),
135                         NotifyDescriptor.ERROR_MESSAGE);
136                 DialogDisplayer.getDefault().notify(ndd);
137             }
138         }
139     }
140     
141     public String JavaDoc getName() {
142         return NbBundle.getMessage(SendEmailAction.class, "LBL_SendEmailAction");
143     }
144     
145     public HelpCtx getHelpCtx() {
146         return HelpCtx.DEFAULT_HELP;
147     }
148     
149     protected boolean asynchronous() {
150         return false;
151     }
152     
153     private String JavaDoc generateJNDILookup(String JavaDoc jndiName, EnterpriseReferenceContainer erc, FileObject fileObject, String JavaDoc className) throws IOException JavaDoc {
154         ResourceRef ref = erc.createResourceRef(className);
155         if (ref != null) {
156             ref.setResRefName(jndiName); // NOI18N
157
ref.setResAuth(org.netbeans.modules.j2ee.dd.api.common.ResourceRef.RES_AUTH_CONTAINER);
158             ref.setResSharingScope(org.netbeans.modules.j2ee.dd.api.common.ResourceRef.RES_SHARING_SCOPE_SHAREABLE);
159             ref.setResType("javax.mail.Session"); //NOI18N
160
return erc.addResourceRef(ref, fileObject, className);
161         }
162         return null;
163     }
164     
165     private void generateMethods(Project project, FileObject fileObject, String JavaDoc className,
166             String JavaDoc jndiName, String JavaDoc simpleName, ServiceLocatorStrategy slStrategy) throws IOException JavaDoc{
167         String JavaDoc memberName = _RetoucheUtil.uniqueMemberName(fileObject, className, simpleName, "mailResource"); //NOI18N
168
if (Utils.isJavaEE5orHigher(project) && InjectionTargetQuery.isInjectionTarget(fileObject, className)) {
169             generateInjectedField(fileObject, className, simpleName, memberName);
170             generateSendMailMethod(fileObject, className, memberName, null);
171         } else {
172             String JavaDoc sessionGetter = generateLookupMethod(fileObject, className, jndiName, simpleName, slStrategy);
173             generateSendMailMethod(fileObject, className, memberName, sessionGetter);
174         }
175     }
176     
177     private void generateSendMailMethod(FileObject fileObject, final String JavaDoc className, String JavaDoc sessionVariableName, String JavaDoc sessionGetter) throws IOException JavaDoc{
178         
179         List JavaDoc<MethodModel.Variable> parameters = Arrays.asList(new MethodModel.Variable[] {
180             MethodModel.Variable.create("java.lang.String", "email"),
181             MethodModel.Variable.create("java.lang.String", "subject"),
182             MethodModel.Variable.create("java.lang.String", "body")
183         });
184         
185         List JavaDoc<String JavaDoc> exceptions = Arrays.asList(new String JavaDoc[] {
186             javax.naming.NamingException JavaDoc.class.getName(),
187             "javax.mail.MessagingException"
188         });
189         
190         final MethodModel methodModel = MethodModel.create(
191                 _RetoucheUtil.uniqueMemberName(fileObject, className, "sendMail", "mailResource"),
192                 "void",
193                 getSendCode(sessionVariableName, sessionGetter),
194                 parameters,
195                 exceptions,
196                 Collections.singleton(Modifier.PRIVATE)
197                 );
198         JavaSource javaSource = JavaSource.forFileObject(fileObject);
199         javaSource.runModificationTask(new AbstractTask<WorkingCopy>() {
200             public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
201                 workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
202                 TypeElement typeElement = workingCopy.getElements().getTypeElement(className);
203                 MethodTree methodTree = MethodModelSupport.createMethodTree(workingCopy, methodModel);
204                 ClassTree classTree = workingCopy.getTrees().getTree(typeElement);
205                 ClassTree newClassTree = workingCopy.getTreeMaker().addClassMember(classTree, methodTree);
206                 workingCopy.rewrite(classTree, newClassTree);
207             }
208         }).commit();
209     }
210     
211     private String JavaDoc getSendCode(String JavaDoc sessionVariableName, String JavaDoc sessionGetter){
212         return (sessionGetter != null ? "javax.mail.Session " + sessionVariableName + " = " + sessionGetter + "();\n" : "") +
213                 "javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(" + sessionVariableName + ");\n" +
214                 "message.setSubject(subject);\n" +
215                 "message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(email, false));\n" +
216                 "message.setText(body);\n" +
217                 "javax.mail.Transport.send(message);\n";
218     }
219     
220     private String JavaDoc generateLookupMethod(FileObject fileObject, final String JavaDoc className, String JavaDoc jndiName, String JavaDoc simpleName,
221             ServiceLocatorStrategy slStrategy) throws IOException JavaDoc {
222         String JavaDoc sessionGetter = "get" + simpleName.substring(0, 1).toUpperCase() + simpleName.substring(1);
223         sessionGetter = _RetoucheUtil.uniqueMemberName(fileObject, className, sessionGetter, "mailResource");
224         String JavaDoc body = null;
225         if (slStrategy == null) {
226             body = getSessionCode(jndiName);
227         } else {
228             body = getSessionCode(jndiName, slStrategy, fileObject, className);
229         }
230         final MethodModel methodModel = MethodModel.create(
231                 sessionGetter,
232                 "javax.mail.Session",
233                 body,
234                 Collections.<MethodModel.Variable>emptyList(),
235                 Collections.singletonList(javax.naming.NamingException JavaDoc.class.getName()),
236                 Collections.singleton(Modifier.PRIVATE)
237                 );
238         JavaSource javaSource = JavaSource.forFileObject(fileObject);
239         javaSource.runModificationTask(new AbstractTask<WorkingCopy>() {
240             public void run(WorkingCopy workingCopy) throws IOException JavaDoc {
241                 workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
242                 TypeElement typeElement = workingCopy.getElements().getTypeElement(className);
243                 MethodTree methodTree = MethodModelSupport.createMethodTree(workingCopy, methodModel);
244                 ClassTree classTree = workingCopy.getTrees().getTree(typeElement);
245                 ClassTree newClassTree = workingCopy.getTreeMaker().addClassMember(classTree, methodTree);
246                 workingCopy.rewrite(classTree, newClassTree);
247             }
248         }).commit();
249         return sessionGetter;
250     }
251     
252     private String JavaDoc getSessionCode(String JavaDoc jndiName, ServiceLocatorStrategy slStrategy, FileObject fileObject, String JavaDoc className) {
253         String JavaDoc mailLookupString = slStrategy.genMailSession(jndiName, fileObject, className);
254         return "return (javax.mail.Session) " + mailLookupString + ";\n"; // NOI18N
255
}
256     
257     private String JavaDoc getSessionCode(String JavaDoc jndiName) {
258         return MessageFormat.format(
259                 "javax.naming.Context c = new javax.naming.InitialContext();\n" + // NOI18N
260
"return (javax.mail.Session) c.lookup(\"java:comp/env/{0}\");\n", // NOI18N
261
new Object JavaDoc[] {jndiName});
262     }
263     
264     private void generateInjectedField(FileObject fileObject, String JavaDoc className, String JavaDoc jndiName, String JavaDoc simpleName) throws IOException JavaDoc {
265         _RetoucheUtil.generateAnnotatedField(
266                 fileObject,
267                 className,
268                 "javax.annotation.Resource",
269                 simpleName,
270                 "javax.mail.Session",
271                 Collections.singletonMap("name", jndiName),
272                 InjectionTargetQuery.isStaticReferenceRequired(fileObject, className)
273                 );
274     }
275     
276     protected boolean enable(Node[] nodes) {
277         if (nodes == null || nodes.length != 1) {
278             return false;
279         }
280         FileObject fileObject = nodes[0].getLookup().lookup(FileObject.class);
281         if (fileObject == null) {
282             return false;
283         }
284         Project project = FileOwnerQuery.getOwner(fileObject);
285         J2eeModuleProvider j2eeModuleProvider = (J2eeModuleProvider) project.getLookup().lookup(J2eeModuleProvider.class);
286         String JavaDoc serverInstanceId = j2eeModuleProvider.getServerInstanceID();
287         if (serverInstanceId == null) {
288             return true;
289         }
290         J2eePlatform platform = Deployment.getDefault().getJ2eePlatform(serverInstanceId);
291         if (platform == null) {
292             return true;
293         }
294         if (!platform.getSupportedModuleTypes().contains(J2eeModule.EJB)) {
295             return false;
296         }
297         JavaSource javaSource = JavaSource.forFileObject(fileObject);
298         final boolean[] isInterface = new boolean[1];
299         try {
300             final ElementHandle<TypeElement> elementHandle = _RetoucheUtil.getJavaClassFromNode(nodes[0]);
301             if (elementHandle == null || javaSource == null) {
302                 return false;
303             }
304             javaSource.runUserActionTask(new AbstractTask<CompilationController>() {
305                 public void run(CompilationController controller) throws IOException JavaDoc {
306                     controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
307                     TypeElement typeElement = elementHandle.resolve(controller);
308                     isInterface[0] = ElementKind.INTERFACE == typeElement.getKind();
309                 }
310             }, true);
311             return elementHandle == null ? false : !isInterface[0];
312         } catch (IOException JavaDoc ioe) {
313             ErrorManager.getDefault().notify(ioe);
314         }
315         return false;
316     }
317     
318     public Action JavaDoc createContextAwareInstance(Lookup actionContext) {
319         boolean enable = enable(actionContext.lookup(new Lookup.Template<Node>(Node.class)).allInstances().toArray(new Node[0]));
320         return enable ? this : null;
321     }
322     
323 }
324
Popular Tags