lundi 20 avril 2015

Spring batch - JSR 352 retry fails when skip exception in thrown in writer

I am trying to investigate what happens when an exception is throw in the writer. As per theory I was expecting a roll-back to occur and then retry the chunk setting commit size as 1. but this is not happening and i am receiving the following error.

I am using Spring Batch -JSR 352 job design. In the writer I have 3 JDBC calls. If i throw an skippable exception after 2 JDBC calls have been successfully executed , then I could find the Spring batch is not able to rollback the transaction for the chunk and retry the chunk by placing the commit size as one. I am receiving the following execption after which the entire chunk is getting skipped and we are having an chunk commit. As a result the data already written to 2 JDBC tables are getting persisted missing the 3rd table data. 20 Apr 2015 18:38:28,811 ERROR [gov.state.nextgen.in.batch.sdx.chunk.writer.SdxRcvDlyWriter.writeItems(SdxRcvDlyWriter.java:74)] - Error while writing sdxRcvRecord :Exception occured during processing at gov.state.nextgen.in.batch.sdx.bo.impl.SdxRcvDlyBoImpl.write(SdxRcvDlyBoImpl.java:125) at gov.state.nextgen.in.batch.sdx.chunk.writer.SdxRcvDlyWriter.writeItems(SdxRcvDlyWriter.java:65) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55) at java.lang.reflect.Method.invoke(Method.java:619) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133) at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy18.writeItems(Unknown Source) at org.springframework.batch.jsr.item.ItemWriterAdapter.write(ItemWriterAdapter.java:55) at org.springframework.batch.core.jsr.step.item.JsrChunkProcessor.doPersist(JsrChunkProcessor.java:243) at org.springframework.batch.core.jsr.step.item.JsrFaultTolerantChunkProcessor$5.doWithRetry(JsrFaultTolerantChunkProcessor.java:298) at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:263) at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:168) at org.springframework.batch.core.step.item.BatchRetryTemplate.execute(BatchRetryTemplate.java:222) at org.springframework.batch.core.jsr.step.item.JsrFaultTolerantChunkProcessor.persist(JsrFaultTolerantChunkProcessor.java:348) at org.springframework.batch.core.jsr.step.item.JsrChunkProcessor.process(JsrChunkProcessor.java:114) at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75) at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77) at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368) at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:198) at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) at org.springframework.batch.core.jsr.job.flow.support.state.JsrStepState.handle(JsrStepState.java:53) at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:165) at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) at org.springframework.batch.core.jsr.job.flow.JsrFlowJob.doExecute(JsrFlowJob.java:82) at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:304) at org.springframework.batch.core.jsr.launch.JsrJobOperator$2.run(JsrJobOperator.java:675) at java.lang.Thread.run(Thread.java:795) 20 Apr 2015 18:38:50,157 DEBUG [org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:293)] - Checking for rethrow: count=1 20 Apr 2015 18:38:52,584 DEBUG [org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:313)] - Retry failed last attempt: count=1 20 Apr 2015 18:38:53,403 DEBUG [org.springframework.batch.core.jsr.step.item.JsrFaultTolerantChunkProcessor$6.recover(JsrFaultTolerantChunkProcessor.java:333)] - Skipping after failed write org.springframework.batch.core.step.item.ForceRollbackForWriteSkipException: Force rollback on skippable exception so that skipped item can be located. at org.springframework.batch.core.jsr.step.item.JsrFaultTolerantChunkProcessor$5.doWithRetry(JsrFaultTolerantChunkProcessor.java:317) at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:263) at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:168) at org.springframework.batch.core.step.item.BatchRetryTemplate.execute(BatchRetryTemplate.java:222) at org.springframework.batch.core.jsr.step.item.JsrFaultTolerantChunkProcessor.persist(JsrFaultTolerantChunkProcessor.java:348) at org.springframework.batch.core.jsr.step.item.JsrChunkProcessor.process(JsrChunkProcessor.java:114) at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75) at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77) at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368) at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:198) at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64) at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:67) at org.springframework.batch.core.jsr.job.flow.support.state.JsrStepState.handle(JsrStepState.java:53) at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:165) at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:144) at org.springframework.batch.core.jsr.job.flow.JsrFlowJob.doExecute(JsrFlowJob.java:82) at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:304) at org.springframework.batch.core.jsr.launch.JsrJobOperator$2.run(JsrJobOperator.java:675) at java.lang.Thread.run(Thread.java:795) Caused by: gov.state.nextgen.framework.batch.exception.NGBatchSkipRecordException: gov.state.nextgen.in.batch.exception.INBatchException: Exception occured during processing at gov.state.nextgen.in.batch.sdx.chunk.writer.SdxRcvDlyWriter.writeItems(SdxRcvDlyWriter.java:76) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:94) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55) at java.lang.reflect.Method.invoke(Method.java:619) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133) at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy18.writeItems(Unknown Source) at org.springframework.batch.jsr.item.ItemWriterAdapter.write(ItemWriterAdapter.java:55) at org.springframework.batch.core.jsr.step.item.JsrChunkProcessor.doPersist(JsrChunkProcessor.java:243) at org.springframework.batch.core.jsr.step.item.JsrFaultTolerantChunkProcessor$5.doWithRetry(JsrFaultTolerantChunkProcessor.java:298) ... 26 more Caused by: gov.state.nextgen.in.batch.exception.INBatchException: Exception occured during processing at gov.state.nextgen.in.batch.sdx.bo.impl.SdxRcvDlyBoImpl.write(SdxRcvDlyBoImpl.java:125) at gov.state.nextgen.in.batch.sdx.chunk.writer.SdxRcvDlyWriter.writeItems(SdxRcvDlyWriter.java:65) ... 41 more20 Apr 2015 18:39:14,808 DEBUG [org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:88)] - Inputs not busy, ended: false 20 Apr 2015 18:39:17,985 DEBUG [org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:437)] - Applying contribution: [StepContribution: read=2, written=0, filtered=0, readSkips=0, writeSkips=1, processSkips=0, exitStatus=EXECUTING] 20 Apr 2015 18:39:18,984 INFO [gov.state.nextgen.in.batch.sdx.chunk.writer.SdxRcvDlyWriter.checkpointInfo(SdxRcvDlyWriter.java:87)] - ParisRcvFedWriter - checkpointInfo(): step name: process, step execution id: 14939 20 Apr 2015 18:39:19,314 TRACE [org.springframework.transaction.support.TransactionSynchronizationManager.getResource(TransactionSynchronizationManager.java:140)] - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@5c4a884f] for key [org.apache.commons.dbcp.BasicDataSource@d9bdc230] bound to thread [SimpleAsyncTaskExecutor-1] 20 Apr 2015 18:39:19,314 DEBUG [org.springframework.transaction.support.AbstractPlatformTransactionManager.handleExistingTransaction(AbstractPlatformTransactionManager.java:472)] - Participating in existing transaction 20 Apr 2015 18:39:19,314 TRACE [org.springframework.transaction.interceptor.TransactionAspectSupport.prepareTransactionInfo(TransactionAspectSupport.java:447)] - Getting transaction for [org.springframework.batch.core.repository.support.SimpleJobRepository.updateExecutionContext] 20 Apr 2015 18:39:19,315 DEBUG [org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:908)] - Executing prepared SQL update 20 Apr 2015 18:39:19,315 DEBUG [org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:627)] - Executing prepared SQL statement [UPDATE BATCH_STEP_EXECUTION_CONTEXT SET SHORT_CONTEXT = ?, SERIALIZED_CONTEXT = ? WHERE STEP_EXECUTION_ID = ?] I am attaching my configuration files for reference. By debugging I could find my insert statements are getting executed under transaction managed by spring and I am sure there is no issue with the transaction manager configuration

