Spring webflow using a lot of memory - memory

Our Webflow (2.3.1) application is claiming a lot of memory for each new flow that we open through the browser.
The screenshot below shows our application's memory use. When the application starts it takes an initial 400 Mb. After that we open 4 individual, identical Webflow TEST pages in the browser which each claim about 90Mb of extra memory..
Each test page is started from its own simple flow definition:
<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/webflow"
xsi:schemaLocation="http://www.springframework.org/schema/webflow
http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd" start-state="start">
<view-state id="start" view="test/test1">
</view-state>
<end-state id="end"/>
<bean-import resource="../flow-beans.xml"/>
</flow>
The JSP test pages are also very simple, just empty with one line of text.
When we currently set the JVM memory to 1.5Gb the application eventually crashes on the server with OutOfMemoryExceptions after opening about 15 different flows. 1.5 Gb seems a bit much, regarding the low complexity of our screens..
We are wondering if the amount of memory Webflow seems to claim for these simple flows/pages is expected and if we should therefore just assign more memory to the server JVM. If not, we would like to know how we can decrease this memory usage.
Below is our entire webflow configuration.
We have tried adding a flow-execution-repository tag and played around with the max-executions-snapshots and max-executions values, but even the most conservative settings don't change the memory usage we are seeing.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Launches new flow executions and resumes existing executions. -->
<webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
</webflow:flow-executor>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:our.properties" />
<property name="placeholderPrefix" value="$xxxx"></property>
</bean>
<tx:annotation-driven transaction-manager="$xxxx{txManager}" />
<!-- Creates the registry of flow definitions for this application -->
<webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
<webflow:flow-location-pattern value="classpath:flows/**/*-flow.xml" />
</webflow:flow-registry>
<bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="viewResolvers" ref="viewResolver" />
</bean>
<bean id="expressionParser" class="org.springframework.expression.spel.standard.SpelExpressionParser">
<constructor-arg name="configuration">
<bean class="org.springframework.expression.spel.SpelParserConfiguration">
<constructor-arg name="autoGrowCollections" value="true" />
<constructor-arg name="autoGrowNullReferences" value="false" />
</bean>
</constructor-arg>
</bean>
<bean id="webflowExpressionParser" class="org.springframework.webflow.expression.spel.WebFlowSpringELExpressionParser">
<constructor-arg name="expressionParser" ref="expressionParser" />
</bean>
<webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="viewFactoryCreator" validator="validator" expression-parser="webflowExpressionParser"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<bean id="projectVersion" class="our.company.versions.ProjectVersionUtil">
<property name="xxxxVersion" value="$xxxx{xxxx.version}" />
<property name="systemConfigurationDao">
<ref bean="SystemConfigurationDao"/>
</property>
</bean>
</beans>

When Spring Web Flow starts a new flow it basically constructs a new BeanFactory which loads the xml file and imports any additional xml files. The newly constructed BeanFactory has the context of the DispatcherServlet as its parent.
Now the problem with this is that a the bean factory constructs instances of all the beans even those defined in imported XML files.
<bean-import resource="../flow-beans.xml"/>
If there are a lot of beans in there those will be duplicated for each flow instance. In general you don't want your all of your beans duplicated and stored in the users sessions.
Remove the singleton beans from the flow-beans.xml and put them in the normal application context, they are still referable from within the flow definition. Or you could simply add the flow-beans.xml to the list of files loaded at startup of your application.

Related

Memory Histogram not showing on monitoring screen using JavaMelody 1.51

The memory histogram is not showing up on monitoring screen. I am using websphere 7.0
I am not sure whether my ear is getting monitored or not.
Below is my monitoring.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="facadeMonitoringAdvisor" class="net.bull.javamelody.MonitoringSpringAdvisor">
<property name="pointcut">
<bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value="com.x.y.*" />
</bean>
</property>
</bean>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
<bean id="springDataSourceBeanPostProcessor" class="net.bull.javamelody.SpringDataSourceBeanPostProcessor">
</bean>
</beans>
Why do we need these last 2 beans??? and how to see memory histogram??
There is no relation between spring configuration and heap histogram to see the number of instances per class in memory: you were on a false track.
But you probably use IBM J9 with Websphere. And the heap histogram feature is not supported in javamelody when using IBM J9.

Spring security authenticaton

