PDA

View Full Version : Mail function using springmvc and extjs



sachintaware
30 Mar 2012, 4:25 AM
I am working on a mail application using springMVC and hibernate.
I have used the MailService for sending the email.But,I get the following error
Debug log for mail


DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre6\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre6\lib\javamail.address.map (The system cannot find the file specified)
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP u5sm4666866pbu.76
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO office-l58g7rse
250-mx.google.com at your service, [122.169.38.83]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO office-l58g7rse
250-mx.google.com at your service, [122.169.38.83]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
c2FjaGl0YXdhcmUyMQ==
334 UGFzc3dvcmQ6
MjExMDg4c2FjaGlu
235 2.7.0 Accepted
DEBUG SMTP: use8bit false
MAIL FROM:<sachitaware21@gmail.com>
250 2.1.0 OK u5sm4666866pbu.76
RCPT TO:<sachitaware21@gmail.com>
250 2.1.5 OK u5sm4666866pbu.76
DEBUG SMTP: Verified Addresses
DEBUG SMTP: sachitaware21@gmail.com
DATA
354 Go ahead u5sm4666866pbu.76
Date: Thu, 29 Mar 2012 15:27:19 +0530 (IST)
From: sachitaware21@gmail.com
To: sachitaware21@gmail.com
Message-ID: <19097634.01333015039154.JavaMail.Administrator@office-l58g7rse>
Subject: TEst
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Test@@@@EEEEEWWWWdssfdg
.
250 2.0.0 OK 1333015042 u5sm4666866pbu.76
QUIT
221 2.0.0 closing connection u5sm4666866pbu.76
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP j3sm4689853pbb.29
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO office-l58g7rse
250-mx.google.com at your service, [122.169.38.83]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO office-l58g7rse
250-mx.google.com at your service, [122.169.38.83]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
c2FjaGl0YXdhcmUyMQ==
334 UGFzc3dvcmQ6
MjExMDg4c2FjaGlu
235 2.7.0 Accepted
DEBUG SMTP: use8bit false
MAIL FROM:<sachitaware21@gmail.com>
250 2.1.0 OK j3sm4689853pbb.29
RCPT TO:<sachitaware21@gmail.com>
250 2.1.5 OK j3sm4689853pbb.29
DEBUG SMTP: Verified Addresses
DEBUG SMTP: sachitaware21@gmail.com
DATA
354 Go ahead j3sm4689853pbb.29
Date: Thu, 29 Mar 2012 15:27:24 +0530 (IST)
From: sachitaware21@gmail.com
To: sachitaware21@gmail.com
Message-ID: <21565491.11333015044853.JavaMail.Administrator@office-l58g7rse>
Subject: Alert - Exception occurred
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Exception occurred
.
250 2.0.0 OK 1333015048 j3sm4689853pbb.29
QUIT
221 2.0.0 closing connection j3sm4689853pbb.


This seems fine and the mails are sent properly as required.
Here,is the error in firebug and due to this I don't get a success message of the mail delivery.
In firebug console I get an error like this under the response tab.