Quartz + Spring double execution

I have Quartz 2.2.1 and Spring 3.2.8 app. My problem is that during startup Quartz creates two jobs with the following one 2 seconds later. My job must be executed every 10 seconds, yet it executes twice:

Info:   INFO: Starting TASK on Mon Apr 20 16:22:21 CEST 2015
Info:   INFO: Starting TASK on Mon Apr 20 16:22:23 CEST 2015
Info:   INFO: Starting TASK on Mon Apr 20 16:22:31 CEST 2015
Info:   INFO: Starting TASK on Mon Apr 20 16:22:33 CEST 2015
Info:   INFO: Starting TASK on Mon Apr 20 16:22:41 CEST 2015
Info:   INFO: Starting TASK on Mon Apr 20 16:22:43 CEST 2015

I tried to follow the suggestions on Quartz + Spring double execution on startup. The provided answers (removal of tag containing "ContextLoaderListener" within web.xml) didn't help as I had an error that the WebContext was missing. Thanks for your help.

Here is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://ift.tt/nSRXKP"
         xmlns:xsi="http://ift.tt/ra1lAU"
         xsi:schemaLocation="http://ift.tt/nSRXKP 
 http://ift.tt/LU8AHS">
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <jsp-config>
        <jsp-property-group>
            <description>header and footer settings</description>
            <url-pattern>/WEB-INF/*</url-pattern>
            <include-prelude>/WEB-INF/header.jspf</include-prelude>
        </jsp-property-group>
    </jsp-config>

    <!-- Spring Security -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>utils.SessionCounterListener</listener-class>
    </listener>

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

    <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>
</web-app>

My spring-servlet.xml look like this:

<?xml version="1.0" encoding="windows-1252"?> <beans xmlns="http://ift.tt/GArMu6"
       xmlns:xsi="http://ift.tt/ra1lAU"
       xmlns:p="http://ift.tt/1jdM0fE"
       xmlns:context="http://ift.tt/GArMu7"
       xmlns:mvc="http://ift.tt/1bHqwjR"
       xmlns:aop="http://ift.tt/OpNdV1"
       xmlns:tx="http://ift.tt/OGfeU2"
       xsi:schemaLocation="
       http://ift.tt/GArMu6
       http://ift.tt/QEDs1e
       http://ift.tt/GArMu7
       http://ift.tt/QEDs1k
       http://ift.tt/1bHqwjR
       http://ift.tt/1bVJL9q
       http://ift.tt/OpNdV1
       http://ift.tt/QEDs1g
       http://ift.tt/OGfeU2
       http://ift.tt/1cQrvTl">

    <!-- Use @Component annotations for bean definitions -->

    <context:component-scan base-package="cinema"/>

    <!-- Use @Controller annotations for MVC controller definitions -->

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />


    <bean id="exampleBusinessObject" class="cinema.controller.ServerMonitorController"/>


    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="exampleBusinessObject"/>
        <property name="targetMethod" value="sendIt"/>
        <property name="concurrent" value="false"/>
    </bean>

    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail"/>
        <!-- czas do odczekania 
        <property name="startDelay" value="10000"/>-->
        <!-- czas pomiedzy odpaleniami (50 sek = 50000) -->
        <property name="repeatInterval" value="10000"/>
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger"/>
            </list>
        </property>
    </bean>


    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
        </property>
    </bean>


    <tx:jta-transaction-manager />

    <!-- Use @Transaction annotations for managing transactions -->
    <tx:annotation-driven />

    <!-- View resolver -->
    <bean class=
     "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
    </bean>

    <import resource="/spring-security.xml" /> </beans>

ServerMonitorController.java :

@Controller
public class ServerMonitorController {

    public static void sendIt() throws FileNotFoundException, IOException {

        System.out.println("INFO: Starting TASK on "+ new Date());

    }
}

Thymeleaf template parsing error

I get parsing error when I try to load localhost:8080/. I can't find any errors in my template, so why have I this mistake? Error:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Mon Apr 20 16:59:56 EEST 2015 There was an unexpected error (type=Internal Server Error, status=500). Exception parsing document: template="index", line 26 - column 3

<tr th:each="customer : ${customers}">
    <td th:text="${customer.identity}">001</td>
    <td th:text="${customer.name}">Name</td>
    <td th:text="${customer.address}">Address</td>
    <td th:text="${customer.age}">Age</td>
</tr>

public String mainPage(Model model){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    PersonJDBCTemplate personJDBCTemplate = (PersonJDBCTemplate) context.getBean("personJDBCTemplate");
    List<Person> persons = personJDBCTemplate.getAllPersons();
    model.addAttribute("customers", persons);
    return "index";
}

Spring upgrade Exception

I have upgrade Spring3.1 to Spring 4.1 encounter a ehcache problem. Below is spring ehcache config:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
    xmlns:xsi="http://ift.tt/ra1lAU" 
    xmlns:cache="http://ift.tt/LO4PtR"
    xmlns:ehcache="http://ift.tt/1nlfGcD"
    xmlns:p="http://ift.tt/1jdM0fE"
    xsi:schemaLocation="http://ift.tt/GArMu6 
        http://ift.tt/1CZCNBy
        http://ift.tt/1nlfGcD     
        http://ift.tt/1nlfGt5">  

    <ehcache:annotation-driven cache-manager="cacheManager" />

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="cacheManagerFactory"/>

    <!-- EhCache library setup -->
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:conf/ehcache.xml"  p:shared="true" />

</beans>

Exception:


Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in file [D:\Workspace\tplh\clinic\mis\src\main\webapp\WEB-INF\classes\spring\base-orm.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.config.internalEhCacheCachingAdvisor': Cannot resolve reference to bean 'com.googlecode.ehcache.annotations.impl.CacheStaticMethodMatcherPointcut#0' while setting bean property 'pointcut'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheStaticMethodMatcherPointcut#0': Cannot resolve reference to bean 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0' while setting bean property 'cacheAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.cache.ehcache.EhCacheCacheManager' to required type 'net.sf.ehcache.CacheManager' for property 'cacheManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.cache.ehcache.EhCacheCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:472)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:736)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:663)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1642)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.config.internalEhCacheCachingAdvisor': Cannot resolve reference to bean 'com.googlecode.ehcache.annotations.impl.CacheStaticMethodMatcherPointcut#0' while setting bean property 'pointcut'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheStaticMethodMatcherPointcut#0': Cannot resolve reference to bean 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0' while setting bean property 'cacheAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.cache.ehcache.EhCacheCacheManager' to required type 'net.sf.ehcache.CacheManager' for property 'cacheManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.cache.ehcache.EhCacheCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101)
    at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:243)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:984)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:955)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:466)
    ... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheStaticMethodMatcherPointcut#0': Cannot resolve reference to bean 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0' while setting bean property 'cacheAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.cache.ehcache.EhCacheCacheManager' to required type 'net.sf.ehcache.CacheManager' for property 'cacheManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.cache.ehcache.EhCacheCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    ... 39 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl#0': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.cache.ehcache.EhCacheCacheManager' to required type 'net.sf.ehcache.CacheManager' for property 'cacheManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.cache.ehcache.EhCacheCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    ... 49 more
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.springframework.cache.ehcache.EhCacheCacheManager' to required type 'net.sf.ehcache.CacheManager' for property 'cacheManager'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.cache.ehcache.EhCacheCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:476)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1523)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1482)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    ... 55 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.springframework.cache.ehcache.EhCacheCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287)
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:461)
    ... 61 more

Q: I have couple of questions about what is preffered, using Java in server-side or Python? [on hold]

I am currently considering going deep with Java an its technologies in server-side web development (Learning about Spring, Servlets, Apache/Tomcat and the like) or with Python/Django. Regardless, I think I will use them both in the server-side, but I am considering what is gonna be the main language in the back-end (the one that I will have to learn all the technologies regard to web development), and the side one.

I have a question regard that:

What language is preferred in server-side as the primary language (Taking into account rapid development, security, fast, scalable).

Thanks ahead you guys!

Audit tables not created

I am trying to use hibernate envers to audit particular tables. Here is the version I use:

<dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
<dependency>  <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>4.0.1.Final</version>
</dependency>

As far as I understand the only thing I have to do is to add @Audited annotation on my entity class.

@Entity
@Audited
@Table(name = "terminal")
public class Terminal {

@Id
    @Column(name = "terminal_id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id")
    @SequenceGenerator(name = "user_id", sequenceName = "user_id")
    private Long terminalId;
    ...
}

Here is my hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://ift.tt/UNuKEc" >
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.showSql">true</property>
        <property name="hbm2ddl.auto">auto</property>
        <mapping class="com.terminal.domain.Terminal"/>
        ...
    </session-factory>

</hibernate-configuration>

However, terminal_aud table has not been created after my application start.

What do I wrong?

P.S.

Looks similar to this question:

http://ift.tt/1J2u6Lq

Spring mapping using hibernate

I am joining two table using one to many relationship

my first table is role and second is roleCompany. where role_id is reference key in roleCompany table.

But when I am writting query to get all companies for specific id it showing me following error

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/myproject] threw exception [Request processing failed; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.test.myproject.domain.entity.RoleEntity.id] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Long field com.test.myproject.domain.entity.RoleEntity.id to java.lang.Long
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)

My RoleEntity Class is :

@Entity
@Table(name = "roles")
public class RoleEntity {

    @Id
    @Getter
    @Setter
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @Getter
    @Setter
    @Column(name = "role", nullable = false)
    private String role;

    @Getter
    @Setter
    @OneToMany(mappedBy = "roles")
    List<RoleCompanyEntity> companyentities;    
}

and my RoleCompanyEntity is

@NamedQueries({
    @NamedQuery(name = RoleCompanyEntity.FIND_ROLE_COMPANY_BY_ROLE_ID, query = "select r.companyId, r.companyName from RoleCompanyEntity r where r.roles  =:roleId")
})


@Entity
@Table(name = "role_company")
public class RoleCompanyEntity {

    public static final String FIND_ROLE_COMPANY_BY_ROLE_ID = "findRoleCompanyByRoleId";

    @Id
    @Getter
    @Setter
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "company_id", unique = true, nullable = false)
    private Long companyId;

    @Getter
    @Setter
    @Column(name = "company_name", unique = true, nullable = false)
    private String companyName;


    @Getter
    @Setter
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="role_id", nullable=false)
    private RoleEntity roles;

}

JsonMappingException when using a Set instead of a List

I have a spring boot project with some entities, in specific, I have a Student Class with a DesiredCourses list which should be a Set<>.

When I use:

@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public List<StudentDesiredCourseEntity> getStudentDesiredCourses() {
    return studentDesiredCourses;
}

public void setStudentDesiredCourses(List<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}

Everything works fine but when I use

@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public Set<StudentDesiredCourseEntity> getStudentDesiredCourses() {
    return studentDesiredCourses;
}

public void setStudentDesiredCourses(Set<StudentDesiredCourseEntity> studentDesiredCourses) {
    this.studentDesiredCourses = studentDesiredCourses;
}

I get

org.springframework.http.converter.HttpMessageNotReadableException",
"message":"Could not read JSON: (was java.lang.NullPointerException) (through reference chain: edu.cs6310.project4.entities.StudentEntity[\"studentDesiredCourses\"]->java.util.HashSet[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: edu.cs6310.project4.entities.StudentEntity[\"studentDesiredCourses\"]->java.util.HashSet[0])

Is there something I am missing or something extra that needs to be done?

As requested, the equals and hashcode

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof StudentDesiredCourseEntity)) return false;

    StudentDesiredCourseEntity that = (StudentDesiredCourseEntity) o;

    if (!course.equals(that.course)) return false;
    if (!priority.equals(that.priority)) return false;
    if (!student.equals(that.student)) return false;

    return true;
}

@Override
public int hashCode() {
    int result = priority.hashCode();
    result = 31 * result + course.hashCode();
    result = 31 * result + student.hashCode();
    return result;
}

Correct way to implement User Management in Spring Boot + Spring Security OAuth2

I have a Spring Boot OAuth2 (with Google Sign in) Auth Server and a Spring Boot resource server. I have two databases one for Auth Server and one for resource server. I have used the standard Spring OAuth2 MySql schema for Auth Server in which I store basic user details like username, enabled / disabled and a set of Authorities. My resource server requires additional details like user language preference etc. hence I am forced to create another table for users in resource server where I store all the additional information about the user. Now I want to implement a User Management operations like CRUD of users. The problem is every time I create a user I need two put entries in two tables of different databases.

Is there any other way to accomplish this? I don't want to put whole of user management in Auth Server because I want to store some user information which is specific to one resource server.

Thanks

how to get sub directories in int-ftp:outbound-gateway with expression?

firstly thanks for attention i have spring integration project that listen ftp server to receive files in different directory and process it,ftp directory structure is:
ftp-root
-----------a\
-----------------in\
---------------------------a.txt
-----------------out\
------------b\
-----------------in\
---------------------------b.txt
-----------------out\

i used int-ftp:outbound-gateway adapter to run ls recursive command,how to write expression attr in int-ftp:outbound-gateway that get a.txt and b.txt in in directories, my adapter code is:

 <int-ftp:outbound-gateway id="gateway1"
                              session-factory="ftpClientFactory"
                              request-channel="inbound1"
                              reply-channel="outbound"
                              reply-timeout="777"
                              auto-create-local-directory="false"
                              auto-startup="true"
                              command="ls"
                              command-options="-1 -R"
                              expression="'*/in/'"
                              mput-regex=".*">

    </int-ftp:outbound-gateway>