I'm developing an application based on Spring and I'm using Spring Security 3.1.3.
Every time i try to authenticate, authentication doesn't succeed. Here is my security-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<security:http auto-config="true">
<security:form-login login-page="/app/main"
default-target-url="/app/account" />
<security:logout logout-url="/app/logout"
logout-success-url="/app/main" />
</security:http>
<bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt. BCryptPasswordEncoder" />
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider
user-service-ref="userService" >
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication .dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userService" />
<property name="hideUserNotFoundExceptions" value="false" />
</bean>
<bean id="authenticationManager"
class="org.springframework.security.authentication .ProviderManager">
<constructor-arg>
<ref local="daoAuthenticationProvider" />
</constructor-arg>
</bean>
</beans>
In my bean's password set method, i use BCryptPasswordEncoder like following:
public void setPassword(String password) {
PasswordEncoder passwordEncoder= new BCryptPasswordEncoder();
this.password=passwordEncoder.encode(password);
}
I store username and encoded password in db. I can authenticate just the first time after i sign up. Reason for that is that hibernate entity manager does automatic update of password value in database after selection. I don't know why!!! When i use plain text password, none of this is happening, everything works fine.
It's difficult to know for sure, since you haven't elaborated on what "my bean" is or where this setPassword function is used, but if it's part of a Hibernate entity, then it may be called with an already encoded password (e.g. when loading an entity from the database, not just when creating a new). You certainly wouldn't want to use bcrypt at that point. This might also explain why you can login the first time and sounds likely from your description of hibernate automatically updating the field.
For testing purposes, try adding an assertion that checks that the string doesn't begin with "$2a" (as a bcrypt string will), and throw an exception if it does.
If that's the case, make sure you call the encoder outside the entity when you create it, and pass in the encoded password to the setter.

Using Spring Security to manage iOS Homescreen web app sessions to prevent reauthn

I recently ran into an issue where I'm being reauthenticated every time I launch or bring my web app to the foreground when launching it from the homescreen on iOS (I added it to the homescreen from Safari originally). This does not happen when I'm in Safari directly.
My research has shown that this can be overcome in php by creating/restarting the session and then adding a session cookie as follows:
// Start or resume session
session_start();
// Extend cookie life time by an amount of your liking
$cookieLifetime = 365 * 24 * 60 * 60; // A year in seconds
setcookie(session_name(),session_id(),time()+$cookieLifetime);
Rather than do this programatically, I was wondering if there is a way to do this through the XML configuration. Otherwise, how could I accomplish something similar with Spring Security?
Here is my security-ctx.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint">
</bean>
<sec:http auto-config="false" entry-point-ref="http403EntryPoint">
<sec:custom-filter position="PRE_AUTH_FILTER" ref="siteminderFilter" />
</sec:http>
<bean id="siteminderFilter" class=
"org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<property name="principalRequestHeader" value="x-paas-uid"/>
<property name="authenticationManager" ref="authenticationManager"/>
</bean>
<bean id="preauthAuthProvider"
class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
<property name="preAuthenticatedUserDetailsService">
<bean id="userDetailsServiceWrapper"
class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
<property name="userDetailsService" ref="ldapUserDetailsService"/>
</bean>
</property>
</bean>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="preauthAuthProvider"/>
</sec:authentication-manager>
<!-- Example using LDAP, but will ultimately use database service -->
<sec:ldap-server id="ldapServer" port="636" root="o=home"
url="ldaps://ldap.home.com"/>
<sec:ldap-user-service id="ldapUserDetailsService" server-ref="ldapServer"
group-search-base="ou=groups,o=home"
role-prefix="ROLE_" group-role-attribute="cn"
user-search-base="ou=people,o=home" user-search-filter="uid={0}"/>
</beans>
As far as I know Spring Security does not manage session timeout value. So there is no way to do it in security xml out of the box. If you want to define this value system wide (for all sessions) then look into your servlet container / application server documentation. In a case of Tomcat you can add following snippet to the web.xml descriptor:
<web-app ....>
.....
<session-config>
<!-- value is in minutes -->
<!-- 60x24x365 -->
<session-timeout>525600</session-timeout>
</session-config>
....
</web-app>

Error registering camel's ftp jpa Idempotent repository

I'm trying to implement jpa idempotent repository just as described here http://camel.apache.org/file2.html, but i'm getting a Mbean export error.
On my application-context.xml i've the following section.
<bean id="mvStore" class="org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository" lazy-init="false">
<!-- Here we refer to the spring jpaTemplate -->
<constructor-arg index="0" ref="jpaTemplate" />
<!-- This 2nd parameter is the name (= a cateogry name). You can have different repositories with different names -->
<constructor-arg index="1" value="FileConsumer" />
</bean>
<context:mbean-server id="mbeanServer" />
<context:mbean-export server="mbeanServer" registration="replaceExisting" default-domain="br.com.touchtec"/>
If I remove the above section than the server (tomcat) starts just fine. Can anybody help me on this?
Here's the stack:
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository#6df960c4] with key 'mvStore'; nested exception is javax.management.MalformedObjectNameException: Key properties cannot be empty
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:602)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:527)
at org.springframework.jmx.export.MBeanExporter.afterPropertiesSet(MBeanExporter.java:413)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 50 more
Caused by: javax.management.MalformedObjectNameException: Key properties cannot be empty
at javax.management.ObjectName.construct(ObjectName.java:467)
at javax.management.ObjectName.<init>(ObjectName.java:1403)
at javax.management.ObjectName.getInstance(ObjectName.java:1285)
at org.springframework.jmx.support.ObjectNameManager.getInstance(ObjectNameManager.java:62)
at org.springframework.jmx.export.naming.MetadataNamingStrategy.getObjectName(MetadataNamingStrategy.java:114)
at org.springframework.jmx.export.MBeanExporter.getObjectName(MBeanExporter.java:728)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:631)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:592)
... 54 more
First of all, I hope you're clear on the fact the jmx part is not necessary to make the Idempotent Repository work. Your error is a pure JMX/Spring error, not linked to Camel.
If you want to use an MBeanExporter, you should read the official documentation on Spring JMX to have a better understaking of this matter.
Your MBeanExporter definition might look like
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="bean:name=mvStore" value-ref="mvStore"/>
</map>
</property>
<property name="server" ref="mbeanServer"/>
</bean>

