samedi 28 février 2015

mysql two FK in the same table

I have three tables: A, B, C. Table C has two FKs which points to A id and B id.


When I try to insert something inside C, if I fill the FK column which points to A with a valid ID and let the FK for B table empty or null or zero, MYSQL throws and error saying that I have another FK to fill.


What is the best solution for this problem?


I was thinking that it would be OK to have two C tables, one for A and the other one for B: C_A, C_B with only one FK in each of them.


I have to consider that I am using also Hibernate JPA and the solution I have will work fine. But this will mean one extra table with the same role.


What is your opinion about this problem?


spring batch and xd good for data integration?

i have tried integration tools such as Kettle, and jasper PDI it is depend on ETL.


i have tried to use spring batch and xd as data integration too, its very nice. but there is no article discus about spring batch or xd data validation (ensure consistence of data, avoid duplicate etc.)


i need some advice about : 1. is spring batch good tools for data integration ? 2. if its good how the technique to do data validation ?


thanks


Spring Batch Write Header

I have a spring-batch file that extracts data from a database and writes it to a .CSV file.


I would like to add the names of the columns that are extracted as the headers of the file without hard coding them on the file.


Is possible to write the header when I get the results or is there another solution?


Thanks


Spring @RequestMapping Controller Forwarding


@RequestMapping({"/someurl"})
public String execute(Model model) {
if (someCondition) {
return "forward:/someUrlA";
} else {
return "forward:/someUrlB";
}
}


Im trying to forward request from a controller to another controller. When I run this the controller returns string as response instead of forwarding to the other controller... Can someone please point out what I'm missing?


Thanks!!


Publishing a NonSpring webservice with CXF (“No services have been found” error)

Here’s my non-spring approach to publishing a webservice:


