FormatterLineAggregator in spring - spring

I am using FormatterLineAggregator. For eg:
<beans:property name="lineAggregator">
<beans:bean class="org.springframework.batch.item.file.transform.FormatterLineAggregator">
<beans:property name="fieldExtractor">
<beans:bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<beans:property name="names" value="desc1, desc2, desc3, desc4, desc5" />
</beans:bean>
</beans:property>
<beans:property name="format" value="%-4s%-9s%-30s%-30s%-30s" />
</beans:bean>
</beans:property>
The desc2 is of size 9. But I am getting a value of size 4 from database. So in the output file, spaces appear for the remaining 5 characters. I want to remove this space.Even if the size is 9 spaces should not follow desc1.

Related

I need to save the messaged in rabbit mq and delete it once my job is completed successfully

I need to save m messages in rabbit mq. I am using acknowledgeMode as MANUAL in SimpleMessageListenerContainer. This is helping me store the value in unacked in rabbit mq. But even after job completion the messages remain in the unacked. I need the messages to be deleted once job gets completed successfully. Please help me find a solution
<beans:bean id="PartitionHandler" class="org.springframework.batch.integration.partition.MessageChannelPartitionHandler" init-method="afterPropertiesSet" scope="job">
<beans:property name="messagingOperations" ref="messagingTemplate"></beans:property>
<beans:property name="stepName" value="slave" />
<beans:property name="gridSize" value="${spring.gridsize}" />
<beans:property name="pollInterval" value="5000"></beans:property>
<beans:property name="jobExplorer" ref="jobExplorer"></beans:property>
<beans:property name="replyChannel" ref="outboundReplies"></beans:property>
</beans:bean>
<beans:bean id="PeriodicTrigger" class="org.springframework.scheduling.support.PeriodicTrigger">
<beans:constructor-arg value="5000"></beans:constructor-arg>
</beans:bean>
<beans:bean id="requestQueue" class="org.springframework.amqp.core.Queue">
<beans:constructor-arg name="name" value="testQueue">
</beans:constructor-arg>
<beans:constructor-arg name="durable" value="true">
</beans:constructor-arg>
</beans:bean>
<int:poller id="PollerMetadata" default="true" trigger="PeriodicTrigger" task-executor="taskExecutor"></int:poller>
<beans:bean id="amqptemplate"
class="org.springframework.amqp.rabbit.core.RabbitTemplate">
<beans:property name="connectionFactory" ref="rabbitConnFactory" />
<beans:property name="routingKey" value="testQueue"/>
<beans:property name="queue" value="testQueue"/>
</beans:bean>
<beans:bean id="amqpOutboundEndpoint" class="org.springframework.integration.amqp.outbound.AmqpOutboundEndpoint">
<beans:constructor-arg ref="amqptemplate"/>
<beans:property name="expectReply" value="false"></beans:property>
<beans:property name="routingKey" value="testQueue"></beans:property>
<beans:property name="outputChannel" ref="inboundRequests"></beans:property>
</beans:bean>
<int:service-activator ref="amqpOutboundEndpoint" input-channel="outboundRequests"/>
<beans:bean id="SimpleMessageListenerContainer" class="org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer">
<beans:constructor-arg ref="rabbitConnFactory"/>
<beans:property name="queueNames" value="testQueue"></beans:property>
<beans:property name="autoStartup" value="false"></beans:property>
<beans:property name="acknowledgeMode" value="MANUAL"></beans:property>
<beans:property name="concurrentConsumers" value="5"></beans:property>
</beans:bean>
<beans:bean id="AmqpInboundChannelAdapter" class="org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter" init-method="afterPropertiesSet">
<beans:constructor-arg ref="SimpleMessageListenerContainer"/>
<beans:property name="outputChannel" ref="inboundRequests"></beans:property>
</beans:bean>
<beans:bean id="StepExecutionRequestHandler" class="org.springframework.batch.integration.partition.StepExecutionRequestHandler">
<beans:property name="jobExplorer" ref="jobExplorer"/>
<beans:property name="stepLocator" ref="stepLocator"/>
</beans:bean>
<int:service-activator ref="StepExecutionRequestHandler" input-channel="inboundRequests" output-channel="outboundStaging"/>
<bean id="rabbitConnFactory"
class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
<constructor-arg><value>localhost</value></constructor-arg>
<property name="username" value="guest" />
<property name="password" value="guest" />
<property name="virtualHost" value="/" />
<property name="port" value="5672" />
</bean>
<bean id="admin" class="org.springframework.amqp.rabbit.core.RabbitAdmin">
<constructor-arg ref="rabbitConnFactory" />
</bean>
<bean id="messagingTemplate"
class="org.springframework.integration.core.MessagingTemplate">
<constructor-arg ref="outboundRequests" />
<property name="receiveTimeout" value="60000000"/>
</bean>
<bean id="outboundRequests" class="org.springframework.integration.channel.DirectChannel" >
<property name="maxSubscribers" value="5"></property>
</bean>
<int:channel id="outboundReplies" scope="job"><int:queue/></int:channel>
<bean id="outboundStaging" class="org.springframework.integration.channel.NullChannel"></bean>
<bean id="inboundRequests" class="org.springframework.integration.channel.QueueChannel"></bean>
<bean id="stepLocator" class="org.springframework.batch.integration.partition.BeanFactoryStepLocator"/>
When using MANUAL acks, you are responsible for the acknowledgment.
See my answer to this question.