but not correctly worked, how to write it?

What is the main method of a WAR file?

Recently, I've reapackaged my java spring application to become a WAR file for deployment in tomcat. After some testing I noticed, that public static void main(String[] args) is not executed. Some necessary initialization of my application is done in main. Is there something like a main method in a WAR file? What is the appropiate place in a WAR file to run some initialization?

sts validation on project builders have a high cpu

spring tool suite version 3.6.4 on my mac os. when I choose the validation on project builders ![enter image description here][1]

[1]: http://ift.tt/1G00WGm like this, the cpu is very high,when I I not choose the validation,the cpu is very lower,so I think this is maybe a problem ,I want to kown how to solve the problem,think you very much.

How to use a custom location for messages properties files in thymeleaf?

Im using thymeleaf and spring, my messages.properties files need to have the same name as the template in order for them to work. I have tried to create a custom path using webConfigurer.Java but it's not working.

WebConfigurer.java source:

/*
 * Copyright 2015 Information Retrieval programs (IRP).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://ift.tt/jtTJvY
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package en.irp.project.config;

import java.util.Locale;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Specify session factory, hibernate properties, data source, hibernate
 * transaction, view resolver.
 *
 * The ComponentScan({ "com.app.skeleton.*" }) annotation means exactly the same
 * as xml -> context:component-scan base-package="com.*" in
 * dispatcher-servlet.xml
 *
 * @author Michael Beers <michael@michaelbeers.nl>
 * @todo Fix the languages resolver.
 */