uncaught exception: [Exception... "'You're trying to decode an invalid JSON String: ' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "JS frame :: resource://firebug_rjs/net/spy.js :: callPageHandler :: line 798" data: no]`


and this under XML tab


XML Parsing Error: no element found Location: moz-nullprincipal:{564d3946-b1b0-48d4-8791-8a5ea8069a85} Line Number 1, Column 1:

^



But,I checked the returned Json and it is in the correct format.And it is returned before the mail function is even called.

This is my config file for spring bean

<!--*************************** E-Mail bean******************************-->

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="587"/>
<property name="username" value="sachitaware21"/>
<property name="password" value="mypass"/>
<property name="javaMailProperties">
<props>
<!-- Use SMTP transport protocol -->
<prop key="mail.transport.protocol">smtp</prop>
<!-- Use SMTP-AUTH to authenticate to SMTP server -->
<prop key="mail.smtp.auth">true</prop>
<!-- Use TLS to encrypt communication with SMTP server -->
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>

<bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from">
<value>sachitaware21@gmail.com</value>
</property>
<property name="to">
<value>sachitaware21@gmail.com</value>
</property>
<property name="subject" value="Alert - Exception occurred"/>
</bean>

Can someone guide me through this??

Thanks
Sachin
S/W Engg
www.optionsconsultancy.com (http://www.optionsconsultancy.com)

mitchellsimoens
30 Mar 2012, 9:42 AM
It's saying the JSON is invalid. Have you made sure it's valid JSON?

sachintaware
30 Mar 2012, 11:05 AM
Yes the JSON is very much valid.Infact it is returned even before I go to the email function.(I use store content already fetched for sending mails).So,the JSON is returned before this.Also,when I check it in CHROME browser,no such error is generated and I get a Mail success message :-?. Mozilla FF gives this error and gets stuck on the progress bar once I submit the mail form.

Thanks
Sachin
S/W Engg
www.optionsconsultancy.com

sachintaware
1 Apr 2012, 9:45 PM
@mitchellsimoens
This is what I get under the XML tab in firebug,tried to google and learnt that response may be a problem.I have added the js that throws the error with line number.Please guide me over this.



XML Parsing Error: no element found Location: moz-nullprincipal:{564d3946-b1b0-48d4-8791-8a5ea8069a85} Line Number 1, Column 1:





originalHandler.handleEvent(event); spy.js (line 798)




This is what I return on success and failure.Works fine in Chrome but not in FF


var f = Ext.getCmp('sendEmailForm');
f.form.submit({
reset: true,
url:'email/view.action',
method:'Post',
waitMsg:'Sending Email...',
success:function(form,action){

Ext.Msg.alert('Status', 'Mail has been sent Successfully!!', function(btn, text){
if (btn == 'ok'){
// var redirect = 'success.html';
// window.location = redirect;

}
});
},

failure:function(form, action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Login Failed!', obj.errors.reason);
//Ext.Msg.alert('Login Failed!');
}
else{
Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText);
}

}

});

sachintaware
12 Apr 2012, 4:35 AM
@mitchellsimoens
I am still stuck with the issue.Can you please suggest any clue?

Thanks
Sach

friend
14 May 2012, 5:36 AM
So you have something to compare against, here's my Spring bean config for the JavaMailSender:



<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="protocol" value="smtps" />
<property name="username" value="yourGmailAccountName@gmail.com" />
<property name="password" value="yourpassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtps.auth">true</prop>
<prop key="mail.smtps.starttls.enable">true</prop>
<prop key="mail.smtps.debug">true</prop>
</props>
</property>
</bean>


And here's my Controller method which constructs/sends email, noting that I go overboard on input parameter checking, in case a user tries hacking around with the request parameters. Note that I'm using the Jackson JSON Mapping view support in Spring 3.1, hence the return type annotation of @ResponseBody where Spring auto-magically handles the content type and JSON conversion:



@RolesAllowed({Utility.ROLE_ADMIN,Utility.ROLE_EMAIL_USERS})
@RequestMapping("/user/emailSubmit")
public @ResponseBody Map<String,Object> emailSubmit(Authentication auth,
@RequestParam("from") String from, @RequestParam("to") String to, @RequestParam("subject") String subject,
@RequestParam("message") String message)
{
// simple utility method which constructs a new Map and adds
// a default "success"/true key/value pair.
Map<String,Object> results = Utility.getJsonResultMap();

if (from == null || from.isEmpty()) {
results.put("success", false);
results.put("title", "Error");
results.put("msg", "Please enter a 'From' email address.");
}
else if (!Utility.isValidEmailAddress(from)) {
results.put("success", false);
results.put("title", "Error");
results.put("msg", "Invalid 'From' email address.");
}
else if (to == null || to.isEmpty()) {
results.put("success", false);
results.put("title", "Error");
results.put("msg", "Please enter one or more 'To' email addresses.");
}
else if (subject == null || subject.isEmpty()) {
results.put("success", false);
results.put("title", "Error");
results.put("msg", "Please enter a 'Subject' for your email.");
}
else if (message == null || message.isEmpty()){
results.put("success", false);
results.put("title", "Error");
results.put("msg", "Please enter a message for the body of your email.");
}
else {

MimeMessage mailMessage = this.mailSender.createMimeMessage();
MimeMessageHelper helper = null;

try
{
helper = new MimeMessageHelper(mailMessage, true);

String[] recipients = to.split(",");
for (String address : recipients) {
if (!Utility.isValidEmailAddress(address)) {
results.put("success", false);
results.put("title", "Error");
results.put("msg", "Email '" + address + "' in the list of recipients doesn't appear to be valid.");
return results;
}

helper.setTo(address.trim());
}


helper.setFrom(from);
helper.setSubject(subject);
helper.setSentDate(new Date());
helper.setText(message, true);

this.mailSender.send(mailMessage);

results.put("msg", "Email sent successfully.");
results.put("title", "Email Sent");

}
catch (Exception e)
{
logger.error("Error sending user email: " + e);
results.put("success", false);
results.put("title", "Error sending email");
results.put("msg", "An error occurred while attempting to send your email. Please contact Tech Support.");
}
}

return results;
}