Spring + JPA LocalContainerEntityManagerFactoryBean. packagesToScan regex support?

I want configure my EntityManagerFactoryBean property "packagesToScan" to use a regex (like spring context component-scan does normally). But the most similar behavior that I can get is with an array of packages.
There are a version like this for use?
com.myproject.*.entity
this my EntityManagerFactoryBean config:
<beans:bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan">
<beans:array>
<beans:value>com.myproject.web.users.entity</beans:value>
</beans:array>
</beans:property>
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop><!-- https://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do -->
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</beans:prop>
</beans:props>
</beans:property>
</beans:bean>

How to implement two different spring security authentication from same login form

I have a requirement that on the login page I have a userId , password field and also another text entry field called customer. If a user logins in with userId and password , the spring-security configuration which I have works good.
Second login scenario is If the customer puts in only their customer Id , they are supposed to login to a different page as well. How do I make the two different logins works with the same spring-security xml configuration from the same login page.
<security:http auto-config="true" use-expressions="true" >
<!-- URL restrictions (order is important!) Most specific matches should be at top -->
<!-- Don't set any role restrictions on login.jsp. Any requests for the login page should be available for anonymous users -->
<security:intercept-url pattern="/login.jsp*" access="isAuthenticated()" />
<security:access-denied-handler error-page="/noaccess.jsp" />
<security:intercept-url pattern="/board.htm" access="hasRole('ROLE_ALL_USER')" />
<security:intercept-url pattern="/AddItems.htm*" access="hasRole('ROLE_USER')" />
<!-- Set the login page and what to do if login fails -->
<security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" />
<!-- Set the logout page and where to go after logout is successful -->
<security:logout logout-url="/logout" logout-success-url="/logoutSuccess.jsp" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="customPreAuthFilter" />
<security:custom-filter ref="switchUserFilter" position="SWITCH_USER_FILTER" />
</security:http>
<security:http>
</security:http>
<beans:bean id="customPreAuthFilter" class="org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
</beans:bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>
<!-- Load the UserDetails object for the user. -->
<beans:bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService">
<beans:bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:property name="userDetailsService" ref="currentUserDetailsService"/>
</beans:bean>
</beans:property>
</beans:bean>
<!-- Aliasing (Switch User) -->
<beans:bean id="switchUserFilter" class="org.springframework.security.web.authentication.switchuser.SwitchUserFilter">
<beans:property name="userDetailsService" ref="currentUserDetailsService" />
</beans:bean>
Thanks
Dhiren
#Ritesh Thanks for the link.. I tried your solution but My Filter does not get invoked.
does web.xml need to be modified.
Any way I tried to implement the entire springSecurityFilterChain but still I have not able to invoke my Filter from my login form. My filter that I need invoked is customBadgeAuthFilter
<beans:bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<beans:constructor-arg>
<beans:list>
<security:filter-chain pattern="/resources/**" filters="none"/>
<security:filter-chain pattern="/**"
filters="securityContextPersistenceFilterWithASCTrue,
logoutFilter,
customBadgeAuthFilter,
formLoginFilter,
formLoginExceptionTranslationFilter,
filterSecurityInterceptor" />
</beans:list>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="securityContextPersistenceFilterWithASCTrue"
class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
<beans:constructor-arg>
<beans:bean class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="formLoginExceptionTranslationFilter"
class="org.springframework.security.web.access.ExceptionTranslationFilter">
<beans:constructor-arg>
<beans:bean
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:constructor-arg value="/login"/>
</beans:bean>
</beans:constructor-arg>
<beans:property name="accessDeniedHandler">
<beans:bean
class="org.springframework.security.web.access.AccessDeniedHandlerImpl">
<beans:property name="errorPage" value="/exception" />
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="formLoginFilter"
class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="allowSessionCreation" value="true"/>
<beans:property name="authenticationSuccessHandler">
<beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
<beans:constructor-arg value="/"/>
<beans:property name="alwaysUseDefaultTargetUrl" value="true"/>
</beans:bean>
</beans:property>
<beans:property name="authenticationFailureHandler">
<beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<beans:constructor-arg value="/login?error=true"/>
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="filterSecurityInterceptor"
class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="accessDecisionManager" ref="accessDecisionManager" />
<beans:property name="runAsManager" ref="runAsManager" />
<beans:property name="securityMetadataSource">
<security:filter-security-metadata-source use-expressions="true">
<security:intercept-url pattern="/**"
access="isAuthenticated()" />
</security:filter-security-metadata-source>
</beans:property>
</beans:bean>
<beans:bean id="accessDecisionManager"
class="org.springframework.security.access.vote.AffirmativeBased">
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.access.vote.RoleVoter"/>
<beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter"/>
</beans:list>
</beans:constructor-arg>
<beans:property name="allowIfAllAbstainDecisions" value="false"/>
</beans:bean>
<beans:bean id="runAsManager"
class="org.springframework.security.access.intercept.RunAsManagerImpl">
<beans:property name="key" value="TELCO_RUN_AS"/>
</beans:bean>
<beans:bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<beans:constructor-arg value="/login"/>
<beans:constructor-arg>
<beans:list>
<beans:bean class="org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler">
<beans:constructor-arg>
<beans:list>
<beans:value>JSESSIONID</beans:value>
</beans:list>
</beans:constructor-arg>
</beans:bean>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</beans:list>
</beans:constructor-arg>
</beans:bean>
<beans:bean id="customBadgeAuthFilter" class="com.company.security.filter.BadgeProcessingSecurityFilter">
<beans:constructor-arg value="/login.jsp"></beans:constructor-arg>
<beans:property name="authenticationManager" ref="authManager" />
</beans:bean>
<security:authentication-manager alias="authManager" >
<security:authentication-provider ref='normalAuthenticationProvider ' />
<security:authentication-provider ref='badgeAuthenticationProvider ' />
<security:authentication-provider ref="preauthAuthProvider" />
</security:authentication-manager>
<beans:bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login.jsp"/>
</beans:bean>
<beans:bean id="badgeAuthenticationProvider" class="com.company.security.filter.BadgeAuthenticationProvider">
</beans:bean>
I think I finally figured how to get my securityFilter to get invoked.
I was doing debugging to see the springsecurity flow and see that there is a method called. requestAuthorization in the subclass of AbstractAuthenticationProcessingFilter. It compares the uri which is configured for the default value for the filter to get invoked and if they don't match the filter is bypassed. For some reason even thought the POSt request is /j_security_check .. it transforms into FSS/home.htm when it is being compared and so the filter was getting bypassed.