I have a servlet that extends org.apache.cxf.transport.servlet.CXFNonSpringServlet and overrides the loadBus(ServletConfig) method (The code snippet of the loadBus method is below). This servlet is configured in the web.xml to receive all requests originating with the URL pattern /services/*



@Override
public void loadBus(ServletConfig servletConfig)
{
super.loadBus(servletConfig);
Bus bus = getBus();
BusFactory.setDefaultBus(bus);
Endpoint ep = Endpoint.create(new myWebService());
ep.publish("/myService");
}


I should see the published services with the URL http://ift.tt/1zR9uha. But I all I see with the URL is “No services have been found” – Clearly says publishing failed.. The exception stack trace on server console is as follows:


java.lang.IllegalArgumentException: Cannot create URL for this address /myService at com.sun.xml.ws.transport.http.server.EndpointImpl.publish(EndpointImpl.java:237) at com.chase.ccs.servlet.CCSCXFNonSpringServlet.loadBus(CCSCXFNonSpringServlet.java:37) at org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:76) at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:329) at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:168) at com.ibm.ws.webcontainer.servlet.ServletWrapper.load(ServletWrapper.java:1283) at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:973) at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3703) at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304) at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:953) at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1655) at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:276) at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214) at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113) at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165) at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775) at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1650)


can someone tell me the cause for this issue and how to overcome it?


Career Related (JAVA or DATASTAGE) [on hold]

I am a fresher, I have learnt JAVA/J2EE(core-java,JDBC,servlets,JSP,Hibernate,Spring). Recently I got job, but they have given the position as BI developer.


I am in confusion what to select either go with that profile or try for the java profile.


Is it possible to shift from BI to JAVA in future, please help me choose the better one.


Please help me to choose right path for better future.


Thanks..


HTTP Status 405 - Request method 'POST' not supported - Spring Security

I get the below error when I try to implement Spring security -


web.xml



<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://ift.tt/HeF78r" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

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

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- /WEB-INF/spring-security.xml -->

<!-- Spring Security -->
<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>


Spring-security.xml



<beans:beans xmlns="http://ift.tt/1c8inpe"
xmlns:beans="http://ift.tt/GArMu6" xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/QEDs1e
http://ift.tt/1c8inpe
http://ift.tt/1epvZ6L">

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>

<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
<password-encoder hash="bcrypt" />
</authentication-provider>
</authentication-manager>

</beans:beans>


login.jsp



<body onload='document.loginForm.username.focus();'>

<h1>Spring Security Login Form (Database + Hibernate Authentication)</h1>

<div id="login-box">

<h3>Login with Username and Password</h3>

<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>

<form name='loginForm'
action="<c:url value='/j_spring_security_check' />" method='POST'>

<table>
<tr>
<td>User:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" /></td>
</tr>
</table>

<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />

</form>
</div>

</body>


Error:-



http://localhost:8080/EmployeeManagement/j_spring_security_check


00:01:51.216 [http-8080-2] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
00:02:34.508 [http-8080-2] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
00:02:34.509 [http-8080-2] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
00:02:34.509 [http-8080-2] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1b565e71. A new one will be created.
00:02:34.509 [http-8080-2] DEBUG o.s.security.web.FilterChainProxy - /j_spring_security_check at position 2 of 11 in additional filter chain; firing Filter: 'CsrfFilter'
00:02:34.512 [http-8080-2] DEBUG o.s.security.web.csrf.CsrfFilter - Invalid CSRF token found for http://localhost:8080/EmployeeManagement/j_spring_security_check
00:02:34.515 [http-8080-2] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'mvc-dispatcher' processing POST request for [/EmployeeManagement/403]
00:02:34.516 [http-8080-2] DEBUG o.s.w.s.m.a.DefaultAnnotationHandlerMapping - Mapping [/403] to HandlerExecutionChain with handler [com.employeemgmt.controller.EmployeeController@5c167eac] and 1 interceptor
00:02:34.520 [http-8080-2] DEBUG o.s.w.s.m.a.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.employeemgmt.controller.EmployeeController@5c167eac]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
00:02:34.523 [http-8080-2] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [com.employeemgmt.controller.EmployeeController@5c167eac]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
00:02:34.523 [http-8080-2] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [com.employeemgmt.controller.EmployeeController@5c167eac]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
00:02:34.523 [http-8080-2] WARN o.s.web.servlet.PageNotFound - Request method 'POST' not supported
00:02:34.523 [http-8080-2] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
00:02:34.523 [http-8080-2] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'mvc-dispatcher': assuming HandlerAdapter completed request handling
00:02:34.523 [http-8080-2] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
00:02:34.523 [http-8080-2] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
00:02:34.523 [http-8080-2] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

API Hack (sending the bulk request)

someone is hitting my API with fake parameters, so our system is heavy loaded. we have the source IP in our access log.


Is anyone please tell me what is the right way to block those request. this time we are checking the parameter in controller and then blocking the requests but is taking lots of resources.


how can we block those IP from where we are getting bulk requests.


Apache with Proxypass and Spring Security

I am having a Spring MVC app which uses Spring Security for login. I am using Apache Webserver as Proxy and Tomcat. Below is my /etc/apache2/sites-enabled/example.com.conf file:



ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/http://ift.tt/18GT7ew

ProxyPreserveHost On
ProxyRequests off

ProxyPass /myapp/j_spring_security_check http://localhost:8080/myapp/j_spring_security_check
ProxyPassReverse /myapp/j_spring_security_check http://localhost:8080/myapp/j_spring_security_check
ProxyPass /myapp http://localhost:8080/myapp
ProxyPassReverse /myapp http://localhost:8080/myapp


This works fine and I am able to log into my site. However, I have to use http://ift.tt/x8TEmW instead of http://example.com. If I use later, it shows me:



Index of /

[ICO] Name Last modified Size Description
[IMG] favicon.ico 2015-02-23 14:15 7.6K


If I modify the example.com.conf file as suggested by other sites/posts, I get nothing and http://example.com takes me to http://ift.tt/x8TEmW:



ProxyPass /j_spring_security_check http://localhost:8080/j_spring_security_check
ProxyPassReverse /j_spring_security_check http://localhost:8080/j_spring_security_check
ProxyPass / http://localhost:8080/myapp
ProxyPassReverse / http://localhost:8080/myapp


Can some one please help? Thanks.


Edit:


Below is my ROOT.xml in "~/apache-tomcat-7.0.52/conf/Catalina/localhost" folder which I created as per HOWTO set the context path of a web application in Tomcat 7.0.



<Context
docBase="/home/anuj/webapps/prod-prop-3"
path=""
reloadable="true"
/>


But when I tried this, http://example.com took me to http://ift.tt/1dQYKGD and gave error:



The requested URL /login was not found on this server.



What is the issue here, can someone help please?


(Spring) Filtering multicasters based on event type

I have a custom event, which I call LoginEvent (which extends ApplicationEvent) defined. I have defined a few listeners which are listening to this event. I have figured our how to make the event listeners asynchronous (by changing the taskExecutor within eventMulticaster). This is how I have made my events to be thrown in an asynchronous manner.



<bean id="applicationEventMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster">
<property name="taskExecutor" > <bean class="org.springframework.core.task.SimpleAsyncTaskExecutor"
/> </property> </bean>


But from what I understand, this is going to force ALL of my custom events go asynchronous. I don't want to do that if I can have a way to chose different taskExecutors for different types of events (ir, categorize my Events as Sync ans async). How can I achieve that?


Jackson Mapper configuration needed for Spring REST JSON object

I am getting the following JSON object via a REST API call and I want to be able to pick the information inside the results JSON array and convert the same in POJO for e.g ExchangeListInfo,RedeemCall ... IncomeInformation only


How do i get this done with Jackson 1-9.0 api, I have written some code snippet as well but I cannot seem to figure out how to get the mapping to work in this complex scenario , Any help is appreciated



{
"code": 200,
"results": [
{
"_id": "5168521",

"ExchangeListInfo": {
"InstrumentListingLevel": "ANC",
"SettlementCurrency": "UAH"
},
"RedeemCall": {
"IsMWholeCall": false
},
"MsdInformation": {
"MSDCallPutFlag": "P",
"MSDMinimumDenomination": 1000.0,
"MSDCouponFrequency": "Q",
"MSDBondForm": "B",
"MSDSovDebtFlag": false,
"MSDDatedDt": "2007-04-26T00:00:00.000-04:00",
"MSDMaturityDt": "2010-04-22T00:00:00.000-04:00"
},
"SecInformation": {
"PutFreq": "EQ",
"ItDivFreq": "QWE",
"ItBasDysTyp": "4123",
"PuTyp": "1O"
},
"ConversionBasic": {
"ConversionMandatoryFlag": false
},
"IncomeInformation": {
"AccrualMethod": "ACT/365",
"NextPayDate": "2010-04-22T00:00:00.000-04:00",
"CouponDividendRate": 0.0,
"CouponDividendType": "KAR",
"CouponDividendCurrency": "9AH",
"CouponDividendFrequency": 4,
"LastPayDate": "2010-01-21T00:00:00.000-05:00",
"FirstPayDate": "2007-07-26T00:00:00.000-04:00",
"PreviousPaymentDate": "2010-01-21T00:00:00.000-05:00",
"DatedDate": "2007-04-26T00:00:00.000-04:00",
"IsPayInKind": false,
"UnadjustedPreviousCouponPayDat": "2010-01-21T00:00:00.000-05:00"
},

"version": 1,
"id": 1615,
"cloudstamp": "2010-12-04T11:46:20.739-05:00"
}
]//end of results
}

Spring Data JPA Persisting Entity with a nested Composite Primary Key entity with itself a nested entity which is detached at persist time

I have three jpa entities I’m trying to get working together. BoxProfile, BoxProfileItemAssignment and BoxItem all code listed below. BoxProfileItemAssignment has a @EmbeddedId using @MapId to map the composite key.


BoxProfile has a set of BoxProfileItemAssignments, the assignments are a BoxItem and quantity value. I want to be able to persist BoxProfileItemAssignments while persisting a new BoxProfile. Each BoxItem in a BoxProfileItemAssignments has already been persisted when a BoxProfile is being created.


I'm using spring data JpaRepository interfaces to persist my BoxProfile entities and accessing the repo through a service layer BoxProfileService.


When I attempt to persist a new BoxProfile entity I get a PersistenceException due to a detached entity. I understand that the BoxItem that is nested in the BoxProfileItemAssignment entity I'm passing in is detached but I'm not looking to make and changes or updates to said entity I just want to use it create the BoxProfileItemAssignment entry.


After much research I can't seem to find an example of Cascading persisted with a nested composite key entity which itself has a nested entity.


I would appreciate if someone could tell me what the correct combination of annotations are to achieve my goal.



javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.quadrimular.fyfe.fulfillment.domain.BoxItem
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1187)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
at com.sun.proxy.$Proxy53.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:394)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:442)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:427)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:381)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy65.save(Unknown Source)
at com.quadrimular.fyfe.fulfillment.service.BoxProfileServiceImpl.addBoxProfile(BoxProfileServiceImpl.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy66.addBoxProfile(Unknown Source)
at com.quadrimular.fyfe.fulfillment.integration.ITBoxProfile.addBoxProfileDatabase(ITBoxProfile.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.quadrimular.fyfe.fulfillment.domain.BoxItem
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:97)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:432)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:137)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:97)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:379)
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:319)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:296)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:460)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:294)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
... 72 more


BoxProfile test method



@Test
@ExpectedDatabase(value = "boxProfileData-add.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
public void addBoxProfileDatabase() throws Exception {
BoxProfileItemAssignment itemAssignment = new BoxProfileItemAssignment.Builder(BOX_ITEM_ONE, new BigDecimal("2.88")).build();
BoxProfile original = new BoxProfile.Builder("example 3").itemAssignments((new HashSet(Arrays.asList(itemAssignment)))).sizes(new HashSet(Arrays.asList(BOX_SIZE))).selected(true).sequencer(3).build();

BoxProfile returned = boxProfileService.addBoxProfile(original);

assertNotNull(returned);
assertThat(returned.getId(), instanceOf(Long.class));
assertNotNull(returned.getId());
}


BoxProfileRepository.java



public interface BoxProfileRepository extends JpaRepository<BoxProfile, Long> {

}


BoxProfileServiceImpl.java



@Service
@Transactional("mainTransactionManager")
public class BoxProfileServiceImpl implements BoxProfileService {

private static final Logger LOG = LoggerFactory
.getLogger(BoxProfileServiceImpl.class);

private BoxProfileRepository repo;
private BoxItemService boxItemService;

@Autowired
public BoxProfileServiceImpl(BoxProfileRepository repo, BoxItemService boxItemService) {
this.repo = repo;
this.boxItemService = boxItemService;
}

@Transactional("mainTransactionManager")
public BoxProfile addBoxProfile(BoxProfile boxProfile) {
LOG.debug("Adding boxProfile with information: " + boxProfile);
BoxProfile toReturn = repo.save(boxProfile);
LOG.debug("BoxProfile id: " + toReturn);
return toReturn;
}
}


BoxProfile.java



@Entity
@Table
public class BoxProfile implements Serializable {

private static final long serialVersionUID = 9091824819977165224L;

@Id
@GeneratedValue
private Long id;
private String description;
private boolean selected;
private int sequencer;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "boxProfileSizes", joinColumns = { @JoinColumn(name = "BOX_PROFILE_ID", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "SIZE_ID", referencedColumnName = "id") })
private Set<BoxSize> sizes;

@OneToMany(mappedBy = "boxProfile", cascade={CascadeType.PERSIST, CascadeType.REMOVE}, fetch = FetchType.EAGER)
private Set<BoxProfileItemAssignment> itemAssignments;

// Modification times
private Date creationTime;
private Date modificationTime;

@PreUpdate
public void preUpdate() {
setModificationTime(new Date());
}

@PrePersist
public void prePersist() {
Date now = new Date();
setCreationTime(now);
setModificationTime(now);
}

public BoxProfile() {
}

private BoxProfile(Builder b) {
this.description = b.description;
this.id = b.id;
this.selected = b.selected;
this.sequencer = b.sequencer;
this.sizes = b.sizes;
}

public static class Builder {
// Mandatory Fields
private final String description;
// Optional Fields
private Long id = null;
private boolean selected = false;
private int sequencer = -1;

private Set<BoxSize> sizes = new HashSet<BoxSize>();
private Set<BoxProfileItemAssignment> itemAssignments = new HashSet<BoxProfileItemAssignment>();

public Builder(String description) {
this.description = description;
}

public Builder sequencer(int sequencer) {
this.sequencer = sequencer;
return this;
}

public Builder sizes(Set<BoxSize> sizes) {
this.sizes = sizes;
return this;
}

public Builder addSize(BoxSize size) {
this.sizes.add(size);
return this;
}

public Builder itemAssignments(
Set<BoxProfileItemAssignment> itemAssignments) {
this.itemAssignments = itemAssignments;
return this;
}

public Builder id(Long id) {
this.id = id;
return this;
}

public Builder selected(boolean selected) {
this.selected = selected;
return this;
}

public BoxProfile build() {
BoxProfile boxProfile = new BoxProfile(this);
// Add the new box profile to the box profile assigned fish.
for (BoxProfileItemAssignment assignment : itemAssignments) {
assignment.setBoxProfile(boxProfile);
}
// Set the updated fish assignments on the box profile
boxProfile.setItemAssignements(itemAssignments);

return boxProfile;
}
}

// Getters setters hashcode equals to string



}


BoxProfileItemAssignment.java



@Entity
@Table(name = "BOX_PROFILE_ITEM")
public class BoxProfileItemAssignment implements Serializable{

private static final long serialVersionUID = 3331165661732043732L;

@EmbeddedId
private BoxProfileItemAssignmentId id = new BoxProfileItemAssignmentId();

@MapsId("boxProfileId")
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "BOX_PROFILE_ID", referencedColumnName = "id")
private BoxProfile boxProfile;

@MapsId("itemId")
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ITEM_ID", referencedColumnName = "id")
private BoxItem item;

private BigDecimal quantity;

// Modification times
private Date creationTime;
private Date modificationTime;

@PreUpdate
public void preUpdate() {
setModificationTime(new Date());
}

@PrePersist
public void prePersist() {
Date now = new Date();
setCreationTime(now);
setModificationTime(now);
}

private BoxProfileItemAssignment(Builder b){
this.boxProfile = b.boxProfile;
this.item = b.item;
this.quantity = b.quantity;
this.id = b.id;
}

public BoxProfileItemAssignment(){}

public static class Builder {

private final BoxItem item;
private final BigDecimal quantity;

private BoxProfile boxProfile;
private BoxProfileItemAssignmentId id = new BoxProfileItemAssignmentId();

public Builder(BoxItem item, BigDecimal quantity){
this.item = item;
this.quantity = quantity;
}
public Builder boxProfile(BoxProfile boxProfile){
this.boxProfile = boxProfile;
return this;
}

public Builder id(BoxProfileItemAssignmentId id){
this.id = id;
return this;
}

public BoxProfileItemAssignment build(){
return new BoxProfileItemAssignment(this);
}
}

// Getters setters hashcode equals to string




}


BoxProfileItemAssignmentId



@Embeddable
public class BoxProfileItemAssignmentId implements Serializable{

private static final long serialVersionUID = -7936926474216068447L;

@Column(name = "BOX_PROFILE_ID")
private Long boxProfileId;
@Column(name = "ITEM_ID")
private Long itemId;



public BoxProfileItemAssignmentId(){}

private BoxProfileItemAssignmentId(Builder b){
this.boxProfileId = b.boxProfileId;
this.itemId = b.itemId;
}
public static class Builder{
private final Long boxProfileId;
private final Long itemId;

public Builder(Long boxProfileId, Long itemId){
this.boxProfileId = boxProfileId;
this.itemId = itemId;
}

public BoxProfileItemAssignmentId build(){
return new BoxProfileItemAssignmentId(this);
}
}

// Getters setters hashcode equals to string




}


BoxItem.java



@Entity
@Table
public class BoxItem implements Serializable {

private static final long serialVersionUID = -6146188094809573420L;

@Id
@GeneratedValue
private Long id;

@NotNull
private BoxItemType type;
@NotNull
private MeasurementUnit unit;
@NotNull
@Size(min=2, max=30)
private String name;
@NotNull
private BigDecimal costPerUnit;

// Modification times
private Date creationTime;
private Date modificationTime;

@PreUpdate
public void preUpdate() {
modificationTime = new Date();
}

@PrePersist
public void prePersist() {
Date now = new Date();
creationTime = now;
modificationTime = now;
}
public BoxItem(){}

private BoxItem(Builder b){
this.type = b.type;
this.name = b.name;
this.costPerUnit = b.costPerUnit;
this.id = b.id;
this.unit = b.unit;
}

public static class Builder{
private BoxItemType type;
private MeasurementUnit unit;
private String name;
private BigDecimal costPerUnit;

private Long id;

public Builder(String name, BoxItemType type, MeasurementUnit unit, BigDecimal costPerUnit){
this.name = name;
this.type = type;
this.unit = unit;
this.costPerUnit = costPerUnit;
}

public Builder id(Long id){
this.id = id;
return this;
}
public BoxItem build(){
return new BoxItem(this);
}
}

// Getters setters hashcode equals to string


}

I am getting an error when I try to run a simple Spring project. Please help me

I am using the latest Spring JARS. I created a very small application where it renders Hello on a JSP.


However, it says that I have a problem in my dispatcher servlet where I declare the bean definition. Please help me. This is my hello Controller



package com.raghav.hellocontroller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

public class HelloController {

protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView modelandview = new ModelAndView("HelloPage");
modelandview.addObject("welcomeMessage","Hi User, welcome to the first Spring MVC Application");

return modelandview;
}
}


This is my web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://ift.tt/ra1lAU" xmlns="http://ift.tt/nSRXKP" xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1eWqHMP" id="WebApp_ID" version="3.0">
<display-name>SpringMVCTutorial</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


This is my dispatcher servlet



<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/1E5zs6r http://ift.tt/GAf8ZW">

<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMaping"/>

<bean name="/welcome.html" class="com.raghav.hellocontroller.HelloController" />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

Dozer + Spring: MappingException: Dozer Bean Mapper is already initialized

I am trying to implement Dozer as help for bridge pattern on my current webapp running Spring and Hibernate but I think I am doing something wrong, since trying to use a DozerBeanMapper instance more than once, will give me a MappingException.


Spring config:



@Configuration
public class AppConfig {
...
@Bean
public DozerBeanMapper dozerBeanMapper() {
return new DozerBeanMapper();
}
}


Usage:



@Service
public class FooService {
@Autowired private DozerBeanMapper mapper;

public void doSomething() {
mapper.map(foo, ImmutableFoo.class);
...
}


First time I call this service will work fine, but any further attempt to use it will result in an exception. Can someone please point what I am doing wrong?


Thanks.


Spring 4 Converters

I'm writing a webserivce using Spring 4. I have a problem with data binding. I've got org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.Set' for property 'groups'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [pl.tt.springtpl.models.Group] for property 'groups[0]': no matching editors or conversion strategy found exception. I'm sending an object in json. In service I binding properties of received map to entity. All is ok if the properties are primitive. But If I have a custom pojo I have that exception.


I wrote two classes:



public class ArrayListToSetConverter implements Converter<ArrayList, Set>{

public Set convert(ArrayList source) {
Set set = new HashSet();
set.addAll(source);
return set;
}

}


and I'm trying to do it more generic with this class:



public class StringToAbstractEntityConverter implements ConditionalGenericConverter{

public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair cp = new ConvertiblePair(String.class, SimpleAbstractEntity.class);
Set<ConvertiblePair> set = new HashSet<ConvertiblePair>();
set.add(cp);
return set;
}

public Object convert(Object o, TypeDescriptor td, TypeDescriptor td1) {
Object w = td.getClass();
return o;
}

public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if(sourceType.getObjectType() == String.class && targetType.isAssignableTo(TypeDescriptor.valueOf(SimpleAbstractEntity.class))){
String idAsTxt = (String)sourceType.getSource();
long id = Long.valueOf(idAsTxt);
}

return true;
}
}


I add line in @Configuration class:



@Override
public FormattingConversionService mvcConversionService() {
FormattingConversionService bean = super.mvcConversionService(); //To change body of generated methods, choose Tools | Templates.
bean.addConverter(new StringToAbstractEntityConverter());
bean.addConverter(new ArrayListToSetConverter());
return bean;
}


But when I add a breakpoint in StringToAbstractEntityConverter app doens't stop in it. So it doesn't use this class...


I want to convert id from client to Object...


I will be very grateful if someone could help me with this :)


Best regards, Matt.


Spring, Hibernate, JPA: Lazy loading id's

I'm currently in the process of converting a large project from Grails to Spring: I'm somewhat stuck when attempting to lazy-load objects id's without having to select the entire table.


The way I would like it to work, /Object/:



Object
List<child> children


to be output like so:



{children:[{id:1},{id:2}]}


So that from another controller I can then access that inner object if required using regular CRUD methods which I have implemented across all of my controllers. /child/1


With the JSON output in mind, I'm having trouble with no Session being available during serialization which is understandable, I've seen methods such as calling object.child.getId() in the service layer seems incredibly hacky to me and would also cause the entire object to be Lazily-loaded.


Overall, I'm looking to create a simple Rest Application with easy customization of the json output, something grails did with the JSON Marshalling plugin really quite well: http://ift.tt/185BLrP


Edit: I don't really wish to set eager loading, but Eager loading is a possibility. Is there a way of getting Eager Loading with a max depth?



{
children: { //depth 1
children-children: { //depth 2 (Ignore this)
}
}
}

How to replicate a maven multi module, web fragment application structure in Spring boot

I am trying to replicate a Maven multi-module like application which uses web fragments in Spring boot but have been failing miserable.


Basically what I am trying to replicate in Spring Boot, which I can easily do with my regular web.xml and web-fragment.xml is to have a Spring MVC as a maven module (let's call it ModuleA) with it's DispatcherServlet mapped to /Module. This mapping and the configuration that provides the DispatcherServlet its spring config file is located in a web-fragment.xml file.


Then I have another module (let's call it ModuleB) which has the web-inf/web.xml file, has ModuleA as its dependency and it is the module that is deployed.


This set up allows for the possibility to easily embed Spring MVC as a "library" that exposes its functionality via a specific path. The the example above its /Module.


Now in Spring Boot, I have seen that by default "/" is mapped to the DispatcherServlet which makes use of a spring application context consisting of the various beans Spring-boot thinks you need plus all the classes annotated with (@Component, @Service etc). Good.


The question then is, how do I configure my Spring MVC app in another module to be exposed via it's own unique path and have access to its own Spring application context?


I have tried using ServletRegistrationBean but what that does is to replace the default "/" to whatever mapping I provide. Which is not what I want. I want the default "/" to still map to the default DispatcherServlet while I specify another path that gets mapped to another DispatcherServlet in the maven module.


I am running with the embedded tomcat.


Is this even possible with Spring Boot?


Update: Now that I think about it, removing the distractions of multi module, web fragments etc. The essence of what I want to achieve is to have multiple SpringMVC in a Spring boot project.


java.lang.NoClassDefFoundError: org/springframework/web/servlet/support/RequestDataValueProcessor

I'm building a Spring application and implementing spring security features within it. But get error when I try to run the application.


web.xml



<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://ift.tt/HeF78r" >

<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

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

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- /WEB-INF/spring-security.xml -->

<!-- Spring Security -->
<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>


mvc-dispatcher-servlet.xml



<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU" xmlns:aop="http://ift.tt/OpNdV1"
xmlns:context="http://ift.tt/GArMu7"
xmlns:jee="http://ift.tt/OpNaZ5" xmlns:lang="http://ift.tt/OGfeTY"
xmlns:p="http://ift.tt/1jdM0fE" xmlns:tx="http://ift.tt/OGfeU2"
xmlns:util="http://ift.tt/OGfeTW"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG
http://ift.tt/OpNdV1 http://ift.tt/1feTlrW
http://ift.tt/GArMu7 http://ift.tt/1jdLYo7
http://ift.tt/OpNaZ5 http://ift.tt/1feTnjL
http://ift.tt/OGfeTY http://ift.tt/1feTlrY
http://ift.tt/OGfeU2 http://ift.tt/18tm2Tg
http://ift.tt/OGfeTW http://ift.tt/1feTls0">

<context:component-scan base-package="com.employeemgmt.controller" />

<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}"></bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- http://ift.tt/1EAw7Ly
<bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean>

<bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean>
-->
<tx:annotation-driven />

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

</beans>


spring-security.xml

<beans:beans xmlns="http://ift.tt/1c8inpe"
xmlns:beans="http://ift.tt/GArMu6" xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/QEDs1e
http://ift.tt/1c8inpe
http://ift.tt/1epvZ6L">

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>

<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
<password-encoder hash="bcrypt" />
</authentication-provider>
</authentication-manager>

</beans:beans>


spring-security.xml



<beans:beans xmlns="http://ift.tt/1c8inpe"
xmlns:beans="http://ift.tt/GArMu6" xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/QEDs1e
http://ift.tt/1c8inpe
http://ift.tt/1epvZ6L">

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http>

<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
<password-encoder hash="bcrypt" />
</authentication-provider>
</authentication-manager>

</beans:beans>


error:-



org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/spring-security.xml]; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/servlet/support/RequestDataValueProcessor
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4210)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4709)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:822)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: java.lang.NoClassDefFoundError: org/springframework/web/servlet/support/RequestDataValueProcessor
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2854)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1159)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.springframework.security.config.http.CsrfBeanDefinitionParser.parse(CsrfBeanDefinitionParser.java:61)
at org.springframework.security.config.http.HttpConfigurationBuilder.createCsrfFilter(HttpConfigurationBuilder.java:651)
at org.springframework.security.config.http.HttpConfigurationBuilder.<init>(HttpConfigurationBuilder.java:162)
at org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.createFilterChain(HttpSecurityBeanDefinitionParser.java:135)
at org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.parse(HttpSecurityBeanDefinitionParser.java:99)
at org.springframework.security.config.SecurityNamespaceHandler.parse(SecurityNamespaceHandler.java:106)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1335)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1325)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:93)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 28 more
Caused by: java.lang.ClassNotFoundException: org.springframework.web.servlet.support.RequestDataValueProcessor
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
... 47 more

java.lang.NoClassDefFoundError on a maven multi module project

I work on a maven multi module project. The modules are: the persistence module called entities packaged as jar, the services module called services packaged as jar and the web module called web packaged as war. The pom is the following:



<groupId>com.af</groupId>
<artifactId>eMuse</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>

<modules>
<module>entities</module>
<module>services</module>
<module>web</module>
</modules>


Each module has his own application context file where I declare the beans.


entities-context.xml



<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG">

<bean id="actionDAO" class="com.af.dao.impl.ActionDAOImpl" />
<bean id="milestoneDAO" class="com.af.dao.impl.MilestoneDAOImpl" />
<bean id="milestoneMarksDAO" class="com.af.dao.impl.MilestoneMarksDAOImpl" />
<bean id="milestoneTypeDAO" class="com.af.dao.impl.MilestoneTypeDAOImpl" />
<bean id="studentDAO" class="com.af.dao.impl.StudentDAOImpl" />
<bean id="studentsActionsDAO" class="com.af.dao.impl.StudentsActionsDAOImpl"></bean>
<bean id="teamDAO" class="com.af.dao.impl.TeamDAOImpl" />
<bean id="toolDAO" class="com.af.dao.impl.ToolDAOImpl" />
</beans>


services-context.xml



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG">

<bean id="studentService" class="com.af.service.impl.StudentServiceImpl"/>
</beans>


Also in the services pom.xml I added the dependency on the entities module.



<parent>
<groupId>com.af</groupId>
<artifactId>eMuse</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>services</artifactId>

<dependency>
<groupId>com.af</groupId>
<artifactId>entities</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>


And the web module configuration file



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU" xmlns:context="http://ift.tt/GArMu7"
xmlns:mvc="http://ift.tt/1bHqwjR" xmlns:p="http://ift.tt/1jdM0fE"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1CZCNBy
http://ift.tt/GArMu7 http://ift.tt/1tY3uA9
http://ift.tt/1bHqwjR http://ift.tt/YzZ6hD">


<mvc:annotation-driven />

<context:component-scan base-package="com.af" />
<import resource="classpath*:entities-context.xml"/>
<import resource="classpath*:services-context.xml"/>
<!-- Tiles configuration -->

<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.tiles2.TilesView</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<mvc:default-servlet-handler />
</beans>


web/pom.xml



<parent>
<groupId>com.af</groupId>
<artifactId>eMuse</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>web</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.af</groupId>
<artifactId>services</artifactId>
<version>1.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>com.af</groupId>
<artifactId>entities</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- other dependencies-->
</dependencies>


And when i run:



@Controller
public class TestController {

@Autowired
private StudentService studentService;

@RequestMapping(value="/index", method = RequestMethod.GET)
public String test(Model model){

StudentModel stud = StudentModelMapper.mapStudentDTO(studentService.getStudentById(1));
model.addAttribute("name", stud.getFirstName());
return "index";
}


}


I get the exception:



org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.af.service.StudentService com.af.controller.TestController.studentService; nested exception is java.lang.NoClassDefFoundError: Lcom/af/dao/StudentDAO;


Can anyone tell me what i am doing wrong?


EDIT: How do i access the application-context file of the entities jar in the services module and then the services application-context file in the web module?


File inbound-channel-adapter spring integration for Multiple Files aggregation into one master File for Job processing

I have written a code to combined multiple files into one single Master file. The issue is with int-transformer where I am getting one file at a time although I have aggregated List of File in composite Filter of File inbound-channel-adapter. The List of File size in composite filter is correct but in Transformer bean the List of File size is always one and not getting the correct list size aggregated file by the filter.


Here is my config:



<!-- Auto Wiring -->
<context:component-scan base-package="com.nt.na21.nam.integration.*" />
<!-- intercept and log every message -->
<int:logging-channel-adapter id="logger"
level="DEBUG" />
<int:wire-tap channel="logger" />

<!-- Aggregating the processed Output for OSS processing -->

<int:channel id="networkData" />
<int:channel id="requests" />

<int-file:inbound-channel-adapter id="pollProcessedNetworkData"
directory="file:${processing.files.directory}" filter="compositeProcessedFileFilter"
channel="networkData">
<int:poller default="true" cron="*/20 * * * * *" />

