1 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 ; 25 import java.beans.PropertyChangeListener ; 26 import java.io.IOException ; 27 import java.text.MessageFormat ; 28 import java.util.Arrays ; 29 import java.util.Collections ; 30 import java.util.List ; 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 ; 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 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 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 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()); 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 () { 102 public void propertyChange(PropertyChangeEvent evt) { 103 if (evt.getPropertyName().equals(SendEmailPanel.IS_VALID)) { 104 Object newvalue = evt.getNewValue(); 105 if ((newvalue != null) && (newvalue instanceof Boolean )) { 106 dialogDescriptor.setValid(((Boolean )newvalue).booleanValue()); 107 } 108 } 109 } 110 }); 111 sendEmailPanel.checkJndiName(); 112 113 Object option = DialogDisplayer.getDefault().notify(dialogDescriptor); 114 if (option == NotifyDescriptor.OK_OPTION) { 115 try { 116 117 String jndiName = generateJNDILookup(sendEmailPanel.getJndiName(), erc, srcFile, beanClass.getQualifiedName()); 122 if (jndiName != null) { 123 String 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 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 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 generateJNDILookup(String jndiName, EnterpriseReferenceContainer erc, FileObject fileObject, String className) throws IOException { 154 ResourceRef ref = erc.createResourceRef(className); 155 if (ref != null) { 156 ref.setResRefName(jndiName); 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"); return erc.addResourceRef(ref, fileObject, className); 161 } 162 return null; 163 } 164 165 private void generateMethods(Project project, FileObject fileObject, String className, 166 String jndiName, String simpleName, ServiceLocatorStrategy slStrategy) throws IOException { 167 String memberName = _RetoucheUtil.uniqueMemberName(fileObject, className, simpleName, "mailResource"); if (Utils.isJavaEE5orHigher(project) && InjectionTargetQuery.isInjectionTarget(fileObject, className)) { 169 generateInjectedField(fileObject, className, simpleName, memberName); 170 generateSendMailMethod(fileObject, className, memberName, null); 171 } else { 172 String sessionGetter = generateLookupMethod(fileObject, className, jndiName, simpleName, slStrategy); 173 generateSendMailMethod(fileObject, className, memberName, sessionGetter); 174 } 175 } 176 177 private void generateSendMailMethod(FileObject fileObject, final String className, String sessionVariableName, String sessionGetter) throws IOException { 178 179 List <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 <String > exceptions = Arrays.asList(new String [] { 186 javax.naming.NamingException .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 { 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 getSendCode(String sessionVariableName, String 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 generateLookupMethod(FileObject fileObject, final String className, String jndiName, String simpleName, 221 ServiceLocatorStrategy slStrategy) throws IOException { 222 String sessionGetter = "get" + simpleName.substring(0, 1).toUpperCase() + simpleName.substring(1); 223 sessionGetter = _RetoucheUtil.uniqueMemberName(fileObject, className, sessionGetter, "mailResource"); 224 String 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 .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 { 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 getSessionCode(String jndiName, ServiceLocatorStrategy slStrategy, FileObject fileObject, String className) { 253 String mailLookupString = slStrategy.genMailSession(jndiName, fileObject, className); 254 return "return (javax.mail.Session) " + mailLookupString + ";\n"; } 256 257 private String getSessionCode(String jndiName) { 258 return MessageFormat.format( 259 "javax.naming.Context c = new javax.naming.InitialContext();\n" + "return (javax.mail.Session) c.lookup(\"java:comp/env/{0}\");\n", new Object [] {jndiName}); 262 } 263 264 private void generateInjectedField(FileObject fileObject, String className, String jndiName, String simpleName) throws IOException { 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 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 { 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 ioe) { 313 ErrorManager.getDefault().notify(ioe); 314 } 315 return false; 316 } 317 318 public Action 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 |