Why isn't hibernate creating my tables from hbm.xmls?

I have several .hbm.xml mapping files set up in Spring, and I can tell from the logs that Spring sees them and does something with them, but no tables are created in the DB.
Bean setup:
<beans:bean id="dataSourceEmbedded" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="org.h2.Driver" />
<beans:property name="url" value="jdbc:h2:~/myDbName" />
<beans:property name="username" value="sa" />
<beans:property name="password" value="" />
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSourceEmbedded">
<beans:property name="mappingLocations">
<beans:list>
<beans:value>classpath:path/to/schemas/Page.hbm.xml</beans:value>
<beans:value>classpath:path/to/schemas/Navigation.hbm.xml</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:value>
hibernate.show_sql=true
hibernate.dialect=${hibernate.dialect}
hibernate.hbmToDdlAuto=create
</beans:value>
</beans:property>
</beans:bean>
I know that the path to the Page and Navigation mapping files is correct - an error is thrown if it's not, and I can see the fields being mapped during the tomcat startup:
DEBUG: org.hibernate.cfg.Configuration - Processing hbm.xml files
INFO : org.hibernate.cfg.HbmBinder - Mapping class: Page -> pages
DEBUG: org.hibernate.cfg.HbmBinder - Mapped property: Page ID -> pageid
DEBUG: org.hibernate.cfg.HbmBinder - Mapped property: title -> title
Similarly, the database is clearly accessed / locked while tomcat is loading, so something is happening in there! But once it's loaded and I try to query it or inspect it, no tables exist.
Question: Why aren't my tables being created / what have I done wrong?
The property you used is wrong, it should be 'hibernate.hbm2ddl.auto' instead of 'hibernate.hbmToDdlAuto'... However instead of that you can also set the schemaUpdate property of the LocalSessionFactoryBean.
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSourceEmbedded">
<beans:property name="mappingLocations">
<beans:list>
<beans:value>classpath:path/to/schemas/Page.hbm.xml</beans:value>
<beans:value>classpath:path/to/schemas/Navigation.hbm.xml</beans:value>
</beans:list>
</beans:property>
<beans:property name="schemaUpdate" value="true" />
<beans:property name="hibernateProperties">
<beans:value>
hibernate.show_sql=true
hibernate.dialect=${hibernate.dialect}
</beans:value>
</beans:property>
</beans:bean>
Related answer/info: Hibernate hbm2ddl.auto possible values and what they do?
Correct property name is hibernate.hbm2ddl.auto