</int-file:inbound-channel-adapter>

<bean id="compositeProcessedFileFilter"
class="com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine" />

<int:transformer id="aggregateNetworkData"
input-channel="networkData" output-channel="requests">
<bean id="networkData" class="com.nt.na21.nam.integration.helper.CSVFileAggregator">
</bean>
</int:transformer>


CompositeFileListFilterForBaseLine:


public class CompositeFileListFilterForBaseLine implements FileListFilter {



private final static Logger LOG = Logger
.getLogger(CompositeFileListFilterForBaseLine.class);

@Override
public List<File> filterFiles(File[] files) {
List<File> filteredFile = new ArrayList<File>();
int index;
String fetchedFileName = null;
String fileCreatedDate = null;
String todayDate = DateHelper.toddMM(new Date());
LOG.debug("Date - dd-MM: " + todayDate);

for (File f : files) {
fetchedFileName = StringUtils.removeEnd(f.getName(), ".csv");
index = fetchedFileName.indexOf("_");

// Add plus one to index to skip underscore
fileCreatedDate = fetchedFileName.substring(index + 1);
// Format the created file date
fileCreatedDate = DateHelper.formatFileNameDateForAggregation(fileCreatedDate);
LOG.debug("file created date: " + fileCreatedDate + " today Date: "
+ todayDate);
if (fileCreatedDate.equalsIgnoreCase(todayDate)) {
filteredFile.add(f);
LOG.debug("File added to List of File: " + f.getAbsolutePath());
}
}
LOG.debug("SIZE: " + filteredFile.size());
LOG.debug("filterFiles method end.");
return filteredFile;
}


}