@EnableWebMvc
@EnableTransactionManagement
@Configuration
@ComponentScan({"en.irp.project.*"})
@PropertySource("classpath:/application.properties")
@Import({SecurityConfigurer.class})
public class WebConfigurer extends WebMvcConfigurerAdapter {

    /**
     * Loads the environment to load properties.
     */
    @Autowired
    Environment env;

    /**
     * Generates the JDBC data source for the application.
     *
     * @return
     */
    @Bean(name = "dataSource")
    public BasicDataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();

        ds.setDriverClassName(env.getProperty("database.driver"));
        ds.setUrl(env.getProperty("database.url"));
        ds.setUsername(env.getProperty("database.user"));
        ds.setPassword(env.getProperty("database.password"));

        return ds;
    }

    /**
     * Generates the Hibernate session factory.
     *
     * @return
     */
    @Bean
    public SessionFactory sessionFactory() {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());

        builder.scanPackages("en.irp.project.model").addProperties(getHibernateProperties());
        //builder.scanPackages("com.app.skeleton.model").addProperties(getHibernateProperties());

        return builder.buildSessionFactory();
    }

    /**
     * Returns all the hibernate properties from the application.properties
     * file.
     *
     * @return
     */
    private Properties getHibernateProperties() {
        Properties prop = new Properties();

        prop.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
        prop.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
        prop.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        prop.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

        return prop;
    }

    /**
     * Generates the Hibernate transaction manager.
     *
     * @return
     */
    @Bean
    public HibernateTransactionManager txManager() {
        return new HibernateTransactionManager(sessionFactory());
    }

    /**
     * Generates the i18n language loader.
     *
     * @return
     */
    @Bean(name="messageSource")
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        resource.setBasename("WEB-INF/languages/messages");
        resource.setDefaultEncoding("UTF-8");
        return resource;
    }

    /**
     * Generates the i18n language changer parameter.
     *
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("language");
        return localeChangeInterceptor;
    }

    /**
     * Genereates the default i18n language.
     *
     * @return
     */
    @Bean(name = "localeResolver")
    public SessionLocaleResolver localeResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(new Locale("en"));
        return localeResolver;
    }

    /**
     * Generates the template resolver for thymeleaf.
     *
     * @return
     */
    @Bean
    public ServletContextTemplateResolver templateResolver() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode("HTML5");
        resolver.setCacheable(false);
        return resolver;

    }

    /**
     * Generates the template engine for thymeleaf.
     *
     * @return
     */
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        engine.addDialect(new SpringSecurityDialect());
        return engine;
    }

    /**
     * Generates the view resolver from Spring MVC with thymeleaf intergrated.
     *
     * @return
     */
    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setOrder(1);
        viewResolver.setViewNames(new String[]{"*"});
        viewResolver.setCache(false);
        return viewResolver;
    }

    /**
     * Add resources.
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("/WEB-INF/assets/");
    }

    /**
     * Add interceptors.
     * 
     * @param registry 
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

Can't store BLOB using Oracle + Spring + Liberty profile

I receive ClassNotFoundException : oracle.sql.BLOB exception storing blob in DB. Here is my conf:

<bean id="nativeJdbcExtractor"      class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" />
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
<property name="nativeJdbcExtractor" ref="nativeJdbcExtractor" /> 
</bean>

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="DataBase" /> 
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" /> 
</bean>

I changed it like this:

<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor"/>

and now I receive:

[ERROR ] Context initialization failed
Error creating bean with name 'clusterizer': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ru.sbrf.indexer.dao.ClusterizerDao ru.sbrf.indexer.ClusterizerProcessor.clusterizerDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clusterizerDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.support.lob.LobHandler ru.sbrf.indexer.dao.ClusterizerDao.lobHandler; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lobHandler' defined in ServletContext resource [/WEB-INF/spring/ds.xml]: Cannot resolve reference to bean 'nativeJdbcExtractor' while setting bean property 'nativeJdbcExtractor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nativeJdbcExtractor' defined in ServletContext resource [/WEB-INF/spring/ds.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Could not initialize WebSphereNativeJdbcExtractor because WebSphere API classes are not available: java.lang.ClassNotFoundException: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection
[ERROR ] SRVE0283E: При инициализации контекста возникла исключительная ситуация: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clusterizer': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ru.sbrf.indexer.dao.ClusterizerDao ru.sbrf.indexer.ClusterizerProcessor.clusterizerDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clusterizerDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.jdbc.support.lob.LobHandler ru.sbrf.indexer.dao.ClusterizerDao.lobHandler; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lobHandler' defined in ServletContext resource [/WEB-INF/spring/ds.xml]: Cannot resolve reference to bean 'nativeJdbcExtractor' while setting bean property 'nativeJdbcExtractor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nativeJdbcExtractor' defined in ServletContext resource [/WEB-INF/spring/ds.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Could not initialize WebSphereNativeJdbcExtractor because WebSphere API classes are not available: java.lang.ClassNotFoundException: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:2223)
at [internal classes]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor]: Constructor threw exception; nested exception is java.lang.IllegalStateException: Could not initialize WebSphereNativeJdbcExtractor because WebSphere API classes are not available: java.lang.ClassNotFoundException: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
... 51 more
Caused by: java.lang.IllegalStateException: Could not initialize WebSphereNativeJdbcExtractor because WebSphere API classes are not available: java.lang.   ClassNotFoundException: com.ibm.ws.rsadapter.jdbc.WSJdbcConnection
at org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor.<init>(WebSphereNativeJdbcExtractor.java:65)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 53 more

but I can't find this com.ibm.ws.rsadapter.jdbc.WSJdbcConnection in LP and I don't want copy all dependencies from WAS. How do I store data in Liberty profile?

Spring unwillingly changes values in my Bean

I named the subject as clear as I could but if it's not, here's the detail, should be long, but my problem, is really weird.

I hope my explanations won't get you confused. Thanks in advance for you help!

EDIT : as there aren't many answers/questions, perhaps my explanations are confusing/unpleasant to read. So, here's a resume : between two methods, I can observe a change in the value of a property of an object, getting the object in a wrong state. Details below :)

I have a Spring/JSF webapp which, among other things, manages a user database. When you load the management page, it displays the data in a p:dataTable (PrimeFaces).

The problem is : when I select a row in the dataTable, it calls the corresponding listener which sets a temporary object in my backingBean. By now, all the properties values correspond to the row selected.

But, when I call a method by clicking a button, and try to retrieve my object in the backing bean, it returns me the correct object (memory address is the same) with all the properties right, except one (see below).

Precisely, when i call my Listener (listenerselectadmin), the value superAdministrateur of the selection is True. Then, when I call the method Test(), the value of superAdministrateur is false, but all the other values aren't changed (see below).

I toggled a breakpoint in the setter of superAdministrateur and it's called several times, the first one with the right value (true), the next ones with the wrong one (false)...

There's no method created by me between these two, so I deduced that Spring modified the value, but why?

To prove it, I created another object : admintemp. In the listener I stock my selection in the object adminSelectionne in the backingBean. Naturally, Spring gives adminSelectionne the memory address of the selection, so it doesn't have to create a new object. Then, I set property by property the values of the selection in the new object adminTemp. When I do so, Spring allocates the same memory address to this object and I have the bug generated to both adminTemp and adminSelectionne.

However, if I set all properties of adminTemp with the values of the selection but one, when I try to retrieve the object in the method test, it has been destroyed (null)...

EDIT : the method getAdministrateurModel() retrieve the model of my MVC in the conversation. NOT part of the problem, I invastigated on the question by retrieving the model with other techniques. Plus, I retrieve my objects with the same memory adress, so the Model is the right one.

Here is my object class :

@Entity
public class Administrateur implements Serializable{

private static final long serialVersionUID = 1L;

//Attributs
private int idAdministrateur;
private String numeroCP;
private boolean superAdministrateur=true;
private String superAdministrateurAnalog;
private Gerant gerant;

//Getters / Setters
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
public int getIdAdministrateur() {
    return idAdministrateur;
}
public void setIdAdministrateur(int idAdministrateur) {
    this.idAdministrateur = idAdministrateur;
}

@Column(unique=true)
public String getNumeroCP() {
    return numeroCP;
}
public void setNumeroCP(String numeroCP) {
    this.numeroCP = numeroCP;
}

public boolean isSuperAdministrateur() {
    return superAdministrateur;
}
public void setSuperAdministrateur(boolean superAdministrateur) {
    this.superAdministrateur = superAdministrateur;
    if(superAdministrateur){
    this.superAdministrateurAnalog = "Oui";
    }else{
    this.superAdministrateurAnalog = "Non";
    }
}

@ManyToOne @JoinColumn(name="gerant_id")
public Gerant getGerant() {
    return gerant;
}
public void setGerant(Gerant gerant) {
    this.gerant = gerant;
}

public String getSuperAdministrateurAnalog() {
    return superAdministrateurAnalog;
}
public void setSuperAdministrateurAnalog(String superAdministrateurAnalog) {
    this.superAdministrateurAnalog = superAdministrateurAnalog;
}
//Constructors
public Administrateur(){

}

public Administrateur(int id, String numCP, boolean sa){
    this.idAdministrateur=id;
    this.numeroCP=numCP;
    this.superAdministrateur=sa;
}
}

Here is my Backing Bean (resumed to the code needed):

@Component
public class AdministrateurModel implements Serializable{

    /**
 * 
 */
