The Java serialization algorithm revealed


Serialization is the process of saving an object's state to a sequence of bytes; deserialization is the process of rebuilding those bytes into a live object. The Java Serialization API provides a standard mechanism for developers to handle object serialization. In this tip, you will see how to serialize an object, and why serialization is sometimes necessary. You'll learn about the serialization algorithm used in Java, and see an example that illustrates the serialized format of an object. By the time you're done, you should have a solid knowledge of how the serialization algorithm works and what entities are serialized as part of the object at a low level.

Why is serialization required?

In today's world, a typical enterprise application will have multiple components and will be distributed across various systems and networks. In Java, everything is represented as objects; if two Java components want to communicate with each other, there needs be a mechanism to exchange data. One way to achieve this is to define your own protocol and transfer an object. This means that the receiving end must know the protocol used by the sender to re-create the object, which would make it very difficult to talk to third-party components. Hence, there needs to be a generic and efficient protocol to transfer the object between components. Serialization is defined for this purpose, and Java components use this protocol to transfer objects.
Figure 1 shows a high-level view of client/server communication, where an object is transferred from the client to the server through serialization.
A high-level view of serialization in action

Figure 1. A high-level view of serialization in action (click to enlarge)

How to serialize an object

In order to serialize an object, you need to ensure that the class of the object implements the java.io.Serializable interface, as shown in Listing 1.

Listing 1. Implementing Serializable

import java.io.Serializable; class TestSerial implements Serializable { public byte version = 100; public byte count = 0; }
In Listing 1, the only thing you had to do differently from creating a normal class is implement the java.io.Serializable interface. The Serializable interface is a marker interface; it declares no methods at all. It tells the serialization mechanism that the class can be serialized.
Now that you have made the class eligible for serialization, the next step is to actually serialize the object. That is done by calling the writeObject() method of the java.io.ObjectOutputStream class, as shown in Listing 2.

Listing 2. Calling writeObject()