The Class file for CSVFileAggregator public class CSVFileAggregator {



private final static Logger LOG = Logger.getLogger(CSVFileAggregator.class);

private int snePostion;

protected String masterFileSourcePath=null;

public File handleAggregateFiles(List<File> files) throws IOException {
LOG.debug("materFileSourcePath: " + masterFileSourcePath);
LinkedHashSet<String> allAttributes = null;
Map<String, LinkedHashSet<String>> allAttrBase = null;
Map<String, LinkedHashSet<String>> allAttrDelta = null;
LOG.info("Aggregator releasing [" + files.size() + "] files");
}


}


Log Output:


INFO : com.nt.na21.nam.integration.aggregator.NetFileAggregatorClient - NetFileAggregator context initialized. Polling input folder... INFO : com.nt.na21.nam.integration.aggregator.NetFileAggregatorClient - Input directory is: D:\Projects\csv\processing DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - Date - dd-MM: 0103 DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - file created date: 0103 today Date: 0103 DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - File added to List of File: D:\Projects\NA21\NAMworkspace\na21_nam_integration\csv\processing\file1_base_0103.csv DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - file created date: 0103 today Date: 0103 DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - File added to List of File: D:\Projects\NA21\NAMworkspace\na21_nam_integration\csv\processing\file2_base_0103.csv DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - SIZE: 2 DEBUG: com.nt.na21.nam.integration.file.filter.CompositeFileListFilterForBaseLine - filterFiles method end. DEBUG: org.springframework.integration.file.FileReadingMessageSource - Added to queue: [csv\processing\file1_base_0103.csv, csv\processing\file2_base_0103.csv] INFO : org.springframework.integration.file.FileReadingMessageSource - Created message: [GenericMessage [payload=csv\processing\file2_base_0103.csv, headers={timestamp=1425158920029, id=cb3c8505-0ee5-7476-5b06-01d14380e24a}]] DEBUG: org.springframework.integration.endpoint.SourcePollingChannelAdapter - Poll resulted in Message: GenericMessage [payload=csv\processing\file2_base_0103.csv, headers={timestamp=1425158920029, id=cb3c8505-0ee5-7476-5b06-01d14380e24a}] DEBUG: org.springframework.integration.channel.DirectChannel - preSend on channel 'networkData', message: GenericMessage [payload=csv\processing\file2_base_0103.csv, headers={timestamp=1425158920029, id=cb3c8505-0ee5-7476-5b06-01d14380e24a}] DEBUG: org.springframework.integration.handler.LoggingHandler - org.springframework.integration.handler.LoggingHandler#0 received message: GenericMessage [payload=csv\processing\file2_base_0103.csv, headers={timestamp=1425158920029, id=cb3c8505-0ee5-7476-5b06-01d14380e24a}] DEBUG: org.springframework.integration.handler.LoggingHandler - csv\processing\file2_base_0103.csv DEBUG: org.springframework.integration.channel.DirectChannel - postSend (sent=true) on channel 'logger', message: GenericMessage [payload=csv\processing\file2_base_0103.csv, headers={timestamp=1425158920029, id=cb3c8505-0ee5-7476-5b06-01d14380e24a}] DEBUG: org.springframework.integration.transformer.MessageTransformingHandler - org.springframework.integration.transformer.MessageTransformingHandler@606f8b2b received message: GenericMessage [payload=csv\processing\file2_base_0103.csv, headers={timestamp=1425158920029, id=cb3c8505-0ee5-7476-5b06-01d14380e24a}] DEBUG: com.nt.na21.nam.integration.helper.CSVFileAggregator - materFileSourcePath: null INFO : com.nt.na21.nam.integration.helper.CSVFileAggregator - Aggregator releasing [1] files


