Showing posts with label Interview Questions. Show all posts
Showing posts with label Interview Questions. Show all posts

Monday, 14 October 2013

Internationalization Using Spring MVC



Spring MVC Internationalization

Questions:-What is i18n (internationalization) and L10n (localization)?

Answer:- According to computer vocabulary, i18n means internationalization and L10n means localization. Here, in i18n -18 belongs to the number of letters between the first i and the last n in the word internationalization. Similarly, In L10n - 10 belongs to the number between the first L and last n in the word localization.
                                                            With the help of internationalization and localization, we can make software in different languages; even we can use it in our regional languages. A process through which software can adapt to various languages and regions without re- engineering is known as internationalization. Similarly, A process through which internationalized software can adapt a specific region or language by adding locale-specific components and translating text.
Spring MVC module, comes with few “LocaleResolver” which support s the internationalization or multiple languages features.

Spring Configuration
 
if we want to use Spring MVC module for supporting the internationalization, then in this case we have to register two beans.

Local Resolvers
 
it’s a component capable of resolving the locale and offer internationalized views which is used by a client. org.springframework.web.servlet.i18n is the package where Locale resolvers and interceptors are available and are configured in your application context in the normal way like other beans. All Known Implementing Classes are AbstractLocaleResolver, AcceptHeaderLocaleResolver,  CookieLocaleResolver, FixedLocaleResolver, SessionLocaleResolver

 SessionLocaleResolver

We have to register a “SessionLocaleResolver” bean. While registering this resolver the bean-id should be exactly the same as “localeResolver”, because it’s a predefined attribute from user’s session. For example:-
<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en"/>
</bean>

AcceptHeaderLocaleResolver

Important Fact:

If we will not register any “localeResolver”, then the default AcceptHeaderLocaleResolver will be used, which resolves the locale by checking the accept-language header in the HTTP request. This header field contains the locale of the client's operating system. This is the default locale resolver and in order to use this locale resolver, we don't require configuring anything in spring configuration file.This locale resolver inspects the accept-language header in the request that was sent by the browser of the client.


CookieLocaleResolver

This locale resolver inspects a Cookie that might exist on the client, to see if a locale is specified. If so, it uses that specific locale. Using the properties of this locale resolver, you can specify the name of the cookie, as well as the maximum age. Find below an example of defining a CookieLocaleResolver.

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">

    <property name="cookieName" value="clientlanguage"/>
   
    <!-- in seconds. If set to -1, the cookie is not persisted (deleted when browser shuts down) -->
    <property name="cookieMaxAge" value="100000">

</bean>

CookieLocaleResolver properties

Property
Default
Description
cookieName
classname + LOCALE
The name of the cookie
cookieMaxAge
Integer.MAX_INT
The maximum time a cookie will stay persistent on the client. If -1 is specified, the cookie will not be persisted. It will only be available until the client shuts down his or her browser.
cookiePath
/
Using this parameter, you can limit the visibility of the cookie to a certain part of your site. When cookiePath is specified, the cookie will only be visible to that path, and the paths below it.

  
LocaleChangeInterceptor

This Interceptor will allow for changing the current locale on every request, via a configurable request parameter. We have to register a “LocaleChangeInterceptor” and reference it to any handler mapping that need to supports the multiple languages. The “paramName” is the parameter value that’s used to set the locale. It calls setLocale() on the LocaleResolver that also exists in the context. All calls containing a parameter named siteLanguage will now change the locale. So a request for the following URL, http://localhost:7075/SpringMVCInternationalization/index.htm?siteLanguage=es will change the site language to Spanish.

Note: - siteLanguage is the value which we are passing against paramName attribute of LocaleChangeInterceptor.


Method Summary
 boolean
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
          This implementation always returns true.
 void
setParamName(String paramName)
          Set the name of the parameter that contains a locale specification in a locale change request.


In this case,

index.htm?
siteLanguage=en – Get the message from English properties file.
index.htm?
siteLanguage=es – Get the message from Spanish properties file.


<bean id="localeChangeInterceptor"
      class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="siteLanguage"/>
</bean>
 
<bean id="localeResolver"
    class=" org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
 
<bean id="urlMapping"
      class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="localeChangeInterceptor"/>
        </list>
    </property>
</bean>

<!-- Registering the bean -->
            <bean class="com.gaurav.spring.internationalization.controller.WelcomeController" />

            <!-- Registering the message properties files-->

            <bean id="messageSource"                  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
                         <property name="basenames">  
 <list>  
<value>/WEB-INF/resourcebundle/messages</value>  
</list>  
                        </property>                
<property name="defaultEncoding" value="UTF-8"/>
            </bean>

            <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    

welcome_en.properties

welcome.springmvcinternationalization = Welcome in England

welcome_es.properties

welcome. springmvcinternationalization = Welcome in Spain

We have to code Like below in the JSP page in order to use Internationalization.

<spring:message code=" welcome.springmvcinternationalization " text="default text"/>  

Thursday, 10 October 2013

Hibernate Interview Questions Part - 2



Interview Questions

Questions: - What is the use of inverse in Hibernate?

Answer: - The “inverse” keyword is always declare in one-to-many and many-to-many relationship. We 
don’t have “inverse” keyword in many-to-one relationship. “inverse” is used to decide which side is the relationship owner will manage the relationship (insert or update of the foreign key column). It means which side is responsible to take care of the relationship.

