Mail not sending using javaMail - spring

In my application I am sending mail using spring. it works fine when I am sending mail from any gmail id, but when I am sending from another smtp server then mail is not sending.
My spring configuration for gmail:
<beans>
<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="diganta.XXXXX#gmail.com" />
<property name="password" value="******" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="requestToAcceptOrDeny" class="com.edfx.adb.mail.RequestToAcceptOrDeny">
<property name="mailSender" ref="mailSender" />
</bean>
</beans>
But when I change the configuration into :
<property name="host" value="mail.mycompany.co.in" />
<property name="port" value="25" />
<property name="username" value="XXX#mycompany.co.in" />
<property name="password" value="abc123" />
then no exception is generating, but mail is also not sending, password is also not checking, ie given password is right or not. I can't understand where I have done wrong.
Can anyone help me? Thanks
Update-1
16:29:23,524 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Hibernate: select user0_.ID as ID7_0_, user0_.CREATE_TIMESTAMP as CREATE2_7_0_, user0_.LAST_UPDATE_TIMESTAMP as LAST3_7_0_, user0_.VERSION as VERSION7_0_, user0_.ACTIVE as ACTIVE7_0_, user0_.DATE_OF_BIRTH as DATE6_7_0_, user0_.DATE_OF_JOINING as DATE7_7_0_, user0_.DATE_OF_RELEASE as DATE8_7_0_, user0_.FIRST_NAME as FIRST9_7_0_, user0_.FULL_NAME as FULL10_7_0_, user0_.HOME_PHONE as HOME11_7_0_, user0_.HOME_POSTAL_ADDRESS as HOME12_7_0_, user0_.LAST_NAME as LAST13_7_0_, user0_.MAIL as MAIL7_0_, user0_.MOBILE as MOBILE7_0_, user0_.ROLE as ROLE7_0_, user0_.USERNAME as USERNAME7_0_ from USER user0_ where user0_.ID=?
16:29:23,534 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: JavaMail version 1.4.4
16:29:23,534 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: Tables of loaded providers
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 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]}
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 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]}
16:29:23,544 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
16:29:23,594 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Sending email ....
16:29:23,594 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
16:29:23,604 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: useEhlo true, useAuth true
16:29:23,604 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: trying to connect to host "mail.mycompany.co.in", port 25, isSSL false
16:29:24,634 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 220 mail.mycompany.co.in ESMTP Postfix
16:29:24,644 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: connected to host "mail.mycompany.co.in", port: 25
16:29:24,644 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:24,644 INFO [stdout] (http-localhost-127.0.0.1-8080-1) EHLO EDFX-DESKTOP-28
16:29:24,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-mail.mycompany.co.in
16:29:24,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-PIPELINING
16:29:24,865 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-SIZE 10240000
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-VRFY
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-ETRN
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-ENHANCEDSTATUSCODES
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250-8BITMIME
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 DSN
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "PIPELINING", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "SIZE", arg "10240000"
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "VRFY", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "ETRN", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "8BITMIME", arg ""
16:29:24,875 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Found extension "DSN", arg ""
16:29:24,895 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: use8bit false
16:29:24,895 INFO [stdout] (http-localhost-127.0.0.1-8080-1) MAIL FROM:<Temp#EDFX-DESKTOP-28>
16:29:25,135 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 2.1.0 Ok
16:29:25,135 INFO [stdout] (http-localhost-127.0.0.1-8080-1) RCPT TO:<diganta.xxx#gmail.com>
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 2.1.5 Ok
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: Verified Addresses
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DEBUG SMTP: diganta.xxxx#gmail.com
16:29:25,365 INFO [stdout] (http-localhost-127.0.0.1-8080-1) DATA
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 354 End data with <CR><LF>.<CR><LF>
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Date: Fri, 3 May 2013 16:29:24 +0530 (IST)
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) To: diganta.xxxx#gmail.com
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Message-ID: <628313650.2.1367578764895.JavaMail.Temp#EDFX-DESKTOP-28>
16:29:25,615 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Subject: Request to Remove Rounak Dey's Activity's Manager privilege from
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) activity EFXL13001
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) MIME-Version: 1.0
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Type: multipart/mixed;
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) boundary="----=_Part_0_263230409.1367578763564"
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_0_263230409.1367578763564
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Type: multipart/related;
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) boundary="----=_Part_1_1514490209.1367578763584"
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_1_1514490209.1367578763584
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Type: text/html; charset=us-ascii
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) Content-Transfer-Encoding: 7bit
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) <html><body><a href=http://localhost:8080/ActivityDatabase/req/AcceptOrDenyPermision.xhtml?activityId=EFXL13001&uniqueId=7fe18301-0bde-48da-a7d1-2bbe43b95e98&emailId=diganta.xxxx#gmail.com>Accept Or Deny request..</a></body></html>
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_1_1514490209.1367578763584--
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1)
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ------=_Part_0_263230409.1367578763564--
16:29:25,625 INFO [stdout] (http-localhost-127.0.0.1-8080-1) .
16:29:25,855 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 250 2.0.0 Ok: queued as 164B322AB7
16:29:25,855 INFO [stdout] (http-localhost-127.0.0.1-8080-1) QUIT
16:29:26,046 INFO [stdout] (http-localhost-127.0.0.1-8080-1) 221 2.0.0 Bye