Can some one help me here in identifying the issue with Filter and same is not collecting for transformation?


Thanks in advance.


Writing CRUDRepository's findBy() method on a field annotated by JoinColumn

I'm kind of new to Spring JPA, so I apologize in advance if my question sounds basic. I have 2 entity objects: OrderInfo, and PersonInfo. The classes are as below:



@Entity
@Table(name="order_info")
@NamedQuery(name="OrderInfo.findAll", query="SELECT o FROM OrderInfo o")
public class OrderInfo implements Serializable {

@Column(name="order_number")
private String orderNumber;

//bi-directional many-to-one association to PersonInfo
@ManyToOne
@JoinColumn(name="person_id")
private PersonInfo personInfo;

public String getOrderNumber() {
return this.orderNumber;
}

public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}

public PersonInfo getPersonInfo() {
return this.personInfo;
}

public void setPersonInfo(PersonInfo personInfo) {
this.personInfo = personInfo;
}


}


And the Person entity:



@Entity
@Table(name="person_info")
@NamedQuery(name="PersonInfo.findAll", query="SELECT p FROM PersonInfo p")
public class PersonInfo implements Serializable {

//bi-directional many-to-one association to OrderInfo
@OneToMany(mappedBy="personInfo")
private List<OrderInfo> orderInfos;

public List<OrderInfo> getOrderInfos() {
return this.orderInfos;
}

public void setOrderInfos(List<OrderInfo> orderInfos) {
this.orderInfos = orderInfos;
}

public OrderInfo addOrderInfo(OrderInfo orderInfo) {
getOrderInfos().add(orderInfo);
orderInfo.setPersonInfo(this);

return orderInfo;
}

public OrderInfo removeOrderInfo(OrderInfo orderInfo) {
getOrderInfos().remove(orderInfo);
orderInfo.setPersonInfo(null);

return orderInfo;
}

}