inverse = “true” describes that this is the relationship owner, where as inverse=”false” (default) means it’s not the relationship owner.

Questions: - What is the use of cascade in Hibernate?

Answer: -

Cascade values are
1.      none (default)
2.      save
3.      update
4.      save-update
5.      delete
6.      all
7.      all-delete-orphan

If cascade = “none” and if we execute save (or update or delete) operation on parent class object, then child class objects will not be effected.

If we write cascade = “all”, then the operations like save or delete or update executed at parent class object will be effected to child class object also.

If we write cascade = “save-update”, then the operations like save and update executed at parent class object will also be effected to child class object also.

In an application, if a child record is removed from the collection and if we want to remove that child record immediately from the database, then we need to set the cascade =”all-delete-orphan”


Questions: - What is the use of BAG collection in hibernate?

Answer: - If our table does not have an index column, and we want to use collection property type, then in this case we can use <bag> Collection property in Hibernate. When a collection of data is retrieved and assigned to bag collection then bag does not retain its order but it can be optionally sorted or ordered. A bag permit duplicates it means it does not have primary key. So finally we can tell that a bag is an unordered, unkeyed collection that can contain the same element multiple times.


Questions: - What is optimistic locking in Hibernate?
Answer: - When we load object in one transaction, modify the data and save it later in another transaction then in this situation Hibernate optimistic locking works. This locking ensures that some other transaction hasn’t changed that same object in the database in between. However, optimistic locking doesn't affect isolation of concurrent transactions.  


Questions: - What is transactional write behind in Hibernate?

Answer: - When we call session.save(Object) in the hibernate code then it does not fire the SQL insert query immediately. Similarly when we call session.delete(Object) or session.update(Object)  then it will not fire the corresponding SQL queries(delete and update queries) immediately.

The meaning is that when objects associated with persistence context are modified, the changes are not immediately propagated to the database.

Hibernate collects all such database operations associated with a transaction and create minimum set of SQL queries and execute them. This will provide us 2 advantages:-

  • In case of multiple updates or inserts or deletes, Hibernate is able to make use of the JDBC Batch API to optimize performance.
  • Every property change in the object does not cause a separate sql update query to be executed.
  • Avoiding unwanted SQL queries ensures minimum hits to database thus reducing the network latency.

This delayed execution of sql queries is known as transactional write behind.

Sunday, 22 September 2013

Transaction Management In Spring Part-2

Spring Transaction Managers





Platform-specific Transaction Implementations

Methods available in the org.springframework.transaction.PlatformTransactionManager interface are shown below:

  • PlatformTransactionManager


public interface PlatformTransactionManager {

    TransactionStatus getTransaction(TransactionDefinition definition)
        throws TransactionException;
                                Return a currently active transaction or create a new one, according to the specified propagation behavior.
     
    void commit(TransactionStatus status) throws TransactionException;
            Commit the given transaction, with regard to its status.
    
    void rollback(TransactionStatus status) throws TransactionException;
           Perform a rollback of the given transaction.
}

  • TransactionStatus Interface


A TransactionStatus is associated with a thread of execution. The TransactionStatus interface provides a normal and simple way for transactional code to control transaction execution and query transaction status. They are common to all transaction APIs:

public interface TransactionStatus {

    boolean isNewTransaction();
                  Return whether the present transaction is new (else participating in an existing transaction, or potentially not running in an actual transaction in the first place).

   
    boolean hasSavepoint();
                  Return whether this transaction internally carries a savepoint, that is, has been created as nested transaction based on a savepoint. 

    void setRollbackOnly();
            Set the transaction rollback-only.
    
    boolean isRollbackOnly();
               Return whether the transaction has been marked as rollback-only (either by the application or by the transaction infrastructure).

    
    boolean isCompleted();
                 Return whether this transaction is completed, that is, whether it has already been committed or rolled back. 
}

  • TransactionDefinition interface


The TransactionDefinition interface specifies:
  •          Transaction isolation: It is applied to transactions in general and is directly related with the ACID transaction properties. For example, can this transaction see uncommitted writes from other transactions?
  •          Transaction propagation: All code executed within a transaction scope will run in that transaction and there are several options specifying propagation behavior if a transactional method is executed when a transaction context already exists: For example, simply running in the existing transaction or suspending the existing transaction and creating a new transaction.
  •          Transaction timeout: How long this transaction may run before timing out (automatically being rolled back by the underlying transaction infrastructure).
  •          Read-only status: A read-only transaction does not modify any data.


public interface TransactionDefinition{

int getIsolationLevel();
                    Return the isolation level.

String getName();
                    Return the name of this transaction. Can be null.

int getTimeout();
                    Return the transaction timeout.

boolean isReadOnly();
                    Return whether to optimize as a read-only transaction.
 

Transaction State

There are few different possible Transaction states and they are:

Active – The initial state of transaction and transaction stays in this state while executing.

Failed When the failed state is determined then the normal execution can no longer proceed.

Aborted – The state of the transaction when it has been roll-backed and the database taken back to its initial state.

Partially Committed – The state of the transaction after the final statement has been executed.

Committed – The state of the transaction after successful completion.




Different Transaction States