I also encountered same situation as OP. I use Spring mail to send mail and test with a gmail account work perfectly then when I apply my company mail, it didn't throw any exception but no mail received.
It took me several hours of googling, seeing debug log and trying many config but not work.
Then I write a java program using javax.mail to test and everything works. I realize the difference is in the java program I set From mail account (same as username property in spring config).
E.g. that is
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("XXX#mycompany.co.in"));
That solved the problem.

Your server doesn't support STARTTLS and won't let you authenticate unless you connect over SSL to begin with. Without authenticating, it won't deliver mail outside of your domain. Assuming you're using a new version of JavaMail, set the property "mail.smtp.ssl" to "true".

package com.karthik.spring;
import java.io.IOException;
import java.io.InputStream;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
#Controller
#RequestMapping("/sendEmail.do")
public class SendEmailAttachController {
#Autowired
private JavaMailSender mailSender;
#RequestMapping(method = RequestMethod.POST)
public String sendEmail(HttpServletRequest request,
final #RequestParam CommonsMultipartFile attachFile) {
// Input here
final String emailTo = request.getParameter("mailTo");
final String subject = request.getParameter("subject");
final String yourmailid = request.getParameter("yourmail");
final String message = request.getParameter("message");
// Logging
System.out.println("emailTo: " + emailTo);
System.out.println("subject: " + subject);
System.out.println("Your mail id is: "+yourmailid);
System.out.println("message: " + message);
System.out.println("attachFile: " + attachFile.getOriginalFilename());
mailSender.send(new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper messageHelper = new MimeMessageHelper(
mimeMessage, true, "UTF-8");
messageHelper.setTo(emailTo);
messageHelper.setSubject(subject);
messageHelper.setReplyTo(yourmailid);
messageHelper.setText(message);
// Attachment with mail
String attachName = attachFile.getOriginalFilename();
if (!attachFile.equals("")) {
messageHelper.addAttachment(attachName, new InputStreamSource() {
#Override
public InputStream getInputStream() throws IOException {
return attachFile.getInputStream();
}
});
}
}
});
return "Result";
}
}
**spring-mvc.xml**
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.karthik.spring" />
<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="xxxx#gmail.com" />
<property name="password" value="xxxx" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">Error</prop>
</props>
</property>
</bean>
</beans>

Related

Data is not written into the XML file from mongodb using Spring Batch, Why?