These two classes were auto-generated in Eclipse using JPA's create entityfromtable option.


Now, I'm trying to write a CRUDRepository to get OrderInfo given an orderNumber, and personId. If I had a personId field in the OrderInfo object, I could have written something like



@Repository
public interface OrderRepository extends CrudRepository<OrderInfo, Integer>{
public OrderInfo findByPersonIdAndOrderNumber(@Param("personId") Long personId, @Param("orderNumber") String orderNumber);

}


However, now the OrderInfo entity does not have a personId. Instead, it has a reference to a Person (Again, I did not write the entity classes. They were auto-generated by Eclipse). How should I write the findBy() method now?


Thanks in advance.


Using EL expression inside ID field (Spring WebFlow)

I have a constant class



@Component
public class NameConstants implements Serializable{
public final static String NAME = "randomName";
public static String getNAME() {
return NAME;
}
}


And the following webflow doesn't seems to work for me:



<subflow-state id="#{NameConstants.NAME }" subflow="someflow">


Is it possible to use EL expression inside the ID field? I keep getting the error:



'#{NameConstants.NAME }'is not a valid value for 'NCName'.

WSO2 Identity Server Change Password On Logon from App

I'm hoping someone can assist. I currently using WSO2 Identity Server as my LDAP provider for my web application. I'm using Spring Security to authenticate a user against the server. This works well, but I'd like to enforce a policy that the user must change password when logging in to my app for the first time. How do I configure IS for this password policy? I see several properties in identity-mgt.properties that may be useful, but very little in the way of documentation on what they actually do. Further, ideally, this password change on logon would be reflected in LdapUserDetailsImpl.credentialsNonExpired, but I'd be willing to use whatever means necessary to gather this information about the user so they could be redirected to a change password page.