private static final long serialVersionUID = 1L;

//Attributes

private Administrateur adminselectionne = new Administrateur();

private Administrateur admintemp = new Administrateur();

    //Getters / Setters


public Administrateur getAdminselectionne() {
    return adminselectionne;
}

public void setAdminselectionne(Administrateur adminselectionne) {
    this.adminselectionne = adminselectionne;
}

public Administrateur getAdmintemp() {
    return admintemp;
}

public void setAdmintemp(Administrateur admintemp) {
    this.admintemp = admintemp;
}
}

Here the method of Controller that are used for this problem:

@Controller("administrateurController")
@Scope("session")
public class AdministrateurController{

public void listenerselectadmin(SelectEvent selectEvent){
    AdministrateurModel model = getAdministrateurModel();
    Administrateur selection = (Administrateur) selectEvent.getObject();
    model.setAdminselectionne(selection);

    model.setAdmintemp(new Administrateur());
    model.getAdmintemp().setGerant(selection.getGerant());
    model.getAdmintemp().setNumeroCP("Test");
    model.getAdmintemp().setSuperAdministrateur(selection.isSuperAdministrateur());
    model.getAdmintemp().setSuperAdministrateurAnalog(selection.getSuperAdministrateurAnalog());


//flag in the model, which enable/disable buttons rendering on the JSF page
    model.setDisabledAdmin(false);
}

public void test(){
    AdministrateurModel model = getAdministrateurModel();
    System.out.println(model.getAdminselectionne());
    System.out.println(model.getAdminselectionne().getNumeroCP());
    System.out.println(model.getAdminselectionne().getSuperAdministrateurAnalog());
    System.out.println(model.getAdminselectionne().isSuperAdministrateur());

    System.out.println(model.getAdmintemp());
    System.out.println(model.getAdmintemp().getNumeroCP());
    System.out.println(model.getAdmintemp().getSuperAdministrateurAnalog());
    System.out.println(model.getAdmintemp().isSuperAdministrateur());
}

Spring rest internationalization

Is there a way to implement Spring internationalization into rest service if I want to setLocale on the parameter i parse from a specific user ticket?

Workflow looks like this: user clicks a link. Service gets user specific ticket and settings. Service parses ticket and gets locale this locale should be set accordingly and then service returns response in a specific language.

All I have found were samples simply transfering locale together with the request. Also I am not getting the point how Spring maps all these names. Do I have to give him the variables and then he maps those names with the language sources given?

Domain authentication with kerberos fails

My app is using grails, spring, kerberos.

applicationContext.xml

<beans 
    ...
    <sec:http entry-point-ref="spnegoEntryPoint">
        <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" />
        <sec:custom-filter ref="spnegoAuthenticationProcessingFilter"
            position="BASIC_AUTH_FILTER" />
    </sec:http>