Creating a custom authentication with Acegi/Spring Security

I'm having trouble discovering exactly what I need to implement in order to use a custom authentication method with my web application using Spring Security. I have a Grails application with the Spring Security plugin that currently uses the standard user/password authentication with a browser form. This is working correctly.
I need to implement a mechanism alongside of this that implements a type of MAC authentication. If the HTTP request contains several parameters (e.g. a user identifier, timestamp, signature, etc.) I need to take those parameters, perform some hashing and signature/timestamp comparisons, and then authenticate the user.
I'm not 100% sure where to start with this. What Spring Security classes do I need to extend/implement? I have read the Reference Documentation and have an okay understanding of the concepts, but am not really sure if I need a Filter or Provider or Manager, or where/how exactly to create Authentication objects. I've messed around trying to extend AbstractProcessingFilter and/or implement AuthenticationProvider, but I just get caught up understanding how I make them all play nicely.
Implement a custom AuthenticationProvider which gets all your authentication information from the Authentication: getCredentials(), getDetails(), and getPrincipal().
Tie it into your Spring Security authentication mechanism using the following configuration snippet:
<bean id="myAuthenticationProvider" class="com.example.MyAuthenticationProvider">
<security:custom-authentication-provider />
</bean>
This step is optional, if you can find a suitable one from standard implementations. If not, implement a class extending the Authentication interface on which you can put your authentication parameters:
(e.g. a user identifier, timestamp, signature, etc.)
Extend a custom SpringSecurityFilter which ties the above two classes together. For example, the Filter might get the AuthenticationManager and call authenticate() using your implementation of Authentication as input.
You can extend AbstractAuthenticationProcessingFilter as a start.
You can reference UsernamePasswordAuthenticationFilter which extends AbstractAuthenticationProcessingFilter. UsernamePasswordAuthenticationFilter implements the standard Username/Password Authentication.
Configure your Spring Security to add or replace the standard AUTHENTICATION_PROCESSING_FILTER. For Spring Security Filter orders, see http://static.springsource.org/spring-security/site/docs/3.0.x/reference/ns-config.html#filter-stack
Here is a configuration snippet for how to replace it with your implementation:
<beans:bean id="myFilter" class="com.example.MyAuthenticationFilter">
<custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/>
</beans:bean>
I have recently put up a sample application that does custom authentication with Spring Security 3.
The source code is here.
More details are in this blog post.
Here is an example of securityContext.xml configuration file using custom autenticationFilter (extending AUTHENTICATION_PROCESSING_FILTER) and authenticationProvider. The user authentication data is provided by jdbc connection. Configuration is for Spring Security 2.0.x
<?xml version="1.0" encoding="UTF-8"?>
<sec:global-method-security />
<sec:http auto-config="false" realm="CUSTOM" create-session="always" servlet-api-provision="true"
entry-point-ref="authenticationProcessingFilterEntryPoint" access-denied-page="/notauthorized.xhtml"
session-fixation-protection="migrateSession">
<sec:port-mappings>
<sec:port-mapping http="80" https="443" />
</sec:port-mappings>
<sec:anonymous granted-authority="ROLE_ANONYMOUS" username="Anonymous" />
<sec:intercept-url pattern="/**" access="ROLE_ANONYMOUS, ROLE_USER" />
<sec:logout logout-url="/logoff" logout-success-url="/home.xhtml" invalidate-session="false" />
</sec:http>
<bean id="authenticationProcessingFilterEntryPoint" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint">
<property name="loginFormUrl" value="/login.xhtml" />
<property name="forceHttps" value="false" />
</bean>
<bean id="authenticationProcessingFilter" class="mypackage.CustomAuthenticationProcessingFilter">
<sec:custom-filter position="AUTHENTICATION_PROCESSING_FILTER" />
<property name="defaultTargetUrl" value="/" />
<property name="filterProcessesUrl" value="/logon" />
<property name="authenticationFailureUrl" value="/loginError.xhtml" />
<property name="alwaysUseDefaultTargetUrl" value="false" />
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<jee:jndi-lookup id="securityDataSource" jndi-name="jdbc/DB_DS" />
<bean id="myUserDetailsService" class="mypackage.CustomJdbcDaoImpl">
<property name="dataSource" ref="securityDataSource" />
<property name="rolePrefix" value="ROLE_" />
</bean>
<bean id="apcAuthenticationProvider" class="mypackage.CustomDaoAuthenticationProvider">
<property name="userDetailsService" ref="myUserDetailsService" />
<sec:custom-authentication-provider />
</bean>
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref local="apcAuthenticationProvider" />
</list>
</property>
</bean>
</beans>

Resources