This code is currently used in a production app and works well.

sachintaware
14 May 2012, 8:58 PM
Thanks @friend

I have problem with applicationContext.xml for bean definition in my project.


ApplicationContext context = new FileSystemXmlApplicationContext("C:/Documents and Settings/Administrator/workspace/StaffingApplication/WebContent/WEB-INF/applicationContext.xml");


I have to give the absolute path here(on my machine) and in production for it to work i have to give a relative one.

When I try to give a relative path I get an error


File not found exception:Cannot find applicationContext.xml at given path.


For example this one doesn't work.So the path has to be given relative to .java files or .class files in the classes folder.(Confused a bit) :s


ApplicationContext context = new FileSystemXmlApplicationContext("WEB-INF/applicationContext.xml");


I tried to read about it and went through examples,but I am not able to resolve it.(Learnt that FileSystemXmlApplicationContext requires the entire path )
This is the navigation view of my app.How can I resolve this issue.Please throw some light on it.

35223

Thanks

friend
15 May 2012, 4:21 AM
I noticed that the PHP error message you posted shows the file name as applicationContect.xml instead of applicationContext.xml. That may be the problem. Also, I kinda confused about the use of PHP when you have a Java Web container on the backend.

Regardless, as for file paths, Spring uses root-relative paths in its config files. Note that I never load the application context manually. I let the web container do all the work by specifying everything in Tomcat's web.xml.

Below is a pared-down example of my web.xml which loads the application and servlet context configs for me, where I also have a Spring Security config in there. Note that I'm old-school/retarded and like '.action' on the end of my URL mappings. A more modern approach would be to place all of your MVC-related URL mappings into an 'mvc' context instead:



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MyApp</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>myapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/myapp-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- Any request which ends with ".action" gets serviced. -->
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>

<!-- The client app uses a 15 minute session timeout, where a 2 minute slop factor is
added here. -->
<session-config>
<session-timeout>17</session-timeout>
</session-config>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>


For thoroughness, here's my applicationContext.xml as well, noting that I break everything out into separate XML files for compartmentalization/ease of reading:



<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

<mvc:annotation-driven/>

<context:component-scan base-package="com.stinkypete.myapp" />

<!-- <aop:aspectj-autoproxy /> -->

<import resource="application-data.xml" />
<import resource="application-security.xml" />
<import resource="application-utility.xml" />
</beans>


The included application-data.xml:



<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

<!-- DataSource configured in Tomcats conf/context.xml and referenced as a JNDI object. -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/myapp" />
</bean>

<!-- For those times when you just want to do simple SQL and get a Map of name/value pairs. -->
<bean id="npjt" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" autowire-candidate="true">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>

<!-- Hibernate SessionFactory instance, which allows you to get at the current Session. -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />

<!-- Instructs Spring to scan only the target package for Domain Entities. -->
<property name="packagesToScan" value="com.stinkypete.myapp.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<!-- Set show_sql to true if you want to see Hibernate's SQL on the Eclipse console. -->
<prop key="hibernate.show_sql">false</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
</props>
</property>
</bean>

<!-- Let the transaction manager know how to get a Session. -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- Enable Transactions via annotations. -->
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>


My application-security.xml config, noting that I use a SALT Source for password hashing/comparison:



<?xml version="1.0" encoding="UTF-8"?>
<b:beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns="http://www.springframework.org/schema/security"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<!-- ============================================================================
== SPRING SECURITY CONFIGURATION ==========================================
============================================================================
Encapsulates all Spring Security Configuration. All security settings
are mananged here, including role-based user access by URL pattern and
authentication mechanism configuration.
============================================================================ -->


<!-- ============================================================================
== GLOBAL SECURITY CONFIG ==================================================
============================================================================
The <global-method-security> tag enables the ability to annotate
individual Controller methods for security, like:

@RolesAllowed("ROLE_ADMIN")
@RolesAllowed({"ROLE_USER", "ROLE_GUEST"})
@PemitAll
@DenyAll
============================================================================ -->
<global-method-security jsr250-annotations="enabled" />

<!-- ============================================================================
== HTTP CONFIG =============================================================
============================================================================
In the <http> tag below, the 'use-expressions="true"' attribute
allows you to use complex boolean expressions when configuring the
'access' attributes of <intercept-url> tags, e.g.:

access="hasRole('ROLE_ADMIN') and hasIpAddress('192.168.1.0/24')"

Visit http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html
for details.
============================================================================ -->
<http auto-config="false" use-expressions="true">

<form-login
login-page="/loadLogin.action"
default-target-url='/home.action'
always-use-default-target="true"/>

<logout
logout-url="/logout"
logout-success-url="/loadLogin.action"
invalidate-session="true" />

<session-management
session-authentication-error-url="/loadLogin.action">
<concurrency-control
max-sessions="1"
error-if-maximum-exceeded="true" />
</session-management>


<!-- No security filters on public resources. -->
<intercept-url pattern="/loadLogin.action" access="permitAll" />
<intercept-url pattern="/forgotPword.action" access="permitAll" />
<intercept-url pattern="/requestPword.action" access="permitAll" />
<intercept-url pattern="/index.html" access="permitAll" />
<intercept-url pattern="/app.js" access="permitAll" />
<intercept-url pattern="/app/**" access="permitAll" />
<intercept-url pattern="/extjs/**" access="permitAll" />
<intercept-url pattern="/resources/**" access="permitAll" />

<intercept-url pattern="/**" access="isAuthenticated()" />
</http>


<b:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
<b:property name="userPropertyToUse" value="salt" />
</b:bean>

<b:bean id="hibernateUserService" class="com.stinkypete.myapp.security.MyUserService" />

<authentication-manager>
<authentication-provider user-service-ref="hibernateUserService">
<password-encoder hash="md5">
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authentication-manager>

</b:beans>


And lastly, my application-utility.xml stuff:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<!-- ===========================================================================
== APPLICATION UTILITY ==
== General/utility beans, properties files, etc. ==
===========================================================================

============================================================================
== JAVA MAIL USING SECURE SMTP =============================================
============================================================================
Here a more complex example of using Secure SMTP to send email via
a foreign mail host (Gmail, in this case).
============================================================================ -->

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="protocol" value="smtps" />
<property name="username" value="yourGmailAccountName@gmail.com" />
<property name="password" value="yourpassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtps.auth">true</prop>
<prop key="mail.smtps.starttls.enable">true</prop>
<prop key="mail.smtps.debug">true</prop>
</props>
</property>
</bean>
-->


<!-- =============================================================================
== File Upload Multipart Resolver ===========================================
=============================================================================
If your application has need to upload files, Spring's
CommonsMultipartResolver bean will allow you to control the maximum upload
size, set default encoding, etc.

In this example, a maximum file size of 10Meg (specified in bytes)
can be uploaded.
============================================================================= -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>




<!-- =============================================================================
== Global Properties File ===================================================
=============================================================================
If your application requires any configuration properties, you can
load the Properties files from the classpath, as a named bean. You can
then inject the bean into any classes which need access to the properties.

In this example, global.properties is placed in the root of the /src folder.

If you need to dynamically insert properties into your application's context
config at startup, visit the documentation for PropertyPlaceholderConfigurer.
============================================================================= -->
<bean id="globalProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:global.properties"/>
</bean>

</beans>


And the overall project layout:

35248

sachintaware
15 May 2012, 5:11 AM
@friend
Thanks for the inputs,will go through for sure.
That was a typo(applicationContext it is as in the layout image.)!!!