    <bean id="spnegoEntryPoint"
        class="org.springframework.security.kerberos.web.authentication.SpnegoEntryPoint" />

    <bean id="spnegoAuthenticationProcessingFilter"
        class="org.springframework.security.kerberos.web.authentication.SpnegoAuthenticationProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <sec:authentication-manager alias="authenticationManager">
        <sec:authentication-provider ref="kerberosServiceAuthenticationProvider" />
    </sec:authentication-manager>

    <bean id="kerberosServiceAuthenticationProvider"
        class="org.springframework.security.kerberos.authentication.KerberosServiceAuthenticationProvider">
        <property name="ticketValidator">
            <bean class="org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator">
                <property name="servicePrincipal" value="HTTP/my.host.com@MY.DOMAIN.COM" />
                <property name="keyTabLocation" value="file:/u/tomcat/app/apache-tomcat-7.0.11/lib/http-web.keytab"/>
                <property name="debug" value="true" />
            </bean>
        </property>
        <property name="userDetailsService" ref="dummyUserDetailsService" />
    </bean>

    <bean class="org.springframework.security.kerberos.authentication.sun.GlobalSunJaasKerberosConfig">
        <property name="debug" value="true" />
        <property name="krbConfLocation" value="/etc/krb5.conf" />
    </bean>

    <bean id="dummyUserDetailsService"
        class="com.spring.security.kerberos.sample.user.DummyUserDetailsService" />
</beans>

When I deploy my app and enter my domain login/password in browser, I get the following request in Fiddler:

GET http://ift.tt/1Ix0PFh HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: ru-RU
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Host: my.host.com:8080
Cookie: JSESSIONID=EDE49792033A8FC877427704DBE26D85
Proxy-Connection: Keep-Alive
DNT: 1
Authorization: Negotiate YIIHDw...=

As I understand, Kerberos domain authentication was successful. But on a web page I see:

java.lang.NullPointerException
at org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator$KerberosValidateAction.run(SunJaasKerberosTicketValidator.java:162)
at org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator$KerberosValidateAction.run(SunJaasKerberosTicketValidator.java:151)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator.validateTicket(SunJaasKerberosTicketValidator.java:66)
at org.springframework.security.kerberos.authentication.KerberosServiceAuthenticationProvider.authenticate(KerberosServiceAuthenticationProvider.java:64)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
....

NPE appears in line

String user = context.getSrcName().toString();

because context.getSrcName() == null. What's wrong?

P.S.: One more moment: when I enter wrong password, it asks on me for it one more time.

how to handle exception this org.springframework.integration.MessageHandlingException: HTTP request execution failed for URI [{outBoundUrl}]

While using spring integration http outbound getting this exception

org.springframework.integration.MessageHandlingException: HTTP request execution failed for URI [{outBoundUrl}]

how to resolve this exception

Please give me any clue

Spring Executors - Executing method in thread with specific index

In my application I have a receiver which should processing messages with many threads. Sender module is putting messages on stack and receiver module is taking it from this stack. Everything works with two threads (one for sending, one for receiving). Now I want to receive messages with many threads.

Messages have some kind of group number. I need to process one group of messages in one thread (there will be more messages groups than threads). How can I handle with this?

I want to do something like this:

public class ReceiverExample {
    @Autowired
    Receiver receiver; 

    @Autowired 
    TaskExecutor executor;

    public void receive(){
        Msg msg = receiver.receive(); 
        int index = msg.getIndex();

        executor.execute(
                //put index ? ,
                msg
        );
    }
}

I'm using Spring Framework. I know I must use some kind of executor, but I can't find any good example showing my problem.

download a file using Angular JS and a Spring-based RESTful web service

I'm using Spring boot and Angular JS . I have a Spring REST Controller that I use to download a File. when I call it using http://localhost:8080/download it works and the file is downloaded. Now I have a button ,when I click on it , I the file will be downloaded . so I wrote a function in my angular js controller to get the url of my spring web service but when I tested it nothing happened . what should I do to fix this ? Is there a better way to download files using Spring and Angular ?