I am developing Spring Batch MongoDB to XML example. I was successfully developed the application, but I dont see data is getting written into the XML file. Could you please guide me what is the issue ? I dont see any working example yet on the web.
job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd">
<!-- Actual Job -->
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mongodbItemReader" writer="xmlItemWriter" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mongodbItemReader" class="org.springframework.batch.item.data.MongoItemReader">
<property name="template" ref="mongoTemplate" />
<property name="collection" value="report" />
<property name="targetType" value="com.mkyong.model.Report" />
<property name="query" value="{'_id':{$gt:0} }" />
<property name="sort">
<util:map>
<entry key="id" value="#{T(org.springframework.data.domain.Sort.Direction).ASC}" />
</util:map>
</property>
</bean>
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="classpath:xml/report.xml" />
<property name="marshaller" ref="reportUnMarshaller" />
<property name="rootTagName" value="record" />
</bean>
<bean id="reportUnMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>com.mkyong.model.Report</value>
</property>
</bean>
</beans>
App.java
public class App {
public static void main(String[] args) {
String[] springConfig = { "database.xml", "context.xml", "job-report.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
Logs from console:
14:58:52.487 [main] DEBUG o.s.b.c.s.c.StepContextRepeatCallback - Preparing chunk execution for StepContext: org.springframework.batch.core.scope.context.StepContext#aa594b
14:58:52.487 [main] DEBUG o.s.b.c.s.c.StepContextRepeatCallback - Chunk execution starting: queue size=0
14:58:52.487 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [null]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.487 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Starting repeat context.
14:58:52.487 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat operation about to start at count=1
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - find using query: { "_id" : { "$gt" : 0}} fields: null for class: class com.mkyong.model.Report in collection: report
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Getting Mongo Database name=[yourdb]
14:58:52.488 [main] DEBUG o.s.data.mongodb.core.MongoDbUtils - Registering Spring transaction synchronization for MongoDB instance yourdb.
14:58:52.488 [main] DEBUG org.mongodb.driver.protocol.query - Sending query of namespace yourdb.report on connection [connectionId{localValue:3, serverValue:53}] to server 127.0.0.1:27017
14:58:52.489 [main] DEBUG org.mongodb.driver.protocol.query - Query completed
14:58:52.489 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat is complete according to policy and result value.
14:58:52.489 [main] DEBUG o.s.b.c.s.item.ChunkOrientedTasklet - Inputs not busy, ended: true
14:58:52.489 [main] DEBUG o.s.b.core.step.tasklet.TaskletStep - Applying contribution: [StepContribution: read=0, written=0, filtered=0, readSkips=0, writeSkips=0, processSkips=0, exitStatus=EXECUTING]
14:58:52.489 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Participating in existing transaction
14:58:52.490 [main] DEBUG o.s.b.core.step.tasklet.TaskletStep - Saving step execution before commit: StepExecution: id=1, version=5, name=step1, status=STARTED, exitStatus=EXECUTING, readCount=4, filterCount=0, writeCount=4 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=5, rollbackCount=0, exitDescription=
14:58:52.490 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Participating in existing transaction
14:58:52.491 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.491 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#a8ee09]
14:58:52.492 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Repeat is complete according to policy and result value.
14:58:52.492 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution success: id=1
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#5b3037]
14:58:52.492 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.494 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.494 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#baa89c]
14:58:52.495 [main] DEBUG o.s.batch.core.step.AbstractStep - Step execution complete: StepExecution: id=1, version=7, name=step1, status=COMPLETED, exitStatus=COMPLETED, readCount=4, filterCount=0, writeCount=4 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=5, rollbackCount=0
14:58:52.495 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.496 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.496 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#1f2ebae]
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.step1 with status=COMPLETED
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Handling state=reportJob.end1
14:58:52.496 [main] DEBUG o.s.b.c.job.flow.support.SimpleFlow - Completed state=reportJob.end1 with status=COMPLETED
14:58:52.497 [main] DEBUG o.s.batch.core.job.AbstractJob - Job execution complete: JobExecution: id=0, version=1, startTime=Tue Jan 10 14:58:52 IST 2017, endTime=null, lastUpdated=Tue Jan 10 14:58:52 IST 2017, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[reportJob]], jobParameters=[{}]
14:58:52.497 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Creating new transaction with name [org.springframework.batch.core.repository.support.SimpleJobRepository.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
14:58:52.501 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Initiating transaction commit
14:58:52.501 [main] DEBUG o.s.b.s.t.ResourcelessTransactionManager - Committing resourceless transaction on [org.springframework.batch.support.transaction.ResourcelessTransactionManager$ResourcelessTransaction#498b0]
14:58:52.501 [main] INFO o.s.b.c.l.support.SimpleJobLauncher - Job: [FlowJob: [name=reportJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Exit Status : COMPLETED
Done
In this example, I do need to manually create xml/report.xml into the classpath. Ideally it should be automatic. Right?
I got the solution to this problem from the link: Complex XML using Spring Batch; StaxEventItemWriter ; Jaxb2Marshaller. Also I should use
<bean id="xmlItemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:outputs/report.xml" />
<property name="encoding" value="ISO-8859-1" />
<property name="version" value="1.0" />
<property name="marshaller" ref="reportMarshaller" />
<property name="rootTagName" value="record" />
</bean>

Why do I still get an AuthenticationCredentialsNotFoundException?

I thought I had the solution to this but unfortunately the problem does still occur and I have no idea what else I could do.
What I do is login as a user. My AuthenticationProvider does not check anything which means that any user can login at the moment.
The thing is, that sometimes the login does work. I get a request through and load data from the server. Sometimes I have to wait a little while, 1 or 2 minutes, and all of a sudden I start receive the AuthenticationCredentialsNotFoundException. From time to time I can not login at all at the first time. I have to send another request in order to be able to successfully login.
I can't see a pattern or anything that would lead me to the cause of this. So, here I start with my LoginService and my implementation of the AuthenticationProvider:
public class LoginService {
private AuthenticationProvider adminAuthenticationProvider;
public LoginService(DSLContext ctx, AuthenticationProvider adminAuthenticationProvider) {
this.adminAuthenticationProvider = adminAuthenticationProvider;
}
#Transactional
public void login(String userId, String password) {
CustomUserDetails user = new CustomUserDetails(userId, password, true, true, true, true, new ArrayList<GrantedAuthority>());
Authentication auth = new UsernamePasswordAuthenticationToken(user, password,
new ArrayList<GrantedAuthority>());
try {
auth = this.adminAuthenticationProvider.authenticate(auth);
} catch(BadCredentialsException e) {
throw e;
}
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
public class AdminAuthenticationProvider implements AuthenticationProvider {
private RestaurantAdminRepository restaurantAdminRepository;
public AdminAuthenticationProvider(DSLContext ctx) {
this.restaurantAdminRepository = new RestaurantAdminRepository(ctx);
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
CustomUserDetails user = (CustomUserDetails) authentication.getPrincipal();
List<String> roles = new ArrayList<>();
roles.add("ROLE_ADMIN");
Authentication customAuthentication = new CustomUserAuthentication(roles, authentication);
customAuthentication.setAuthenticated(true);
return customAuthentication;
}
#Override
public boolean supports(Class<? extends Object> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
Nothing special about that I guess. My calls are secured just by isAuthenticated()
#PreAuthorize("isAuthenticated()")
public List<StoreDTO> getAvailableStores() {
// ..
return result;
}
The next thing is the debug output including the output of my own code and org.springframework on TRACE debug level. You can see that the authorization is successful but that after some requests the exception gets thrown. Sorry for this large output. You can also look at it here.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.LoginServletImpl - Login request by userId: sfalk
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.LoginService - Login for sfalk
[http-bio-8080-exec-2] INFO com.mz.server.web.auth.AdminAuthenticationProvider - authenticate(), Username: sfalk
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - findByUsername(): sfalk
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - User found.
[http-bio-8080-exec-2] INFO com.mz.server.web.repository.StoreAdminRepository - Checking password for sfalk
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - Password valid.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - getPrincipal()
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - Setting user com.mz.server.web.auth.CustomUserDetails#684666d: Username: sfalk; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities to 'authenticated'.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.LoginService - User successfully authenticated [userId=sfalk]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requested available stores.
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getAvailableStores(); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - isAuthenticate(): true
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: com.mz.server.web.auth.CustomUserAuthentication#7d055aa6
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter#36d4a51, returned: 1
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - Trying to get available stores for ..
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - getPrincipal()
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - sfalk
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - Fetching stores for store_admin_id 1
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - Stores found..
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requesting items for store ..
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.Map com.mz.server.web.service.StoreService.getItems(java.lang.Long); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - isAuthenticate(): true
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: com.mz.server.web.auth.CustomUserAuthentication#7d055aa6
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter#36d4a51, returned: 1
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - Getting items.
[http-bio-8080-exec-2] DEBUG com.mz.server.web.repository.StoreAdminRepository - getItems
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/mz_db]
[http-bio-8080-exec-2] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
[http-bio-8080-exec-2] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requested offers from 2016-01-11T00:00:00.278+01:00 to 2016-01-17T00:00:00.278+01:00.
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - isAuthenticate(): true
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: com.mz.server.web.auth.CustomUserAuthentication#7d055aa6
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter#36d4a51, returned: 1
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
[http-bio-8080-exec-2] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
[http-bio-8080-exec-2] DEBUG com.mz.server.web.service.StoreService - Getting offers ..
[http-bio-8080-exec-2] DEBUG com.mz.server.web.auth.CustomUserAuthentication - getPrincipal()
[http-bio-8080-exec-1] DEBUG com.mz.server.web.servlet.StoreServletImpl - Requested offers from 2016-01-11T00:00:00.167+01:00 to 2016-01-17T00:00:00.167+01:00.
[http-bio-8080-exec-1] DEBUG org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String); target is of class [com.mz.server.web.service.StoreService]; Attributes: [[authorize: 'isAuthenticated()', filter: 'null', filterTarget: 'null']]
[http-bio-8080-exec-1] TRACE org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in Root WebApplicationContext: org.springframework.security.access.event.AuthenticationCredentialsNotFoundEvent[source=ReflectiveMethodInvocation: public java.util.List com.mz.server.web.service.StoreService.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String); target is of class [com.mz.server.web.service.StoreService]]
[http-bio-8080-exec-1] DEBUG com.mz.server.web.auth.CustomHttpSessionListener - AuthenticationCredentialsNotFoundEvent
Jän 12, 2016 11:27:02 PM org.apache.catalina.core.ApplicationContext log
SEVERE: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.util.List com.mz.shared.web.service.store.StoreServlet.getUpcomingOffersForCalendarWeek(java.lang.Long,java.lang.String,java.lang.String)' threw an unexpected exception: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:416)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:605)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:333)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:303)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:373)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:378)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:222)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.mz.server.web.service.StoreService$$EnhancerBySpringCGLIB$$b5728734.getUpcomingOffersForCalendarWeek(<generated>)
at com.mz.server.web.servlet.StoreServletImpl.getUpcomingOffersForCalendarWeek(StoreServletImpl.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:587)
... 25 more
The last thing are my application context configuration files. This is my configuration applicationContext-spring-acl.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">
<!-- Imports -->
<import resource="applicationContext-jooq.xml"/>
<!-- See 15.3.2 Built-In Expression #http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html#el-permission-evaluator -->
<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<!-- To use hasPermission() in expressions, configure a PermissionEvaluator -->
<property name="permissionEvaluator" ref="permissionEvaluator" />
<property name="roleHierarchy" ref="roleHierarchy" />
</bean>
<bean class="com.mahlzeit.server.web.auth.permission.CustomAclPermissionEvaluator" id="permissionEvaluator">
<constructor-arg ref="aclService" />
</bean>
<!-- Declare an acl service -->
<bean class="org.springframework.security.acls.jdbc.JdbcMutableAclService" id="aclService">
<constructor-arg ref="dataSource" />
<constructor-arg ref="lookupStrategy" />
<constructor-arg ref="aclCache" />
</bean>
<!-- Declare a lookup strategy -->
<bean id="lookupStrategy"
class="org.springframework.security.acls.jdbc.BasicLookupStrategy">
<constructor-arg ref="dataSource" />
<constructor-arg ref="aclCache" />
<constructor-arg ref="aclAuthorizationStrategy" />
<constructor-arg ref="auditLogger" />
</bean>
<!-- Declare an acl cache -->
<bean id="aclCache" class="org.springframework.security.acls.domain.EhCacheBasedAclCache">
<constructor-arg>
<bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:shared="true"/>
</property>
<property name="cacheName" value="aclCache" />
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy">
<constructor-arg>
<bean class="org.springframework.security.acls.domain.ConsoleAuditLogger" />
</constructor-arg>
</bean>
</constructor-arg>
<constructor-arg>
<bean
class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
<constructor-arg>
<list>
<bean
class="org.springframework.security.core.authority.SimpleGrantedAuthority">
<constructor-arg value="ROLE_ACL_ADMIN" />
</bean>
</list>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
<!-- Declare an acl authorization strategy -->
<bean id="aclAuthorizationStrategy" class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
<constructor-arg>
<list>
<bean
class="org.springframework.security.core.authority.SimpleGrantedAuthority">
<constructor-arg value="ROLE_ADMIN" />
</bean>
<bean
class="org.springframework.security.core.authority.SimpleGrantedAuthority">
<constructor-arg value="ROLE_ADMIN" />
</bean>
<bean
class="org.springframework.security.core.authority.SimpleGrantedAuthority">
<constructor-arg value="ROLE_ADMIN" />
</bean>
</list>
</constructor-arg>
</bean>
<!-- Declare an audit logger -->
<bean id="auditLogger"
class="org.springframework.security.acls.domain.ConsoleAuditLogger" />
<!-- http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.html -->
<bean id="roleHierarchy"
class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
<property name="hierarchy">
<value>
ROLE_ADMIN > ROLE_USER
ROLE_USER > ROLE_VISITOR
</value>
</property>
</bean>
<sec:global-method-security authentication-manager-ref="authenticationManager" pre-post-annotations="enabled">
<sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>
</beans>
And this is applicationContext-spring-security.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd"
>
<!-- Imports -->
<import resource="applicationContext-spring-acl.xml"/>
<sec:http pattern="/**" auto-config="true" use-expressions="true"/>
<bean id="httpSessionSecurityContextRepository" class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
<property name='allowSessionCreation' value='false' />
</bean>
<bean id="securityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
<constructor-arg ref="httpSessionSecurityContextRepository" />
</bean>
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<constructor-arg>
<list>
<sec:filter-chain pattern="/**" filters="securityContextPersistenceFilter" />
</list>
</constructor-arg>
</bean>
<bean id="authenticationListener" class="com.mahlzeit.server.web.auth.CustomAuthenticationListener"/>
<bean id="adminAuthenticationProvider" class="com.mahlzeit.server.web.auth.AdminAuthenticationProvider">
<constructor-arg ref="dslContext" />
</bean>
<bean id="userDetailsService" class="com.mahlzeit.server.web.service.CustomUserDetailsService"/>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="adminAuthenticationProvider"/>
</sec:authentication-manager>
</beans>
Thank you for any help that sheds some light on this.
It seems to me that the SecurityContextPersistenceFilter doesn't execute around your requests. I can see it is defined in your applicationContext-spring-security.xml but, since you didn't post your web.xml, I can only assume you don't have the corresponding filter entry in your web.xml with DelegatingFilterProxy as a filter class. You can define the filter in the web.xml like this:
<filter>
<filter-name>filterChainProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>filterChainProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Note that the filter-name references a bean from your spring context with the name filterChainProxy.
From the DelegatingFilterProxy javadoc:
Proxy for a standard Servlet 2.3 Filter, delegating to a
Spring-managed bean that implements the Filter interface. Supports a
"targetBeanName" filter init-param in web.xml, specifying the name of
the target bean in the Spring application context.
web.xml will usually contain a DelegatingFilterProxy definition, with
the specified filter-name corresponding to a bean name in Spring's
root application context. All calls to the filter proxy will then be
delegated to that bean in the Spring context, which is required to
implement the standard Servlet 2.3 Filter interface.
I hope this helps.
I wonder if the issue is related to your empty GrantedAuthority List in the login method.
In my implementation LocalAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider and in the GrantedAuthority list I add user role that comes from my domain.
final List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
for(com.tony.trip.domain.Role role:user.getRoles()){
auths.add(new SimpleGrantedAuthority(role.getRolename()));
}
Hope this hepls

MULE ESB - Error HTTPS, received EOFException: error

I have MULE ESB deployed in JBoss server 7.0.1 configured with HTTPS connector:
<https:inbound-endpoint address="https://${ws.host}:8443/services" path="services" exchange- pattern="request-response" connector-ref="httpConnector" responseTimeout="${ws.timeout}">
<cxf:jaxws-service serviceClass="..." >
</cxf:jaxws-service>
<transformer ref="..." />
</https:inbound-endpoint>
<https:connector name="httpConnector">
<https:tls-key-store path="/tmp/keystore.jks" keyPassword="pass" storePassword="passs"/>
<!--https:tls-server path="/tmp/trustStore.jks" storePassword="pass"/-->
</https:connector>
The client Side is using gSoap Version 1.3.
When calling web service, received error, these are logs of JBoss server:
20:11:39,498 INFO [stdout] (httpConnector.receiver.01) Allow unsafe renegotiation: true
20:11:39,499 INFO [stdout] (httpConnector.receiver.01) Allow legacy hello messages: true
20:11:39,499 INFO [stdout] (httpConnector.receiver.01) Is initial handshake: true
20:11:39,499 INFO [stdout] (httpConnector.receiver.01) Is secure renegotiation: false
20:11:39,509 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, received EOFException: error
20:11:39,509 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, handling exception: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
20:11:39,510 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, SEND TLSv1 ALERT: fatal, description = handshake_failure
20:11:39,510 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, WRITE: TLSv1 Alert, length = 2
20:11:39,510 INFO [stdout] (httpConnector.receiver.02) [Raw write]: length = 7
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) 0000: 15 03 01 00 02 02 28 ......(
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called closeSocket()
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called close()
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called closeInternal(true)
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called close()
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called closeInternal(true)
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called close()
20:11:39,511 INFO [stdout] (httpConnector.receiver.02) httpConnector.receiver.02, called closeInternal(true)
20:11:39,516 ERROR [org.mule.exception.DefaultSystemExceptionStrategy] (httpConnector.receiver.02) Caught exception in Exception Strategy: Remote host closed connection during handshake: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:882) [:1.6]
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188) [:1.6]
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:818) [:1.6]
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75) [:1.6]
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:50) [:1.6]
at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) [commons-httpclient-3.1-osgi.jar:]
at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) [commons-httpclient-3.1-osgi.jar:]
at org.mule.transport.http.HttpServerConnection.readLine(HttpServerConnection.java:219) [mule-transport-http-3.2.1.jar:]
at org.mule.transport.http.HttpServerConnection.readRequest(HttpServerConnection.java:185) [mule-transport-http-3.2.1.jar:]
at org.mule.transport.http.HttpMessageReceiver$HttpWorker.run(HttpMessageReceiver.java:155) [mule-transport-http-3.2.1.jar:]
at org.mule.work.WorkerContext.run(WorkerContext.java:310) [mule-core-3.2.1.jar:]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) [:1.6.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) [:1.6.0_45]
at java.lang.Thread.run(Thread.java:662) [:1.6.0_45]
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:462) [:1.6]
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:863) [:1.6]
... 13 more
Is there a compatibility problem between gSoap 1.3 and JBoss?
Thanks in advance.
Make sure the client side has access to the same certificate.
EDIT: Remove path="services" from the http:inbound-endpoint as it's useless since you provide a full address attribute.