Thanks, Tim


How to stop/start spring DefaultMessageListenerContainer?

I have developed project using Spring JMS to receive the message from Queue. and it is deployed Websphere application Server (WAS 7.5) clustered environment. it is working fine once it is deployed in server.Later i have update my logger information and deployed in to server. it seems server not picking the latest code base. Even though i have stop/start the cluster.


Please refer below config xml.



<bean id="connectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName" value="${hostName}"/>
<property name="port" value="${port}"/>
<property name="queueManager" value="${queueManager}"/>
<property name="transportType" value="${transportType}"/>
<property name="channel" value="${channel}"/>
</bean>

<jms:listener-container container-type="default"
connection-factory="connectionFactory" acknowledge="auto" concurrency="5" >
<jms:listener destination="DEV.TESTQUEUE" ref="jmsMessageListener"
</jms:listener-container>

<bean id="jmsMessageListener" class="JmsMessageListener"/>


public class JmsMessageListener implements MessageListener {

public void onMessage(Message message) {

}
}



Could you please advise how to stop/start the container?

How to get key value from properties file at runtime using spring

I want to get the changed key value from properties file at runtime.


test.properties file: name = Hi


I have made Thread sleep with 5 sec and changed the key value as "Hello" but it is not getting changed.


classpath:test.properties



Blockquote




<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:test</value>
</list>
</property>
<property name="cacheSeconds" value="1" />
</bean>
<bean id="tempBean" name="tempBean1" class="org.sri.spring.temp.Temp"
lazy-init="false" scope="prototype">
<constructor-arg type="String" value="${name}" />
</bean>