 /**
 * Size of a byte buffer to read/write file
 */
private static final int BUFFER_SIZE = 4096;
private String filePath = "C:\\Users\\marwa\\Desktop\\marwa\\gg.jpg";

/**
 * Method for handling file download request from client
 */
@RequestMapping (value="/download", method=RequestMethod.GET )
public void doDownload(HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    // get absolute path of the application
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    System.out.println("filepath = " + filePath);

    // construct the complete absolute path of the file

    File downloadFile = new File(filePath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = context.getMimeType(filePath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"",
            downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

}

my angular js function ( I added console.log("ok") to see if I get a result from the spring controller and it printed ok )

$scope.downloadFile = function () {                   
        $http({method: 'GET', url: '/download'}).
         success(function(result) {
                        console.log("ok");
          }).
     error(function(data, status, headers, config) {
            console.log("oops");
         });
 };

and my button

<button  class="btn btn-success" ng-click="downloadFile()">download</button>

File upload in Spring

I am trying to upload an audio file using the following code on server.Right now, it works perfectly well for image files but not for audios.I think MultipartFile should work with audio files as well.Can any one tell me what is wrong here? I am getting "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." error.

Does MultipartFile not work with audio files?If no what is an alternative?

@Transactional
public BaseVO uploadImage(MultipartFile file, long userId){
    Map<String, Object> alertParams = new HashMap<String, Object>();

    try{
        if (!file.isEmpty()) {
            Image profileImage = imageRepository.findByUserId(userId);
            if(profileImage == null){
                profileImage = new Image();
                profileImage.setUserId(userId);
            }

            File dir = null;
            String realPath;
            if(liveBuild == "true"){
                realPath = liveImageUploadRepository;
                dir = new File(realPath);
            }else{
                HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
                realPath = request.getSession().getServletContext().getRealPath("/") + devImageUploadRepository;
                dir = new File(realPath);
            }
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String finalFileStorePath = realPath + "/" + userId + ".jpg";
            File path = new File(finalFileStorePath);
            file.transferTo(path);

            profileImage.setImagePath(realPath);
            //profileImage.setImageName(userId + ".jpg");
            profileImage.setImageName(userId+"");
            profileImage.setImageType(".jpg");

            imageRepository.save(profileImage);

            alertParams.put("id", profileImage.getId());
        } else {
            return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
        }
    }catch(HibernateException e){
        return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG + " " + e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
    } catch (IOException e) {
        e.printStackTrace();
        return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
    }
    return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}

J2EE: Spring + Maven + Hibernate integration

I'm trying to get spring and hibernate woring in maven project. Here's my various files:

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <modelVersion>4.0.0</modelVersion>

    <groupId>local.bb</groupId>
    <artifactId>MavenSpringMVC</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <name>MavenSpringMVC</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <org.springframework.version>4.1.6.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>

        <!--
                MAIN / SPRING
        -->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <!--
                SPRING / HIBERNATE
        -->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.0.Beta1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.0.Beta1</version>
        </dependency>

        <!--
                HIBERNATE / TILES
        -->

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>3.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>3.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>3.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-request-api</artifactId>
            <version>1.0.6</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.12</version>
        </dependency>

        <!--
                TILES / ...
        -->

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Config.java

    package local.bb.config;

import java.util.ArrayList;
import java.util.Properties;
import local.bb.test.Test;
import org.hibernate.mapping.Array;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableTransactionManagement
@EnableWebMvc
public class Config {

    @Bean
    ViewResolver viewResolver() {
        InternalResourceViewResolver isvr = new InternalResourceViewResolver();
        isvr.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        isvr.setPrefix("/WEB-INF/views/");
        isvr.setSuffix(".jsp");
        return isvr;
    }


    @Bean
    DriverManagerDataSource dataSource() {
        DriverManagerDataSource dmds = new DriverManagerDataSource("jdbc:mysql://localhost:3306/java?zeroDateTimeBehavior=convertToNull");
        dmds.setUsername("root");
        return dmds;
    }


    @Bean
    LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        lsfb.setDataSource(dataSource());
        lsfb.setPackagesToScan("local.bb.entities");
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        props.setProperty("hibernate.hbm2ddl.auto", "validate");
        lsfb.setHibernateProperties(props);
        return lsfb;
    }
}

dispatcher.servlet.xml

    <?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://ift.tt/GArMu6"
       xmlns:xsi="http://ift.tt/ra1lAU"
       xmlns:p="http://ift.tt/1jdM0fE"
       xmlns:aop="http://ift.tt/OpNdV1"
       xmlns:tx="http://ift.tt/OGfeU2"
       xmlns:context="http://ift.tt/GArMu7"
       xsi:schemaLocation="
            http://ift.tt/1bHqwjR
            http://ift.tt/1kF4x7W
            http://ift.tt/GArMu6 
            http://ift.tt/1cnl1uo
            http://ift.tt/OpNdV1
            http://ift.tt/1eQJ7vy
            http://ift.tt/OGfeU2 
            http://ift.tt/KC395X
            http://ift.tt/GArMu7
            http://ift.tt/1ldEMZY"
       xmlns:mvc="http://ift.tt/1bHqwjR">

    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven />

    <context:annotation-config />
    <context:component-scan base-package="local.bb.*" />
</beans>

If some other files are required to spot my problem I'll paste them. The problem is I get such error when run my app:

Exception while loading the app: 
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in local.bb.config.Config:
Invocation of init method failed; nested exception is java.lang.NoSuchMethodError:
org.hibernate.annotations.common.reflection.java.JavaReflectionManager.injectClassLoaderDelegate(Lorg/hibernate/annotations/common/reflection/ClassLoaderDelegate;)

I've been searching on the Internet for ome time and pom.xml seems to be ok. I even found (potentially missing) class and method in my dependencies jars structure what makes this error even more odd. Additionally the hibernate configuration is pasted from another project(which is not maven) where it works ok. The controllers are good and views are as well. Does anybody have any ideas?

How to map JSON fields to custom object properties?

I have a simple json message with some fields, and want to map it to a java object using spring-web.

Problem: my target classes fields are named differently than int he json response. How can I anyhow map them to the object without having to rename the fields in java?

Is there some annotation that could be placed here?

{
  "message":"ok"
}

public class JsonEntity {
    //how to map the "message" json to this property?
    private String value;
}

RestTemplate rest = new RestTemplate();
rest.getForObject(url, JsonEntity.class);

How do i make a correct architecture for a multi-enterprise application?

I've got a question about the architecture for a JEE application, that is supposed to give personal spaces in the server (also database) for enterprises that make an account with us.

So is it better if i create a new database for each enterprise or do i make them all in the same database ?

I'm currently using Spring Boot, Spring JPA Hibernate, Thymeleaf, MYSQL. (I'm also having an android side to connect with my Servlets)

So do i stick with these or is there something better ?

Thanks for your time. Have a nice day.

Transaction concurrency

Hi Stackoverflow members,

In my Spring application i have a bid button. As the time ramps up, the number of users who click the button will be high. Which may leads to concurrent clicks. How to handle this issue? Can you someone give an idea on this? Thanks in advance

Execute sth. after or before bean is created

I use spring-boot with flyway and a datasource, so both beans are automatically configured by spring-boot. Now I would like to execute sth. either directly after the datasource or before the flyway bean is initialized.

How can I configure externally -preferably with annotations- that flyway dependsOn mySth or that post construct of the datasource sth should be called?

Is it the 'better' approach trying to alter the bean initialization order or registering an ApplicationListener (if possible)?

Spring's method injection

I'm reading the Spring current version's documentation and have problems with understanding of the chapter 5.4.6 Method Injection. As far as I got that we can provide the ability of recreation a bean every time we call the method using the bean. Documentation provides the following code example:

public class CommandManager implements ApplicationContextAware {