Spring JMS Listener Container stop only half of listeners

I have weired problem with a JMS Listener container. In case I disable the listener container, half of messages are delivered and processed by listener. Here is my Spring configuration:
<bean id="ConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="JmsXA" />
</bean>
<bean id="testQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="queue/test" />
</bean>
<bean id="listener" class="eu.cuptech.jms.listener.ExampleListener" />
<bean id="listenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="ConnectionFactory" />
<property name="destination" ref="testQueue" />
<property name="messageListener" ref="listener" />
<property name="concurrency" value="1" />
</bean>
ExampleListener is here:
package eu.cuptech.jms.listener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class ExampleListener implements MessageListener {
public void onMessage(Message message) {
try {
String msg = ((TextMessage) message).getText();
System.out.println("MESSAGE TEXT: " + msg);
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}
Client is Spring MVC Controller with following methods:
send10Messages method (common JMS client):
#Resource(name="ConnectionFactory")
private ConnectionFactory connectionFactory;
#Resource(name="testQueue")
private Queue testQueue;
#RequestMapping(value="send10", method = RequestMethod.GET)
public String send10Messages(ModelMap model, HttpSession session) throws Exception {
sendTextMessages(10, "Test message: ");
return "redirect:/info";
}
private void sendTextMessages(int count, final String prefix) throws Exception {
Connection connection = null;
Session session = null;
MessageProducer messageProducer = null;
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = session.createProducer(testQueue);
connection.start();
TextMessage message = session.createTextMessage();
int i = 0;
while (i < count) {
message.setText(prefix + ++i);
messageProducer.send(message);
Thread.sleep(250);
System.out.println("Message " + prefix + i + " sent.");
}
} finally {
try {
if (messageProducer != null)
messageProducer.close();
if (connection != null)
connection.close();
if (session != null)
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
disableListener method:
#Resource(name="listenerContainer")
private DefaultMessageListenerContainer listenerContainer;
#RequestMapping(value="disableListener", method = RequestMethod.GET)
public String disableListener(ModelMap model, HttpSession session) {
listenerContainer.stop(new Runnable() {
public void run() {
System.out.println("JMS Listener stopped.");
}
});
return "redirect:/info";
}
enableListener method
#Resource(name="listenerContainer")
private DefaultMessageListenerContainer listenerContainer;
#RequestMapping(value="enableListener", method = RequestMethod.GET)
public String enableListener(ModelMap model, HttpSession session) {
listenerContainer.start();
return "redirect:/info";
}
When I start server and send messages I got this log (It is OK):
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 1
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 1 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 2
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 2 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 3
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 3 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 4
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 4 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 5
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 5 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 6
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 6 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 7
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 7 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 8
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 8 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 9
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 9 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 10
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 10 sent.
When I disable the listener container and send messages again I got this:
INFO [stdout] (listenerContainer-1) JMS Listener stopped.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 1
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 1 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 2 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 3
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 3 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 4 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 5
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 5 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 6 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 7
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 7 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 8 sent.
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 9
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 9 sent.
INFO [stdout] (http-localhost/127.0.0.1:8080-1) Message Test message: 10 sent.
When I enable the listener container again I got this:
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 2
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 4
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 6
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 8
INFO [stdout] (listenerContainer-1) MESSAGE TEXT: Test message: 10
The problem is that every odd message is processed by listener even if listener is disabled. I expact that all messages will be delivered and processed by listener when I enable the listener container and no message will be processed when I disable it.
I'm using Spring 3.2.4.RELEASE (I was trying 3.2.3.RELEASE too), HornetQ 2.3.0.Final as remote JMS Server and JBoss 7.3.1.Final as App server.
My guess is that you are loading the container into both the web context (DispatcherServlet's context) and the root context (ContextLoaderListener's context). Which means you have 2 containers and you are only stopping the one in the servlet context.
Turn on DEBUG logging for org.springframework and examine the bean initialization logs.
It probably should be just in the root context.

Using Spring Expression Language in Camel Marshal and Unmarshal Tags

I've tried searching for this information but haven't been able to find it. I am relatively new to Camel (and Java) so forgive me if I have overlooked something simple. Please keep in mind this is just sample code so it may be a bit brittle.
The real issue can be found in the Java output (all the way at the bottom) at the following line:
org.quartz.JobExecutionException: java.lang.ClassNotFoundException: #{${header.ProtobufType}} [See nested exception: java.lang.ClassNotFoundException: #{${header.ProtobufType}}]
I want to (at runtime) decide what instanceClass to use when marshaling or unmarshaling a message. I think using Spring Expression Language is the way to go but haven't been able to figure out the proper Google queries for what I am looking for. My Spring application context looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="toBean" class="To.ToBean" />
<bean id="fromBean" class="From.FromBean" />
<bean id="addTypeProcessor" class="Processor.AddTypeProcessor" />
<camel:errorHandler id="camelErrorHandler" type="NoErrorHandler" />
<camelContext id="camelContext" errorHandlerRef="camelErrorHandler" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="quartz://myTimer?trigger.repeatCount=-1&trigger.repeatInterval=5000" />
<to uri="bean:fromBean" />
<process ref="addTypeProcessor" />
<marshal>
<protobuf instanceClass="#{${header.ProtobufType}}" />
</marshal>
<unmarshal>
<protobuf instanceClass="#{${header.ProtobufType}}" />
</unmarshal>
<to uri="bean:toBean" />
<process ref="addTypeProcessor" />
</route>
</camelContext>
</beans>
My AddTypeProcessor looks like this:
package Processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
public class AddTypeProcessor implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
String headerName = "ProtobufType";
String headerValue = (String) exchange.getIn().getHeader(headerName);
System.out.println(headerName + " was " + headerValue);
exchange.getIn().setHeader(headerName, exchange.getIn().getBody().getClass().getCanonicalName());
headerValue = (String) exchange.getIn().getHeader(headerName);
System.out.println(headerName + " is " + headerValue);
}
}
My output is the following:
0 [main] INFO org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#63c5ab93: startup date [Fri Jun 28 16:33:17 EDT 2013]; root of context hierarchy
46 [main] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
1081 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#7cb01f72: defining beans [toBean,fromBean,addTypeProcessor,camelErrorHandler,template,consumerTemplate,camelContext:beanPostProcessor,camelContext]; root of factory hierarchy
1285 [main] INFO org.apache.camel.spring.SpringCamelContext - Apache Camel 2.10.1 (CamelContext: camelContext) is starting
1356 [main] INFO org.apache.camel.management.ManagementStrategyFactory - JMX enabled.
1521 [main] INFO org.apache.camel.impl.converter.DefaultTypeConverter - Loaded 175 type converters
1633 [main] INFO org.quartz.simpl.SimpleThreadPool - Job execution threads will use class loader of thread: main
1645 [main] INFO org.quartz.core.SchedulerSignalerImpl - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
1645 [main] INFO org.quartz.core.QuartzScheduler - Quartz Scheduler v.1.8.5 created.
1646 [main] INFO org.quartz.simpl.RAMJobStore - RAMJobStore initialized.
1647 [main] INFO org.quartz.core.QuartzScheduler - Scheduler meta-data: Quartz Scheduler (v1.8.5) 'DefaultQuartzScheduler-camelContext' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
1647 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler 'DefaultQuartzScheduler-camelContext' initialized from an externally provided properties instance.
1647 [main] INFO org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 1.8.5
1812 [main] INFO org.apache.camel.spring.SpringCamelContext - Route: route1 started and consuming from: Endpoint[quartz://myTimer?trigger.repeatCount=-1&trigger.repeatInterval=5000]
1812 [main] INFO org.apache.camel.management.DefaultManagementLifecycleStrategy - StatisticsLevel at All so enabling load performance statistics
1817 [main] INFO org.apache.camel.component.quartz.QuartzComponent - Starting Quartz scheduler: DefaultQuartzScheduler-camelContext
1817 [main] INFO org.quartz.core.QuartzScheduler - Scheduler DefaultQuartzScheduler-camelContext_$_NON_CLUSTERED started.
1819 [main] INFO org.apache.camel.spring.SpringCamelContext - Total 1 routes, of which 1 is started.
1822 [main] INFO org.apache.camel.spring.SpringCamelContext - Apache Camel 2.10.1 (CamelContext: camelContext) started in 0.535 seconds
ProtobufType was null
ProtobufType is WireFormatProtos.WireFormat.A
1848 [DefaultQuartzScheduler-camelContext_Worker-1] WARN org.apache.camel.util.ObjectHelper - Cannot find class: $header.ProtobufType
1849 [DefaultQuartzScheduler-camelContext_Worker-1] ERROR org.apache.camel.component.quartz.QuartzEndpoint - Error processing exchange. Exchange[Message: ]. Caused by: [org.quartz.JobExecutionException - java.lang.ClassNotFoundException: #{${header.ProtobufType}}]
1850 [DefaultQuartzScheduler-camelContext_Worker-1] INFO org.quartz.core.JobRunShell - Job DEFAULT.quartz-endpoint1 threw a JobExecutionException:
org.quartz.JobExecutionException: java.lang.ClassNotFoundException: #{${header.ProtobufType}} [See nested exception: java.lang.ClassNotFoundException: #{${header.ProtobufType}}]
at org.apache.camel.component.quartz.QuartzEndpoint.onJobExecute(QuartzEndpoint.java:117)
at org.apache.camel.component.quartz.CamelJob.execute(CamelJob.java:54)
at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: java.lang.ClassNotFoundException: #{${header.ProtobufType}}
at org.apache.camel.impl.DefaultClassResolver.resolveMandatoryClass(DefaultClassResolver.java:52)
at org.apache.camel.dataformat.protobuf.ProtobufDataFormat.loadDefaultInstance(ProtobufDataFormat.java:79)
at org.apache.camel.dataformat.protobuf.ProtobufDataFormat.getInstance(ProtobufDataFormat.java:67)
at org.apache.camel.dataformat.protobuf.ProtobufDataFormat.unmarshal(ProtobufDataFormat.java:109)
at org.apache.camel.processor.UnmarshalProcessor.process(UnmarshalProcessor.java:57)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:91)
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:45)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.interceptor.DefaultChannel.process(DefaultChannel.java:303)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:117)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:45)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.processor.UnitOfWorkProcessor.processAsync(UnitOfWorkProcessor.java:150)
at org.apache.camel.processor.UnitOfWorkProcessor.process(UnitOfWorkProcessor.java:117)
at org.apache.camel.processor.RouteInflightRepositoryProcessor.processNext(RouteInflightRepositoryProcessor.java:48)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)
at org.apache.camel.processor.loadbalancer.QueueLoadBalancer.process(QueueLoadBalancer.java:44)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:99)
at org.apache.camel.processor.loadbalancer.QueueLoadBalancer.process(QueueLoadBalancer.java:71)
at org.apache.camel.component.quartz.QuartzEndpoint.onJobExecute(QuartzEndpoint.java:113)
... 3 more
This is not possible.
Instead you can use a processor / bean, and then create the marshaller and unmarshaller in the java code, and invoke the marshal/unmarshal method. As this is java code, you can then have the dynamic behavior of defining the instance class from a camel message header.

Resources