Error while deploying Spring Batch Application - java.lang.NoClassDefFoundError: org/codehaus/jettison/mapped/MappedXMLOutputFactory

I am stuck with this error from last few days , while loading the spring batch application,it keep on giving error org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in ServletContext resource [/WEB-INF/classes/spring/batch/jobs/config/context.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/codehaus/jettison/mapped/MappedXMLOutputFactory


I have added jettison to my pom and here below my pom file looks like org.codehaus.jettison jettison 1.3.2 org.springframework spring-webmvc ${spring.version} org.springframework spring-oxm ${spring.version} org.springframework.batch spring-batch-test ${spring.batch.version} jettison org.codehaus.jettison


I want to include a view in my .jsp page that is mapped by a spring controller. Here is the controller method:



@RequestMapping("/include/header")
public String showHeader() {
return "include/header";
}


And here is the include tag from the jsp page:



<jsp:include page="/include/header">


It works, but eclipse flags the above line with "Fragment "/include/header" was not found at expected path ..." . Is there a better way to do this that will make eclipse happy? I do want the header file to have its own controller method, otherwise I would just make it a static resource.


Thanks!


Spring Security Angularjs + Android REST

I am wondering what is the best approach to implement Spring Security to secure a REST api that will be accessed by two types of clients, Angularjs and Android.


I have read many sources online in search of the perfect answer but I have not found what I am looking for (as of yet).


Ideally, the two clients will go through the exact same authentication process so that the one set of code is easily maintainable (Hence, the reason I am developing in Angularjs - so that both clients can share the same code base). I assume that I will be lead down the oauth2 route and have the token being passed with every api call once authentication has occurred but as I said, this is an assumption. I seen JSESSION mentioned here and there but nothing too detailed that I could grasp the concept 100%.


I am not looking for the easy way out as I have spent a lot of the day researching this. I am a student so I am do not have the most in depth knowledge but if I can could get pointed in the right direction that I would highly appreciate it.


Some of the sources include - although there were a LOT more: http://ift.tt/16sJS21 http://ift.tt/1wyRBSb


What is the ideal implementation to authenticate these different REST clients?


AbstractAnnotationConfigDispatcherServletInitializer in Spring and Registration of Classes

i am converting my xml based spring app to java config and the hell break lose. I have several @config classes and my problem is the registration of MyWebConfiguration.class. This class is a child of RepositoryRestMvcConfiguration and has of course some @bean methods in it. But no @bean method is invoked, even though the registration went w/o problems.


Are there any issues when overriding both getRootConfigClasses() and getServletConfigClasses() ?


If i put the MyWebConfiguration class into getRootConfigClasses(), it will at least run those @bean methods.



public class AppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {

...
@Override
protected final Class<?>[] getRootConfigClasses() {
return new Class[]{CoreConfiguration.class, JpaConfiguration.class,
ShiroSecurityConfig.class};
}

@Override
protected final Class<?>[] getServletConfigClasses() {
return new Class[]{MyWebConfiguration.class};
}
}


Furthermore i have severe Problems using @Resource in@Configuration classes to obtain a bean from a different configuration class. But this is just a side issue i have at the moment.


The issue with @Bean methods which wont get fired is the most serious one. Thanks for any infos.


WARN PageNotFound:1120 - No mapping found for HTTP request with URI

I got a problem when developing spring project. I am getting warnings after returning from the controller. This is the configuration



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://ift.tt/ra1lAU"
xmlns="http://ift.tt/nSRXKP" xmlns:web="http://ift.tt/LU8AHS"
xsi:schemaLocation="http://ift.tt/nSRXKP http://ift.tt/1eWqHMP"
id="WebApp_ID" version="3.0">
<display-name>PolavaramWebApp</display-name>
<welcome-file-list>
<welcome-file>jsp/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>polavaram</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/polavaram-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>polavaram</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Default mapping for css and js and img folders -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/img/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/js/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/fonts/*</url-pattern>
</servlet-mapping>


From the index.jsp I am calling this controller



@Controller
@RequestMapping("/polavaram")
public class LoginController implements ServletContextAware {
private ServletContext servletContext;

@Override
public void setServletContext(ServletContext servletCtx) {
this.servletContext = servletCtx;

}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("loginpage");

}


This is my tiles configuration



<definition name="loginpage" extends="baseLayout">
<put-attribute name="title" value="Login Page" />
<put-attribute name="body" value="/jsp/loginpage.jsp" />
</definition>


This is the warning I am getting 00:16:04,849 WARN PageNotFound:1120 - No mapping found for HTTP request with URI [/PolavaramWebApp/polavaram/js/bootstrap.js] in DispatcherServlet with name 'polavaram'


I have this folder structure



webapp
css
jsp
js
img


There are some libraries in them. I am not able to access them in the loginpage.jsp



<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:ApplicationResources.properties</value>
<value>classpath:database.properties</value>
<value>classpath:dbqueries.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

<!-- <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/employee/*"
/> <mvc:mapping path="/course/*" /> <mvc:mapping path="/sessionplan/*" />
<mvc:mapping path="/registration/*" /> <mvc:mapping path="/tms/logout"/>
<mvc:mapping path="/faculty/*"/> <mvc:mapping path="/course/*"/> <bean class="in.walamtari.tms.interceptor.AuthenticationInterceptor"
/> </mvc:interceptor> </mvc:interceptors> -->

<context:annotation-config />
<context:component-scan
base-package="in.gov.polavaram.controller,in.gov.polavaram.manager,in.gov.polavaram.dao" />

<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>

<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>

<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">
<value>/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>


<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:ApplicationResources" />
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${psql.jdbc.driverClassName}" />
<property name="url" value="${psql.jdbc.url}" />
<property name="username" value="${psql.jdbc.username}" />
<property name="password" value="${psql.jdbc.password}" />
</bean>

<!-- <bean id="dataSource_hrms" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${psqlhrms.jdbc.driverClassName}"
/> <property name="url" value="${psqlhrms.jdbc.url}" /> <property name="username"
value="${psqlhrms.jdbc.username}" /> <property name="password" value="${psqlhrms.jdbc.password}"
/> </bean> -->

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- setting maximum upload size -->
<property name="maxUploadSize" value="5000000" />

</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<!-- <mvc:interceptors>
<bean class="in.gov.jalabharati.interceptor.AuthenticationInterceptor" />
</mvc:interceptors> -->
</beans>