Also,I changed the tag mistakenly to PHP and did not notice.When you said I realised that's why they are showing up in colors.

Will edit the question.
This is the exact error



SEVERE: Servlet.service() for servlet in context with path threw exception [Request processing failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [C:\Documents and Settings\Administrator\workspace\StaffingApplication\WebContent\WEB-INF\applicationContext.xml]; nested exception is java.io.FileNotFoundException: C:\Documents and Settings\Administrator\workspace\StaffingApplication\WebContent\WEB-INF\applicationContext.xml (The system cannot find the path specified)] with root cause
java.io.FileNotFoundException: C:\Documents and Settings\Administrator\workspace\StaffingApplication\WebContent\WEB-INF\applicationContext.xml (The system cannot find the path specified)



Thanks

friend
15 May 2012, 5:35 AM
I think the root cause of your problem is attempting to manually load the application context. Is there a reason you need to do so?

sachintaware
15 May 2012, 8:24 AM
Actually,the examples I have been going through have the same configuration and I am following them(Following some tutorials from websites)!!
Please suggest a better alternative or the standard solution,so that I have a permanent solution.

Thanks

friend
15 May 2012, 8:47 AM
The main point I'm trying to make is that you shouldn't be trying to manually load the application context XML file. This is automatically handled for you via the WEB-INF/web.xml configuration.

I don't know at what point in your application you're doing it, but this piece of code is not needed and should be deleted:



ApplicationContext context = new FileSystemXmlApplicationContext("C:/Documents and Settings/Administrator/workspace/StaffingApplication/WebContent/WEB-INF/applicationContext.xml");

sachintaware
15 May 2012, 9:00 PM
Yes got your point friend.
Actually,earlier I had configured my bean in the xml file.As posted before.
And the the reason for using it there was I had the mailService object of the bean that I was using to call the MailService class' "sendMail" function.



ApplicationContext context = new FileSystemXmlApplicationContext("WEB-INF/applicationContext.xml");
MailService mailService = (MailService) context.getBean("mailService");
mailService.sendMail(from,toAddress,subject,mailBody);


MailService class