Spring security SessionRegistry and bean based configuration woes

I'm using Spring Security 3.0.5 and trying to get a count of currently logged in users. My scenario is Pre-Authenticated and using bean based configuration as opposed to <http> namespace based configuration (in which case this appears to be trivial.
My config file is as follows:
<beans:bean id="springSecurityFilterChain"
class="org.springframework.security.web.FilterChainProxy">
<filter-chain-map path-type="ant">
<filter-chain pattern="/**/resources/**" filters="none" />
<filter-chain pattern="/**/logout/**" filters="none" />
<filter-chain pattern="/service/**" filters="none" />
<filter-chain pattern="/**"
filters="sif,concurrencyFilter,shibbolethFilter,smf,logoutFilter,etf,fsi" />
</filter-chain-map>
</beans:bean>
<beans:bean id="sif"
class="org.springframework.security.web.context.SecurityContextPersistenceFilter" />
<beans:bean id="scr"
class="org.springframework.security.web.context.HttpSessionSecurityContextRepository" />
<beans:bean id="smf"
class="org.springframework.security.web.session.SessionManagementFilter">
<beans:constructor-arg name="securityContextRepository"
ref="scr" />
<beans:property name="sessionAuthenticationStrategy"
ref="sas" />
</beans:bean>
<beans:bean id="shibbolethFilter"
class="PreAuthenticatedShibbolethAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="exceptionIfHeaderMissing" value="true" />
<beans:property name="continueFilterChainOnUnsuccessfulAuthentication"
value="true" />
<beans:property name="developmentMode" value="true" />
<beans:property name="authenticationSuccessHandler"
ref="customAuthenticationSuccessHandlerBean" />
</beans:bean>
<beans:bean id="sas"
class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<beans:constructor-arg name="sessionRegistry"
ref="sessionRegistry" />
<beans:property name="maximumSessions" value="1" />
</beans:bean>
<beans:bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
<beans:bean id="concurrencyFilter"
class="org.springframework.security.web.session.ConcurrentSessionFilter">
<beans:property name="sessionRegistry" ref="sessionRegistry" />
<beans:property name="expiredUrl" value="/session-expired.html" />
</beans:bean>
<authentication-manager alias="authenticationManager">
<authentication-provider ref='preauthAuthProvider' />
</authentication-manager>
<beans:bean id="preauthAuthProvider"
class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<beans:property name="preAuthenticatedUserDetailsService">
<beans:bean id="userDetailsServiceWrapper"
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="logoutHandlerBean"
class="LogoutSuccessHandlerImpl" />
<beans:bean id="userDetailsService"
class="CustomJdbcDaoImpl">
<beans:property name="dataSource" ref="projectDS" />
<beans:property name="enableGroups" value="true" />
<beans:property name="enableAuthorities" value="false" />
</beans:bean>
In my controller I have the following code:
#Resource(name="sessionRegistry")
private SessionRegistry sessionReg;
private void doTest() {
List<Object> principals = sessionReg.getAllPrincipals();
for (Object o : principals) {
List<SessionInformation> siList = sessionReg.getAllSessions(o,
true);
for (SessionInformation si : siList) {
logger.error(si.getSessionId() + " " + si.getPrincipal());
}
}
}
The list principals is always empty. I feel the PreAuthenticatedShibbolethAuthenticationFilter filter which extends AbstractPreAuthenticatedProcessingFilter should get a ref to ConcurrentSessionControlStrategy, however, there is no such property which could be set.
What am I missing?
SecurityContextPersistenceFilter requires a SecurityContextRespository
<bean id="sif" class="org.springframework.security.web.context.SecurityContextPersistenceFilter" >
<property name="securityContextRepository" ref="scr" />
</bean>

Resources