public static void main(String args[]) throws IOException { FileOutputStream fos = new FileOutputStream("temp.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); TestSerial ts = new TestSerial(); oos.writeObject(ts); oos.flush(); oos.close(); }
Listing 2 stores the state of the TestSerial object in a file called temp.out. oos.writeObject(ts); actually kicks off the serialization algorithm, which in turn writes the object to temp.out.
To re-create the object from the persistent file, you would employ the code in Listing 3.

Listing 3. Recreating a serialized object

public static void main(String args[]) throws IOException { FileInputStream fis = new FileInputStream("temp.out"); ObjectInputStream oin = new ObjectInputStream(fis); TestSerial ts = (TestSerial) oin.readObject(); System.out.println("version="+ts.version); }
In Listing 3, the object's restoration occurs with the oin.readObject() method call. This method call reads in the raw bytes that we previously persisted and creates a live object that is an exact replica of the original object graph. Because readObject() can read any serializable object, a cast to the correct type is required.
Executing this code will print version=100 on the standard output.

The serialized format of an object

What does the serialized version of the object look like? Remember, the sample code in the previous section saved the serialized version of the TestSerial object into the file temp.out. Listing 4 shows the contents of temp.out, displayed in hexadecimal. (You need a hexadecimal editor to see the output in hexadecimal format.)

Listing 4. Hexadecimal form of TestSerial

AC ED 00 05 73 72 00 0A 53 65 72 69 61 6C 54 65 73 74 A0 0C 34 00 FE B1 DD F9 02 00 02 42 00 05 63 6F 75 6E 74 42 00 07 76 65 72 73 69 6F 6E 78 70 00 64
If you look again at the actual TestSerial object, you'll see that it has only two byte members, as shown in Listing 5.

Listing 5. TestSerial's byte members

public byte version = 100; public byte count = 0;
The size of a byte variable is one byte, and hence the total size of the object (without the header) is two bytes. But if you look at the size of the serialized object in Listing 4, you'll see 51 bytes. Surprise! Where did the extra bytes come from, and what is their significance? They are introduced by the serialization algorithm, and are required in order to to re-create the object. In the next section, you'll explore this algorithm in detail.

Java's serialization algorithm

By now, you should have a pretty good knowledge of how to serialize an object. But how does the process work under the hood? In general the serialization algorithm does the following:
  • It writes out the metadata of the class associated with an instance.
  • It recursively writes out the description of the superclass until it finds java.lang.object.
  • Once it finishes writing the metadata information, it then starts with the actual data associated with the instance. But this time, it starts from the topmost superclass.
  • It recursively writes the data associated with the instance, starting from the least superclass to the most-derived class.
I've written a different example object for this section that will cover all possible cases. The new sample object to be serialized is shown in Listing 6.

Listing 6. Sample serialized object

class parent implements Serializable { int parentVersion = 10; } class contain implements Serializable{ int containVersion = 11; } public class SerialTest extends parent implements Serializable { int version = 66; contain con = new contain(); public int getVersion() { return version; } public static void main(String args[]) throws IOException { FileOutputStream fos = new FileOutputStream("temp.out"); ObjectOutputStream oos = new ObjectOutputStream(fos); SerialTest st = new SerialTest(); oos.writeObject(st); oos.flush(); oos.close(); } }
This example is a straightforward one. It serializes an object of type SerialTest, which is derived from parent and has a container object, contain. The serialized format of this object is shown in Listing 7.

Listing 7. Serialized form of sample object

AC ED 00 05 73 72 00 0A 53 65 72 69 61 6C 54 65 73 74 05 52 81 5A AC 66 02 F6 02 00 02 49 00 07 76 65 72 73 69 6F 6E 4C 00 03 63 6F 6E 74 00 09 4C 63 6F 6E 74 61 69 6E 3B 78 72 00 06 70 61 72 65 6E 74 0E DB D2 BD 85 EE 63 7A 02 00 01 49 00 0D 70 61 72 65 6E 74 56 65 72 73 69 6F 6E 78 70 00 00 00 0A 00 00 00 42 73 72 00 07 63 6F 6E 74 61 69 6E FC BB E6 0E FB CB 60 C7 02 00 01 49 00 0E 63 6F 6E 74 61 69 6E 56 65 72 73 69 6F 6E 78 70 00 00 00 0B
Figure 2 offers a high-level look at the serialization algorithm for this scenario.
An outline of the serialization algorithm

Figure 2. An outline of the serialization algorithm

Let's go through the serialized format of the object in detail and see what each byte represents. Begin with the serialization protocol information:
  • AC ED: STREAM_MAGIC. Specifies that this is a serialization protocol.
  • 00 05: STREAM_VERSION. The serialization version.
  • 0x73: TC_OBJECT. Specifies that this is a new Object.
The first step of the serialization algorithm is to write the description of the class associated with an instance. The example serializes an object of type SerialTest, so the algorithm starts by writing the description of the SerialTest class.
  • 0x72: TC_CLASSDESC. Specifies that this is a new class.
  • 00 0A: Length of the class name.
  • 53 65 72 69 61 6c 54 65 73 74: SerialTest, the name of the class.
  • 05 52 81 5A AC 66 02 F6: SerialVersionUID, the serial version identifier of this class.
  • 0x02: Various flags. This particular flag says that the object supports serialization.
  • 00 02: Number of fields in this class.
Next, the algorithm writes the field int version = 66;.
  • 0x49: Field type code. 49 represents "I", which stands for Int.
  • 00 07: Length of the field name.
  • 76 65 72 73 69 6F 6E: version, the name of the field.
And then the algorithm writes the next field, contain con = new contain();. This is an object, so it will write the canonical JVM signature of this field.
  • 0x74: TC_STRING. Represents a new string.
  • 00 09: Length of the string.
  • 4C 63 6F 6E 74 61 69 6E 3B: Lcontain;, the canonical JVM signature.
  • 0x78: TC_ENDBLOCKDATA, the end of the optional block data for an object.
The next step of the algorithm is to write the description of the parent class, which is the immediate superclass of SerialTest.
  • 0x72: TC_CLASSDESC. Specifies that this is a new class.
  • 00 06: Length of the class name.
  • 70 61 72 65 6E 74: SerialTest, the name of the class
  • 0E DB D2 BD 85 EE 63 7A: SerialVersionUID, the serial version identifier of this class.
  • 0x02: Various flags. This flag notes that the object supports serialization.
  • 00 01: Number of fields in this class.
Now the algorithm will write the field description for the parent class. parent has one field, int parentVersion = 100;.
  • 0x49: Field type code. 49 represents "I", which stands for Int.
  • 00 0D: Length of the field name.
  • 70 61 72 65 6E 74 56 65 72 73 69 6F 6E: parentVersion, the name of the field.
  • 0x78: TC_ENDBLOCKDATA, the end of block data for this object.
  • 0x70: TC_NULL, which represents the fact that there are no more superclasses because we have reached the top of the class hierarchy.
So far, the serialization algorithm has written the description of the class associated with the instance and all its superclasses. Next, it will write the actual data associated with the instance. It writes the parent class members first:
  • 00 00 00 0A: 10, the value of parentVersion.
Then it moves on to SerialTest.
  • 00 00 00 42: 66, the value of version.
The next few bytes are interesting. The algorithm needs to write the information about the contain object, shown in Listing 8.

Listing 8. The contain object

contain con = new contain();
Remember, the serialization algorithm hasn't written the class description for the contain class yet. This is the opportunity to write this description.
  • 0x73: TC_OBJECT, designating a new object.
  • 0x72: TC_CLASSDESC.
  • 00 07: Length of the class name.
  • 63 6F 6E 74 61 69 6E: contain, the name of the class.
  • FC BB E6 0E FB CB 60 C7: SerialVersionUID, the serial version identifier of this class.
  • 0x02: Various flags. This flag indicates that this class supports serialization.
  • 00 01: Number of fields in this class.
Next, the algorithm must write the description for contain's only field, int containVersion = 11;.
  • 0x49: Field type code. 49 represents "I", which stands for Int.
  • 00 0E: Length of the field name.
  • 63 6F 6E 74 61 69 6E 56 65 72 73 69 6F 6E: containVersion, the name of the field.
  • 0x78: TC_ENDBLOCKDATA.
Next, the serialization algorithm checks to see if contain has any parent classes. If it did, the algorithm would start writing that class; but in this case there is no superclass for contain, so the algorithm writes TC_NULL.
  • 0x70: TC_NULL.
Finally, the algorithm writes the actual data associated with contain.
  • 00 00 00 0B: 11, the value of containVersion.

Conclusion

In this tip, you have seen how to serialize an object, and learned how the serialization algorithm works in detail. I hope this article gives you more detail on what happens when you actually serialize an object.

Spring Acegi Security Framework

The Authentication object

The Authentication object is pivotal to the Acegi framework. Since "security" basically means "restricted access for specific roles" the framework has to be able to determine, at any time, the roles given to the authenticated user. The framework stores this info in the "Authentication" object, which contains the username, password and the roles granted to the user.

The Authentication object is created and validated by the by the AuthenticationManager. Access to resources is controlled by the AccessDecisionManager.

Filters ^

Acegi uses a chain of (at least) three filters to enable webapplication security:

1.The AuthenticationProcessingFilter handles the Authentication Request Check ("logging into the application"). It uses the AuthenticationManager to do its work.

2. The HttpSessionContextIntegrationFilter maintains the Authentication object between various requests and passes it around to the AuthenticationManager and the AccessDecisionManager when needed;

3. The ExceptonTranslationFilter performs the Existing Authentication Check, handles security exceptions and takes the appropriate action. This action can be either spawning the authentication dialog (a.k.a. the login form) or returning the appropriate HTTP security error code. ExceptonTranslationFilter depends on the next filter, FilterSecurityInterceptor, to do its work.

4. FilterSecurityInterceptor manages the Restricted Acces Check,and the Authorisation check. It knows which resources are secure and which roles have access to them. FilterSecurityInterceptor uses the AuthenticationManager and AccessDecisionManager to do its work.

In good Spring and Dependency Injection fashion, the classes described above do not do their work alone and serve mainly as proxies who delegate the hard work to other classes. I will describe those classes in more detail while laying out the configuration file later on.

Configuration

Since Acegi depends on the Spring framework, all configuration is done through "wiring". Without going into too much detail, "wiring" means associating JavaBeans with each other via a XML configuration file. The three filters mentioned in the previous paragraph need all their dependent objects "wired" into them. We will get to the XML configuration in a moment, but first it might be a good idea to graphically outline the dependencies between the three filters and the various "utility objects" they use.

The Filter Chain

As you saw in the graph in paragraph 5.2, the three filters form a chain through which every HTTP request passes. Together, the three filters perform the task of securing the application. The three filters are "chained" together by an object called the "filterChainProxy", which in turn creates and starts the three filters. See the diagram below:

In good Spring fashion, the three filters are started by yet another object, the "FilterChainProxy". This proxy is configured in the configuration XML file and any additional filters (we will come to some of them later on) will be added to the "FilterChainProxy" configuration list.

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor
    </value>
 </property>
</bean>

The above configuration states the filter beans which will be started by the proxy. The configuration of those filter beans will be discussed below.

The AuthenticationProcessingFilter

The first filter through which the HTTP request will pass is the formAuthenticationProcessingFilter bean. This filter specializes in handling authentication request, i.e. The validation of username/password combinations. Let's take a look at the configuration XML:

<bean id="formAuthenticationProcessingFilter"
        class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
    <property name="filterProcessesUrl">
        <value>/j_acegi_security_check</value>
    </property>
    <property name="authenticationFailureUrl">
        <value>/loginFailed.html</value>
    </property>
    <property name="defaultTargetUrl">
        <value>/</value>
    </property>
    <property name="authenticationManager">
        <ref bean="authenticationManager" />
    </property>
</bean>

The filter bean is of type org.acegisecurity.ui.webapp.AuthenticationProcessingFilter. This filter class is specifically used for Form logins, which is why the form-submit URL ("filterProcessUrl"), the login-failed page ("authenticationFailureUrl") are configured with this bean. In case you are wondering where the login page itself is configured: with the security realm, which we will get to later on. Remember that the AuthenticationProcessingFilter specialised in handling authentication requests. Spawning a login dialog is enables a user to log in, but has nothing to do with actually validating the provided username/password combination and is therefore not configured in this filter.

For clarity, here's a diagram of AuthenticationProcessingFilter and its dependencies:


The HttpSessionContextIntegrationFilter

The work of the HttpSessionContextIntegrationFilter is very specialized and therefor very easy to configure. The only thing this filter does, is propagating the established authentication object through all requests. The filter wraps the authentication object a ThreadLocal and hands that wrapper over to the other filters in the chain. Here is the configuration XML:

<bean id="httpSessionContextIntegrationFilter"
  class="org.acegisecurity.context.HttpSessionContextIntegrationFilter">
</bean>

Below is a (perhaps unnecessary?) diagram of HttpSessionContextIntegrationFilter and its dependencies:


The ExceptionTranslationFilter

The ExceptionTranslationFilter is the one of the two"pivotal" filters in the security system (the other being FilterSecurityInterceptor). In short, ExceptionTranslationFilter catches any authentication or authorization error (in the form of an AcegiSecurityException) and may do one of the following two things.

If the exception was caused by the absence of an Authentication object (i.e. the user has not logged in yet), it spawns the configured AuthenticationEntryPoint to prompt the user for login (more on AuthenticationEntryPoint later).

If the exception was caused by an authorization exception thrown by FilterSecurityInterceptor (i.e. the user is logged in but is not authorized for the resource requested), ExceptionTranslationFilter will send an SC_FORBIDDEN (HTTP 403) error to the browser, which will display it’s built-in version of an ‘unauthorized access’ page.

That sounds like quite the story, does it not? Nonetheless, the XML configuration for ExceptionTranslationFilter is rather simple:

<bean id="exceptionTranslationFilter"
        class="org.acegisecurity.ui.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint">
        <ref bean="formLoginAuthenticationEntryPoint" />
    </property>
</bean>

The filter leaves all the hard work to it's collaborators: FilterSecurityInterceptor (to which it is linked through the filter chain) and authenticationEntryPoint. Before we examine those two in more detail, it will definitely be useful to take a look at the following diagram, which shows the two filters and their dependencies:


FilterSecurityInterceptor

FilterSecurityInterceptor contains the definitions of the secured resources. Let's take a look at the XML configuration first:

<bean id="filterSecurityInterceptor"
        class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
    <property name="authenticationManager">
        <ref bean="authenticationManager" />
    </property>
    <property name="accessDecisionManager">
        <ref bean="accessDecisionManager" />
    </property>
    <property name="objectDefinitionSource">
        <value>
            CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
            PATTERN_TYPE_APACHE_ANT
            /secure/admin/*=ROLE_ADMIN
            /secure/app/*=ROLE_USER
        </value>
    </property>
</bean>

You see two bean references here, "authenticationManager" and "accessDecisionManager". We will get to those in a moment, first let's take a look at the property "objectDefinitionSource". In Acegi security, "secured resources" are called "object definitions" (it is a rather generic sounding name because Acegi can be also used to control access to method invocations and object creations, not just web applications). The thing to remember here is that "objectDefinitionSource" should contain some directives and the URL patterns to be secured, along with the roles who have access to those URL patterns.

There are two directives here:

    * CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON tells the Acegi framework to convert the request URL to lowercase, so that the security mechanism cannot be surpassed by simply entering a slightly different URL in the browser;
    * PATTERN_TYPE_APACHE_ANT makes it easier to define the URL patterns to be secured (there is also a different notation style, which looks more like regular expressions and less like the standard J2EE notation so I will not go into that here, mainly because I do not really understand that notation myself ;-) ).

And there are two URL patterns defined here, which are the two main URLs used in the example webapplication.

AuthenticationManager

Here is the configuration XML for AuthenticationManager and it's dependents:

 <bean id="authenticationManager"
        class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref bean="daoAuthenticationProvider" />
        </list>
    </property>
</bean>
<bean id="daoAuthenticationProvider"
        class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
    <property name="authenticationDao">
        <ref bean="authenticationDao" />
    </property>
</bean>
<bean id="authenticationDao"
        class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">
    <property name="userMap">
        <value>
            jklaassen=4moreyears,ROLE_ADMIN
            bouerj=ineedsleep,ROLE_USER
        </value>
    </property>
</bean>

The AuthenticationManager is of type ProviderManager, which means that it forms a proxy to the AuthenticationProvider. In Acegi, an AuthenticationProvider validates the inputted username/password combination and extracts the role(s) appointed to that user. AuthenticationProvider is itself a proxy to an AuthenticationDao, which is basically an registry containing usernames, passwords and roles. There a several types of AuthenticationDao (inmemory, database via JDBC or even LDAP), but for simplicity the standard InMemoryDaoImpl type is used. In the Dao, two users have been defined (jklaassen and bouerj), each with a different role.

AccessDecisionManager

Validating the correctness of the username/password combination and the retrieval of associated roles is one thing, deciding whether to grant access is another. In other words: once a user has been authenticated, he must also be authorized. This decision is the responsibilty of the AccessDecisionManager. The AccessDecisionManager takes the available user information and decides to grant access (or not, of course). The AccessDecisionManager uses a Voter to determine if the user will be authorized. Below is the configuration XML:

<bean id="accessDecisionManager"
        class="org.acegisecurity.vote.UnanimousBased">
    <property name="decisionVoters">
        <list>
            <ref bean="roleVoter" />
        </list>
    </property>
</bean>
<bean id="roleVoter" class="org.acegisecurity.vote.RoleVoter">
    <property name="rolePrefix">
        <value>ROLE_</value>
    </property>
</bean>

The above configuration is usually sufficient for webapplications, so we will leave it at that. Note though, that you will have to specify which rolenames should be handled by a specific voter by specifying the role prefix.

Note also that it is possible to wire multiple voters into one AccessDecisionManager and that multiple ProviderManagers can be wired to an AuthenticationManager. So it is possible to let Acegi consult several different username/password registries available (say a mixture of LDAP, Database and NT Domain registries), with many different rolenames configured and voted on by several Voters. I admit that elaborate scenario to be a bit far fetched and certainly far too complex for one webapplication, but in huge enterprise systems such (legacy) complextity may very well exist.

AuthenticationEntryPoint

Now only one configuration item needs to be specified: the AuthenticationEntryPoint, which is the starting point of the authentication dialog. If the FilterSecurityInterceptor determines that there is no available authentication object present, the SecurityEnforcementFilter will pass control to the AuthenticationEntryPoint. Here is the configuration XML:

<bean id="formLoginAuthenticationEntryPoint"
    class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl">
        <value>/login.jsp</value>
    </property>
    <property name="forceHttps">
        <value>false</value>
    </property>
</bean>

The AuthenticationEntryPoint in this example is of type AuthenticationProcessingFilterEntryPoint, which is specifically suitable for FORM login dialogs. Configuration is fairly straightforward, only the URL of the login form to spawn needs to be specified. An optional parameter "forceHttps", may be set to "true" if you would like the username/password data to be sent as encrypted data.

Using an authentication database through JDBC

The above example uses the InMemoryDaoImpl as the AuthenticationDAO, to store usernames, passwords and roles. That's fine for simple testing purposes, but in the real world a user registry is usually a database. So here's some configuration for using the JdbcDaoImpl class of Acegi:

<bean id="userDetailsService"
        class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl">
    <property name="dataSource">
        <ref bean="dataSource"/>
    </property>
</bean>

That's all. The dataSource configuration is standard Spring:

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
        <value>jdbc:mysql://localhost:3306/springweb_auth_db</value>
    </property>
    <property name="username">
        <value>j2ee</value>
    </property>
    <property name="password">
        <value>password</value>
    </property>
</bean>

Now all you need is the database specification: the tables. There are two ways to go here. The hard way involves using custom tables and thus specifying custom queries and rowmappers for the AuthenticationDao. This is beyond the scope of this tutorial. The documentation included in the full Acegi framework download contains more information on using a user database.

The easy way is to create a database tailored to Acegi's wishes, which would mean the following schema:

The "ENABLED" column could also be a CHAR or VARCHAR holding the values "true" and "false". Obviously, the AUTHORITY column would hold the role names. Populate the database and you are all set!

Using custom authentication provider

The above example uses the JdbcDaoImpl as the AuthenticationDAO, to store usernames, passwords and roles into a database. But if you don't want Acegi to access directly to the database you can configure a custom authentication as a Java bean. So here's some configuration for using a custom authentication:

First you declare your bean:

<bean id="customAuthenticationDao"
        class="test.mypackage.mydao.security.CustomAuthenticationDAO" />

Here is the new configuration XML for AuthenticationManager and it's dependents:

 <bean id="authenticationManager"
        class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref bean="daoAuthenticationProvider" />
        </list>
    </property>
</bean>
<bean id="daoAuthenticationProvider"
        class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
    <property name="authenticationDao">
        <ref bean="customAuthenticationDao" />
    </property>
</bean>

And finally your Java code will look like this:

 public class CustomAuthenticationDAO implements UserDetailsService {

    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException, DataAccessException {


    //This method loads the user by username from the DB   
    final User user = AccountFacade.loadUserByUsername(userName);
    if (user == null)
        throw new UsernameNotFoundException("The user name was not found");
    return new UserDetails() {

     private static final long serialVersionUID = -2868501916277412090L;

        public GrantedAuthority[] getAuthorities() {
            return new GrantedAuthority[] { new GrantedAuthority() {

                public String getAuthority() {
                    if (user.isSystemAdmin())
                        return "ROLE_ADMIN";
                    else if (user.isAccountAdmin())
                        return "ROLE_ACCOUNTADMIN";
                    else
                        return "ROLE_USER";
                }
            } };
        }

        public String getPassword() {
            return user.getPassword();
        }

        public String getUsername() {
            return user.getUsername();
        }

        public boolean isAccountNonExpired() {
            return true;
        }

        public boolean isAccountNonLocked() {
            return true;
        }

        public boolean isCredentialsNonExpired() {
            return true;
        }

        public boolean isEnabled() {
            return user.isActivated();
        }
    };
}
}


Logout Filter

Add logout functionallity is really simple. You only have to configure one filter. The filter bean is of type org.acegisecurity.ui.logout.LogoutFilter. In this example it will process the logout.jsp url and it will return to index.jsp.

<bean id="logoutFilter"
        class="org.acegisecurity.ui.logout.LogoutFilter">
 <constructor-arg value="/index.jsp" />
 <constructor-arg>
   <list>
     <bean class="org.acegisecurity.ui.logout.SecurityContextLogoutHandler" />
     </list>
 </constructor-arg>
   <property name="filterProcessesUrl">
     <value>/logout.jsp</value>
     </property>
</bean>

And don't forget to add LogoutFilter to the filter chain:

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor,logoutFilter
    </value>
 </property>
</bean>


RememberMe Filter

Now you can add Remember Me functionallity. This part is not as simple than Logout. The main filter you have to configure is RememberMeProcessingFilter. The XML configuration will look like this:

<bean id="rememberMeProcessingFilter"
    class="org.acegisecurity.ui.rememberme.RememberMeProcessingFilter">
    <property name="rememberMeServices">
        <ref local="rememberMeServices" />
    </property>
    <property name="authenticationManager">
        ref="authenticationManager" />
    </property>
</bean>
<bean id="rememberMeServices"
    class="org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices">
    <property name="userDetailsService">
        <ref local="customAuthenticationDao" />
    </property>
    <property name="key" value="myKey" />
    <property name="parameter" value="rememberMe" />
</bean>
<bean id="rememberMeAuthenticationProvider"
class="org.acegisecurity.providers.rememberme.RememberMeAuthenticationProvider">
    <property name="key">
        <value>myKey</value>
    </property>
</bean>

Also you have to add a reference in your AuthenticationProcessingFilterEntryPoint defined above:

<bean id="formLoginAuthenticationEntryPoint"
    class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl">
        <value>/login.jsp</value>
    </property>

    <property name="rememberMeServices">
        <ref bean="rememberMeServices" />
    </property>
</bean>

And don't forget to add RememberMeProcessingFilter to the filter chain:

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor,logoutFilter,
    rememberMeProcessingFilter
    </value>
 </property>
</bean>


ChannelProcessingFilter (SSL)

Add secure login functionallity is really simple too. You have to configure two beans: ChannelProcessingFilter and ChannelDecisionManager. In the first filter you have to configure which resources will require secure channel. In the second bean you need to specify two references (SecureChannelProcessor and InsecureChannelProcessor). Here is the XML configuration:

<bean id="channelProcessingFilter"
    class="org.acegisecurity.securechannel.ChannelProcessingFilter" >
    <property name="channelDecisionManager" ref="channelDecisionManager"/>
    <property name="filterInvocationDefinitionSource">
        <value>
        PATTERN_TYPE_APACHE_ANT
        /login.jsp=REQUIRES_SECURE_CHANNEL
        /**=REQUIRES_INSECURE_CHANNEL
      </value>
  </property>
<bean id="channelDecisionManager"
    class="org.acegisecurity.securechannel.ChannelDecisionManagerImpl">
    <property name="channelProcessors">
        <list>
        <bean class="org.acegisecurity.securechannel.SecureChannelProcessor"/>
        <bean class="org.acegisecurity.securechannel.InsecureChannelProcessor"/>
      </list>
  </property>
</bean>

AGAIN: Don't forget to add ChannelProcessingFilter to the filter chain:

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
 <property name="filterInvocationDefinitionSource">
    <value>
    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
    PATTERN_TYPE_APACHE_ANT
    /**=httpSessionContextIntegrationFilter,formAuthenticationProcessingFilter,
    exceptionTranslationFilter,filterSecurityInterceptor,logoutFilter,
    rememberMeProcessingFilter,channelProcessingFilter
    </value>
 </property>
</bean>

And also you have to change to TRUE the forceHttps property defined above:

<bean id="formLoginAuthenticationEntryPoint"
    class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
    <property name="loginFormUrl">
        <value>/login.jsp</value>
    </property>
    <property name="forceHttps">
        <value>true</value>
    </property>
</bean>

And finally you will need to install your certificates and configure your application server. If you are using Apache Tomcat you can read about it at:

http://tomcat.apache.org/tomcat-5.5-doc/ssl-howto.html

JBOSS EJB WEB SERVICES Example

Employee Service.java
---------------------------------
package com.crm.services;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import com.crm.bean.Employee;
/**
* @author AnilKumar
*
*/
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface EmployeeService {
public Employee getEmployee(long pin);
}

EmployeeServiceImpl.java
-------------------------------------
package com.crm.services;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

import com.crm.bean.Employee;
import com.crm.model.EmployeeDAO;
import com.crm.modelinterface.cmsEmployee;
/**
* @author AnilKumar
*
*/
@Stateless
@WebService(endpointInterface = "com.crm.services.EmployeeService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class EmployeeServiceImpl {

@WebMethod(operationName = "getEmployee")
public Employee getEmployee(@WebParam(name = "pin")
long pin) {
cmsEmployee employee2 = new EmployeeDAO();
// Employee employee2 = employeeDAO.getEmployeebyemployee(pin);

Employee employee = employee2.getEmployeebyemployee(pin);

System.out.println(employee.getFirstname());
return employee;
}

}

deploy above two classes by archieving in a jar and copy it to deploy folder of jboss
then run ur jboss server with url http://localhost:8080/jbossws there u will get all ur
web services running in your server

the client program will be like this

package com.crm.serviceClient;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;

import com.crm.bean.Employee;
import com.crm.services.EmployeeService;
/**
* @author AnilKumar
*
*/
@WebServiceClient(name = "EmployeeServiceImplService", targetNamespace = "http://services.crm.com/",
wsdlLocation = "http://localhost:8080/jarfilename/EmployeeServiceImpl?wsdl")
public class EmployeeServiceClient extends Service {
protected EmployeeServiceClient(URL wsdlDocumentLocation,
QName serviceName) {
super(wsdlDocumentLocation, serviceName);
// TODO Auto-generated constructor stub
}

public EmployeeServiceClient() throws MalformedURLException {
super(new URL(
"http://localhost:8080/jarfilename/EmployeeServiceImpl?wsdl"),
new QName("http://services.crm.com/",
"EmployeeServiceImplService"));
}

@WebEndpoint
public EmployeeService getEmployeeServiceport() {
return (EmployeeService) super.getPort(new QName(
"http://services.crm.com/", "EmployeeServiceImplPort"),
EmployeeService.class);

}

public static void main(String[] args) throws MalformedURLException {

try {
EmployeeService service = new EmployeeServiceClient().getEmployeeServiceport();

if (service != null) {
System.out.println("Serrvice not null");
Employee employee1 = service.getEmployee(18);

System.out.println(employee1.getFirstname());
System.out.println(employee1.getLastname());
}

} catch (Exception e) {
e.printStackTrace();
}

}

}

How to Improve Your Memory & Exercise Your Brain

How to Improve Your Memory & Exercise Your Brain
Everyone can take steps to improve their memory, with time and practice most people can gain the ability to memorize seemingly impossible amounts of information. Whether you want to win the World Memory Championships, ace your history test, or simply remember where you put your keys, this article can get you started. Scientists believe that exercising your brain can create a `cognitive reserve' that will help you stay sharp as you age.

1. Convince yourself that you do have a good memory that will improve. Too many people get stuck here and convince themselves that their memory is bad, that they are just not good with names, that numbers just slip out of their minds for some reason. Erase those thoughts and vow to improve your memory. Commit yourself to the task and bask in your achievements it's hard to keep motivated if you beat yourself down every time you make a little bit of progress.

2. Keep your brain active. The brain is not a muscle, but regularly "exercising" the brain actually does keep it growing and spurs the development of new nerve connections that can help improve memory. By developing new mental skills especially complex ones such as learning a new language or learning to play a new musical instrument and challenging your brain with puzzles and games you can keep your brain active and improve its physiological functioning.

3. Exercise daily. Regular aerobic exercise improves circulation and efficiency throughout the body, including in the brain, and can help ward off the memory loss that comes with aging. Exercise also makes you more alert and relaxed, and can thereby improve your memory uptake, allowing you to take better mental "pictures."

4. Reduce stress. Chronic stress, although it does not physically damage the brain, can make remembering much more difficult. Even temporary stresses can make it more difficult to effectively focus on concepts and observe things. Try to relax, regularly practice yoga or other stretching exercises, and see a doctor if you have severe chronic stress.

5. Eat well and eat right. There are a lot of herbal supplements on the market that claim to improve memory, but none have yet been shown to be effective in clinical tests (although small studies have shown some promising results for ginkgo biloba and phosphatidylserine). A healthy diet, however, contributes to a healthy brain, and foods containing antioxidants broccoli, blueberries, spinach, and berries, for example and Omega-3 fatty acids appear to promote healthy brain functioning. Feed your brain with such supplements as Thiamine, Vitamin E, Niacin and Vitamin B-6. Grazing, eating 5 or 6 small meals throughout the day instead of 3 large meals, also seems to improve mental functioning (including memory) by limiting dips in blood sugar, which may negatively affect the brain.

6. Take better pictures. Often we forget things not because our memory is bad, but rather because our observational skills need work. One common situation where this occurs (and which almost everyone can relate to) is meeting new people. Often we don't really learn people's names at first because we aren't really concentrating on remembering them. You'll find that if you make a conscious effort to remember such things, you'll do much better. One way to train yourself to be more observant is to look at an unfamiliar photograph for a few seconds and then turn the photograph over and describe or write down as many details as you can about the photograph. Try closing your eyes and picturing the photo in your mind. Use a new photograph each time you try this exercise, and with regular practice you will find you're able to remember more details with even shorter glimpses of the photos.

7. Give yourself time to form a memory. Memories are very fragile in the short-term, and distractions can make you quickly forget something as simple as a phone number. The key to avoid losing memories before you can even form them is to be able to focus on the thing to be remembered for a while without thinking about other things, so when you're trying to remember something, avoid distractions and complicated tasks for a few minutes.

8. Create vivid, memorable images. You remember information more easily if you can visualize it. If you want to associate a child with a book, try not to visualize the child reading the book that's too simple and forgettable. Instead, come up with something more jarring, something that sticks, like the book chasing the child, or the child eating the book. It's your mind make the images as shocking and emotional as possible to keep the associations strong.

9. Repeat things you need to learn. The more times you hear, see, or think about something, the more surely you'll remember it, right? It's a no-brainer. When you want to remember something, be it your new coworker's name or your best friend's birthday, repeat it, either out loud or silently. Try writing it down; think about it.

10. Group things you need to remember. Random lists of things (a shopping list, for example) can be especially difficult to remember. To make it easier, try categorizing the individual things from the list. If you can remember that, among other things, you wanted to buy four different kinds of vegetables, you'll find it easier to remember all four.

11. Organize your life. Keep items that you frequently need, such as keys and eyeglasses, in the same place every time. Use an electronic organizer or daily planner to keep track of appointments, due dates for bills, and other tasks. Keep phone numbers and addresses in an address book or enter them into your computer or cell phone. Improved organization can help free up your powers of concentration so that you can remember less routine things. Even if being organized doesn't improve your memory, you'll receive a lot of the same benefits (i.e. you won't have to search for your keys anymore).

12. Try meditation. Research now suggests that people who regularly practice "mindfulness" meditation are able to focus better and may have better memories. Mindfulness (also known as awareness or insight meditation) is the type commonly practiced in Western countries and is easy to learn. Studies at Massachusetts General Hospital show that regular meditation thickens the cerebral cortex in the brain by increasing the blood flow to that region. Some researchers believe this can enhance attention span, focus, and memory.

13. Sleep well. The amount of sleep we get affects the brain's ability to recall recently learned information. Getting a good night's sleep a minimum of seven hours a night may improve your short-term memory and long-term relational memory, according to recent studies conducted at the Harvard Medical School.
14. Build your memorization arsenal. Learn pegs, memory palaces, and the Dominic System. These techniques form the foundation for mnemonic techniques, and will visibly improve your memory.

15. Venture out and learn from your mistakes. Go ahead and take a stab at memorizing the first one hundred digits of pi, or, if you've done that already, the first one thousand. Memorize the monarchs of England through your memory palaces, or your grocery list through visualization. Through diligent effort you will eventually master the
art of memorization.