@Service("mailService")
public class MailService {

@Autowired
private MailSender mailSender;
@Autowired
private SimpleMailMessage alertMailMessage;


public void sendMail(String from, String[] toAddress, String subject, String mailBody)throws MailException {
...
...
}


But now I have fixed it.
Thanks for your continuous support.

sachintaware
15 May 2012, 9:59 PM
@friend
but still I am not able to fix the original error,went through your files and I have not used Jackson
but JSON Array and JSON Object(but that should not be the reason I suppose)
And also,the Json is handled(i.e the list is retrieved from database) before even the mail is sent to the list.
but the error comes when the mail is sent.

Again i would like to highlight, I GET THIS IN FIREFOX (firebug)and NOT IN CHROME BROWSER.(In chrome I get the mail sent successfully message)
Reproducing the error.


uncaught exception: [Exception... "'You're trying to decode an invalid JSON String: ' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "JS frame :: chrome://firebug/content/net/spy.js :: callPageHandler :: line 812" data: no]
http://localhost:9191/StaffingApplication/js/ext-all-debug.js

Line 20820 :
disableCache = options.disableCaching !== false ? (options.disableCaching || me.disableCaching) : false; //This line is from ext-all-debug.js


My Controller code:


@RequestMapping(value = "/email/view.action", method = RequestMethod.POST)
public Object emailView(HttpServletRequest req,HttpServletResponse res) throws AddressException{

/*********************Mail function*********************/

String from="sachitaware21@gmail.com";
String[] toAddress = (req.getParameter("to").split(","));

InternetAddress[] addressTo = new InternetAddress[toAddress.length];
for (int i = 0; i < toAddress.length; i++)
{
addressTo[i] = new javax.mail.internet.InternetAddress(toAddress[i]);
}
String subject = req.getParameter("subject");
String mailBody =req.getParameter("body");
String firstName = (req.getParameter("firstName"));


MailService mailService = new MailService();
mailService.sendMail(from,toAddress,subject,mailBody);
//mailService.sendAlertMail("Exception occurred");

return null;

}
//JSON to iterate over the results and send to the extjs view

@SuppressWarnings("unchecked")
private Map<String,Object> getMap(List<CandidateStatus> candidatestatus){

// Map<String,Object> modelMap = new HashMap<String,Object>(3);
// Map<String,Object> candDetails = new HashMap<String,Object>(7);

Iterator<CandidateStatus> iterator=candidatestatus.iterator();
CandidateStatus astring = new CandidateStatus();

JSONArray jArray = new JSONArray();
while(iterator.hasNext())
{
JSONObject candDetails = new JSONObject();
astring = iterator.next();

candDetails.put("clientName",astring.getRequirement().getClient().getClientName());
candDetails.put("firstName",astring.getCandidate().getFirstName());
candDetails.put("lastName",astring.getCandidate().getLastName());
candDetails.put("email",astring.getCandidate().getEmail());
candDetails.put("phone",astring.getCandidate().getPhone());
candDetails.put("statusTitle",astring.getStatusTitle());
candDetails.put("reqTitle",astring.getRequirement().getReqTitle());

jArray.add(candDetails);
}
//System.out.println("----"+candDetails+"----");
JSONObject modelMap = new JSONObject();
modelMap.put("success",true);
modelMap.put("totalCount",jArray.size());
modelMap.put("data", jArray);
modelMap.toString();
return modelMap;




MailServce class



@Service("mailService")
public class MailService {

@Autowired
private MailSender mailSender;
@Autowired
private SimpleMailMessage alertMailMessage;


public void sendMail(String from, String[] toAddress, String subject, String mailBody)throws MailException {

/*************Get the username from session***************/

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName(); //get logged in username

System.out.println("----Username is-------"+username+"--------------");

SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(toAddress);
message.setSubject(subject);
message.setText(mailBody);

Properties props = new Properties();
JavaMailSenderImpl sender = new JavaMailSenderImpl();

props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.debug", "true");

sender.setHost("smtp.gmail.com");
sender.setPort(587);

if(username.equals("options")){
sender.setUsername("sachitaware21");
sender.setPassword("mypasswd");
sender.setJavaMailProperties(props);

}
else if (username.equals("options1")){
sender.setUsername("newastronsolutions");
sender.setPassword("mypasswd");
sender.setJavaMailProperties(props);
}

try {
sender.send(message);
// mailSender.send(message);
}catch(MailException exception)
{
//log the message and go on
System.err.println(exception.getMessage());
}

}

}


I am not using a bean to set the config as I have to change the Email Id based on the current logged in user.
But not able to fix the firebug error I mentioned at the top.

Thanks

friend
16 May 2012, 4:38 AM
I noticed that your Controller request mapping ('email/view.action') is returning a null and I don't see that your request handler is returning a ModelMap either. It looks like there's no JSON response to be decoded.

I always return a JSON response from all request mappings, with a minimum of success: true.

sachintaware
16 May 2012, 5:20 AM
I have tried doing that earlier,but will think over it surely.Also,is it that Chrome and Mozilla behave differently over the same??

Also,to add I am giving the error under the XML tab in the firebug console.



XML Parsing Error: no element found Location: moz-nullprincipal:{02e54f82-a834-4424-9a75-e6d1574fce98} Line Number 1, Column 1:


Thanks

friend
16 May 2012, 10:50 AM
It's really hard to debug a problem such as this without seeing the big picture.

I'm thinking that a full, working example app with user authentication (login/logout), email functionality and the use of Spring MVC native JSON view handling would help you.

It will take me a bit of time, but I'm willing to take a production app, strip it down to just user authentication and email functions (and maybe an innocuous CRUD page), zip up the Eclipse project, do a mysql dump on a test database and share these artifacts with you.

I'll include a 'readme.txt' on importing the Eclipse project, importing the MySQL database and Tomcat JNDI datasource config via conf/context.xml. Seeing a working example will probably save us both a ton of forum posts. :]

Again, It'll take a while to do this, but I'll send you a 'private message' via the forums when it's ready and provide a download link.

sachintaware
17 May 2012, 7:42 AM
That would really do a WORLD of good!!!!!!
You are a gem of a person.Will wait for that.

And close the thread on that note!!! :) :D

Thanks