    //Imports and comments were omitted
    private ApplicationContext applicationContext;

    public Object process(Map commandState) {
        Command command = createCommand();
        command.setState(commandState);
        return command.execute();
    }

    protected Command createCommand() {
        return this.applicationContext.getBean("command", Command.class);
    }

    public void setApplicationContext(
            ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

where ApplicationContextAware interface looks like:

public interface ApplicationContextAware {

    //JavaDocs ommited
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

So, what is the method public Object process(Map commandState)? Is it a callback? If so, where is it going to be called and who performs that call? After all, it's not clear why the bean is goign to be recreated every time it needed.

File Upload with PUT request

I'm working on file upload handling in server side. I'm using the code posted here. I modified the FileCommand Class code to the following

import org.springframework.web.multipart.MultipartFile;

public class FileUploadCommand {

private MultipartFile file;

public void setFile(MultipartFile file) {
    this.file=file;
}

public MultipartFile getFile() {
    return this.file;
} }

and the dispatcher-servlet.xml

<mvc:annotation-driven/>

<context:component-scan base-package="fileupload"/>

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/api/file/*"/>
            <bean id="fileUploadHandlerInterceptor" class="fileupload.FileUploadHandlerInterceptor">
                 <constructor-arg index="0" ref="putServletFileUpload" />
            </bean>
    </mvc:interceptor>
</mvc:interceptors>



<bean name="putServletFileUpload" class="fileupload.PutServletFileUpload">

    <constructor-arg index="0">
    <bean class="org.apache.commons.fileupload.disk.DiskFileItemFactory" />
    </constructor-arg>
</bean>

The problem is that the HandlerInterceptor which is FileUploadHandlerInterceptor were not called when I tested the application. Could anyone help me to find out the cause of this problem.

MongoDB connection error after an idle application period

We have this behavior of MongoDB connection which is unable to be traced; the MongoDB connections after some application idle time starts getting MongoDB connection error for every request made by the application. Only after the restart of the AppServer ('Tomcat', the application is deployed on) the MongoDB connections are reacquired and works well.

Want to know if anyone have come across such an issue and probable configuration solution. One another way which I think is then to Exception handle and do a retry for getting the connection.

NOTE: Java 1.7, Spring 3.1.x have been used for Server code. MongoDB Version: 2.6.9. Mongo Driver: mongo-2.10.1

How to set up a context.xml for spring with annotations?

I am using Tomcat to host a webapp and would like to know if I can use Spring annotations to create the equivalent of a context.xml in the conf folder of tomcat. An example context.xml:

<?xml version="1.0" encoding="UTF-8"?> <!-- The contents of this file will be loaded for each web application -->
<Context> <!-- Default set of monitored resources -->
    <ResourceLink name="jdbc/SomeDB" global="jdbc/SomeDB" type="javax.sql.DataSource"/>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

If this is possible to do with annotations can you show me how it is done preferably with an example?

Load only required services spring framework

I'm looking for a way to create a free version and a paid version of an application. I was wondering if spring has the functionality to group/tag services so I can switch between services i.e. services which don't do much for a free user and the actual service for the paid user.

Is this the right approach? or is there another framework which lets me do this and works well with spring?

Is there a way I can do the same in the front end i.e. show or hide features/icons based on the type of user?

-- Edited --

The project is a multi module maven project with a war module and 3 jars which uses Spring framework with spring security (nothing fancy) and angularjs.

The requirement is that I should be able to build the war file based on different configuration. For example, lets say a client doesn't want a particular feature, I should be able to turn it off by just changing some configuration. So the user will not see that particular feature anymore.

Can it be done?

Clear database at startup while using flyway

In my case, I'm using spring-boot with gradle and added flyway by simply putting compile 'org.flywaydb:flyway-core' to the build.gradle.

For a simulator run, which is in test, I would like to clear the database before each run. I've put a reset script in /src/test/resources/db/migration/V1.0__Reset.sql (with the real init sql-script at /src/main/resources/db/migration/V1.1__Init.sql), but receive a SyntaxException due to the reset script, which doesn't occur when I run it from the MySQL Workbench.

How can I reset or clear the database at startup?

-- UPDATE --

I've tried to use a Spring DataSourceInitializer, but it seems Flyway scripts are executed before the DS init, so it results in Hibernate Syntax error because the tables aren't found.

@Resource
DataSource ds;

@Bean
public DataSourceInitializer dbInit() throws FileNotFoundException, URISyntaxException {
        public DataSourceInitializer dbInit() throws FileNotFoundException, URISyntaxException {
        DataSourceInitializer re = new DataSourceInitializer();
        re.setDataSource(ds);
        re.setEnabled(true);

        String str = "classpath:sql/V1.0__Reset.sql";
        URL url = ResourceUtils.getURL(str);
        org.springframework.core.io.Resource resi = new PathResource(url.toURI());
        // new org.springframework.core.io.ClassPathResource(str)
        re.setDatabasePopulator(new ResourceDatabasePopulator(resi));
        return re;
    }