Monday, November 4, 2013

Servlet JSP Interview Questions

1. What is a servlets?
Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.


2. What are the types of Servlet?There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of  GenericServlet and provides http protocol specific functionality.

3. Servlet life cycle 
There are four phases of servlet life cycle.
 

Servlet Class Loading – When container receives request for a servlet, it first loads the class into memory.

Servlet Class Initialization – Once the servlet class is loaded, container initializes the ServletContext object for the servlet and then invoke it’s init  method by passing servlet config object.
  
Request Handling – Once servlet is initialized, its ready to handle the client requests. For every client request, servlet container initiate a new thread and invokes the service() method by passing the request and response object reference.
  
Removal from Service – When container stops or we stop the application, servlet container destroys the servlet class by invoking it’s destroy() method.


4. What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:

public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()

5. What is meant by Pre-Initialization of Servlet?
When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify 1 in between the tag in the Web.xml file in order to pre-initialize your servlet

6. Servlet constructor?
We can put one but. But I don’t think its of any use because we won’t be initialize it.

7. What are the differences between HttpServlet and Generic Servlets?
GenericServlet is protocol independent implementation of Servlet interface. HttpServlet is HTTP protocol specific implementation.

8. What is ServletConfig object?
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

9. What is ServletContext object?
javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application,

We can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

10. What is difference between ServletConfig and ServletContext?
Some of the differences between ServletConfig and ServletContext are:

ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.

ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.

We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.

11. What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

There are two methods defined in this interface:
    void forward(ServletRequest request, ServletResponse response) – forwards the request from a
    servlet to another resource (servlet, JSP file, or HTML file) on the server.
   
    void include(ServletRequest request, ServletResponse response) – includes the content of a
    resource (servlet, JSP page, HTML file) in the response.

We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.


12. What is difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.

We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

13. What is Servlet Chaining?
Servlet Chaining is a method where the output of one servlet is piped or passed onto a second servlet. The output of the second servlet could be passed on to a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

14. What is servlet lazy loading?
Lazy servlet loading means – the container does not initialize the servlets as soon as it starts up. Instead it initializes servlets when they receive their first ever request. This is the standard or default behavior. If you want the container to load your servlet at start-up then use pre-initialization using the load-on-startup element in the deployment descriptor.




15. What is the use of servlet wrapper classes?
Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper and HttpServletResponseWrapper.These wrapper classes are provided to help developers
with custom implementation of servlet request and response.

16. What is SingleThreadModel interface?
SingleThreadModel interface was provided for thread safety and it guarantees that not more then one threads will execute concurrently in the servlets service method. However SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time.

17. How to achieve thread safety in servlets?
HttpServlet init() method and destroy() method are called only once in servlet life cycle, so we don’t need to worry about their synchronization. But service  methods such as doGet() or doPost() are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.

If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread but if we have a  shared resource then we can use synchronization to achieve thread safety

18 . Diff between ServletResponse sendRedirect() and RequestDispatcher forward() method?

RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a   completely new request hence have to use session or url param for message passing.
  
forward() is handled internally by the container whereas sednRedirect() is handled by browser.

We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.

In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.
  
forward() can’t be used to invoke a servlet in other context, we can only use sendRedirect() in this case.

19. What is servlet filter?
Servlet Filters are pluggable java components use to intercept and process requests before they are sent to servlets and response before container sends back to the client.

Some common tasks that we can do with filters are:
1. Logging request parameters to log files.
2. Authentication and authorization of request for resources.
3. Formatting of request body or header before sending it to servlet.
4. Compressing the response data sent to the client.

20. what is servlet listener?
Servlet API provides Listener interfaces that we can implement and configure to listen for an event and do certain operations. Servlet API provides different types of Listener interfaces for Context, Session and Request that we can implement and configure in web.xml

21. What are different methods of session management in servlets?
Session is a conversational state between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

 Session management techniques available in servlets are:
1. HTML Hidden Field
2. Cookies
3. URL Rewriting

22. What are different ways for servlet authentication?
Servlet Container provides different ways of login based servlet authentication:

    HTTP Basic Authentication
    HTTP Digest Authentication
    HTTPS Authentication
    Form Based Login:

23. How to invoke servlets in a different application?
 We can’t use RequestDispatcher to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse sendRedirect()

24. What are the different methods present in a HttpServlet?
The methods of HttpServlet class are :
doGet() - To handle the GET, conditional GET, and HEAD requests
doPost() - To handle POST requests
doPut() - To handle PUT requests
doDelete() - To handle DELETE requests
doOptions() - To handle the OPTIONS requests and
doTrace() - To handle the TRACE requests

Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively.


25. What are the advantages of Servlets over CGI programs?
Java Servlets have a number of advantages over CGI and other API's. Some are:

Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets.

Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs.

Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.

Also, in terms of Safety & Security Servlets are superior when compared to CGI.

26. Which HTTP method is non-idempotent?
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

27. What is the difference between GET and POST method?

GET is a safe method (idempotent) where POST is non-idempotent method.

We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.

GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.

GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.

28 What is MIME Type?
The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

29. What is URL Encoding?
URL Encoding is the process of converting data into CGI form so that it can travel across the network.URL Encoding strip the white spaces and replace special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String unicode) to encode a String.

30. What is different between web server and application server?
A web server responsibility is to handler HTTP request and response. Application Servers is web server with additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc.

31. What are common tasks performed by Servlet Container
Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of  container, we don’t need to build a server socket to listen for any request from web client, parse the request and generate response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.
                             
Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. Container also provides utility like JNDI for resource pooling and management

Multi-threading Support: Container creates new thread for every request to the servlet and provide them request and response objects to process. So servlets are not initialized for each request and saves time and memory.       
   
JSP Support: JSP compiled by container and converted to Servlet and then  container manages them like other servlets.

Deployment and Other : provides security configurations,support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.

32. How can we achieve transport layer security for our web application?
We can configure our servlet container to use SSL for message communication over the network..

33. What are the differences between a Servlet and an Applet?
Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser.

Applets have GUI interface but there is no GUI interface in case of Servlets.

Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations

34. What are important features of Servlet 3?
Servlet Annotations : java annotations to define a servlet, filter and listener servlets and init parameters

Web Fragments : we can have multiple modules in a single web application, all these modules should have web-fragment.xml file in META-INF directory.

Adding Web Components dynamically:  We can use ServletContext object to add servlets, filters and listeners programmatically.

Asynchronous Processing: Delegate the request processing to another thread rather than keeping the servlet thread busy.

35. What is JSP
Java Server Pages are an extension to the Java servlet technology. A JSP is translated into Java servlet before being run, and it processes HTTP requests and generates responses like any servlet.

A JSP page can have two types of data one is Template Data it is the static part of a jsp page other one is JSP Elements it is the dynamic part of a jsp page translated and executed by the server.

36. what is JSPF
JSP Fragments can be compared to server side includes. These fragments are not compiled on their own, They're designed to be statically included in another JSP file,

37. What is JSP Element :

There are three type of element Scripting,Directive,Standard Action.

Scripting Elements:
    JSP declaration tag: Define variables and Method. Statements should end with semi-colon
            Syntax:
             <%!  statement;  %>   or <jsp:declaration> statement; </jsp:declaration>    

    JSP Scriptlet tag : Declare or define any java code into jsp.
                Syntax:
                <% statement; %>  or <jsp:scriptlet>  Java code; </jsp:scriptlet>

    JSP expression tag : Use to display java values to the browser.
                  Syntax:
                  <%= statement %> or <jsp:expression> statement < /jsp:expression>

     Comment : Hidden comment <%-- --%>or HTML comment <!-- -->

Directive Element:
    Page Directive : used to specify attributes for the JSP page. Some attributes are language, import,
     session, pageEncoding.
     Syntax:
       <%@ page import="java.util.*" %> or <jsp:directive.page import="java.util.*" />

     Include Directive :   It allows to include source code (static resource) of a file inside a jsp file at
     the specified place at a translation time.Typically include files are used for headers, footers, tables
     and navigation that are common to multiple pages
                            Syntax:
                                    <%@ include file="/folder_name/file_name"%>
    TagLib directive : The taglib directive makes custom actions available in the page through the use
    of tag library.
Standard Action :
Actions are create, modify or use other objects. Unlike directives and scripting elements, JSP actions are coded using strict XML syntax form.
The standard action types are:

                (1)<jsp:param>

                (2)<jsp:include>

                (3)<jsp:forward>

                (4)<jsp:fallback>

                (5)<jsp:plugin>

                (6) <jsp:useBean>

                (7)<jsp:setProperty>

                (8)<jsp:getProperty>

38. What is the difference between < jsp : include page = ... > and < % @ include file = ... >? 

The jsp:include element is processed when a JSP page is executed.
The include directive is a static include is processed at compile time,no support for parameter pasing.

39.What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are injected by web container and contain information related to a particular request, page, and application.

The JSP implicit objects are:

application
config
exception
out
page
pageContext
request
response and
session

40. What are all the different scope values for the < jsp : useBean > tag?

Scopes are following:
a) page
b) request
c) session and
d) application

41. What are the life-cycle phases of a JSP?

Page translation: -  Page is parsed, and a java file which is a servlet is created.
Page compilation:  Page is compiled into a class file
Page loading :       This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.



42. What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.

c) jspDestroy(): The container calls this when its instance is about to destroyed.

The jspInit() and jspDestroy() methods can be overridden within a JSP page.



43. What do you understand by JSP translation?

JSP translation is an action that refers to the conversion of the JSP page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.


44. What is EL ?
expression language systax ${}

45. how does EL search for an attribute ?
EL parser searches the attribute in following order:
Page
Request
Session (if it exists)
Application
If no match is found for then it displays empty string.

46. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. every time you click on any link in the website URL rewriting require data transfer from and to the
server

47. What is session hijacking?
Session hijacking refers to the act of taking control of a user session with authentication. to prevent this use SSL/HTTPS or regeneration of session token or  session regenerate technique.

48. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. we can achieve this by
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

Friday, April 19, 2013

HOW CALL JAVA METHOD FROM ORACLE / Java Stored Procedure



Step-1: Create Java Project in eclipse. I use jdk  1.5 for oracle 11g.

Step-2: Form oracle we can call static method.  for the supported data type check this link . This link will be helpful to define parameter and return type. For the User Defined Data type we have  implement either the SQLData or CustomDatum interface.  

package com.abb.functions;

import java.sql.Array;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Dictionary;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
import com.abb.functions.out.model.BranchOpenDateOut;


public class BranchWrapper {
    public synchronized static String isValidBranch(String branchCode) {
        return "CBS";
    }

    public static Array parseToArray(String str, String delim) throws SQLException {
        OracleDriver ora = new oracle.jdbc.OracleDriver();
        Connection conn = ora.defaultConnection();
        OracleConnection oraConn = (OracleConnection) conn;
        Array arr = oraConn.createARRAY("STRINGARRAY", str.split(delim));
        return arr;
    }
   
    public synchronized static BranchOpenDateOut isBranchOpenDate(String branchCode) throws SQLException {

        BranchOpenDateOut e = new BranchOpenDateOut("BRANCHOPENDATEOUT", "KAMAL HOSSAIN");       
        return e;
    }   


}
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;

import oracle.jdbc.driver.OracleConnection;
import oracle.jpub.runtime.MutableStruct;
import oracle.sql.CustomDatum;
import oracle.sql.CustomDatumFactory;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
public BranchOpenDateOut  implements CustomDatum, CustomDatumFactory {
    public static final String _SQL_NAME = "
BranchOpenDateOut";
    public static final int _SQL_TYPECODE = oracle.jdbc.OracleTypes.STRUCT;

    MutableStruct _struct;

    static int[] _sqlType = {java.sql.Types.VARCHAR };

    static CustomDatumFactory[] _factory = new CustomDatumFactory[_sqlType.length];

    static final TRANSACTIONOUT _
BranchOpenDateOutFactory = new TRANSACTIONOUT();

    public static CustomDatumFactory getFactory() {
        return _
BranchOpenDateOutFactory ;
    }

    /* constructor */
    public TRANSACTIONOUT() {
        _struct = new MutableStruct(new Object[_sqlType.length], _sqlType,
                _factory);
    }

    /* CustomDatum interface */
    public Datum toDatum(OracleConnection c) throws SQLException {
        return _struct.toDatum(c, _SQL_NAME);
    }

    /* CustomDatumFactory interface */
    public CustomDatum create(Datum d, int sqlType) throws SQLException {
        if (d == null) {
            return null;
        }
        TRANSACTIONOUT o = new TRANSACTIONOUT();
        o._struct = new MutableStruct((STRUCT) d, _sqlType, _factory);
        return o;
    }

    /* accessor methods */
    public String getmResBrDt() throws SQLException {
        return (String) _struct.getAttribute(0);
    }

    public void setmResBrDt(String mResBrDt) throws SQLException {
        _struct.setAttribute(0, mResBrDt);
    }
  
         
}


Step-3: after compiling this project export it as jar.


Step-4 use following loadjava command
Loadjava –user schema xyz jar-location


Step-5: in oracle create a Wrapper based on the static method want to call from oracle.


CREATE or REPLACE
FUNCTION ISVALIDBRANCH(brCode VARCHAR2) RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'com.abb.functions.BranchWrapper.isValidBranch(java.lang.String) return java.lang.String';


CREATE or REPLACE
FUNCTION PARSETOARRAY (str IN VARCHAR2, delim IN VARCHAR2)
RETURN STRINGARRAY AS
LANGUAGE JAVA NAME 'com.abb.functions.BranchWrapper.parseToArray (java.lang.String, java.lang.String) return java.sql.Array';



CREATE or REPLACE
FUNCTION ISBRANCHOPENDATE(brCode VARCHAR2) RETURN BranchOpenDateOut AS
LANGUAGE JAVA NAME 'com.abb.functions.BranchWrapper.isBranchOpenDate2(java.lang.String) return com.abb.functions.out.model.BranchOpenDateOut';

We have to map BranchOpenDateOutin and  STRINGARRAY  oracle as Object


CREATE or REPLACE  TYPE BranchOpenDateOut AS OBJECT (
   mResBrDt VARCHAR2 (100)
)

CREATE or REPLACE type STRINGARRAY is table of varchar2(4000);

That it we have done now we are going to call JAVA METHODS from oracle.

DECLARE
  STR VARCHAR2(200);
  DELIM VARCHAR2(200);
  v_Return STRINGARRAY;
  v_Return2 ABBTEST.BRANCHOPENDATEOUT;
v_Return3 VARCHAR2(200);
BEGIN
 
-- call to  parseToArray method
  STR := 'A,B';
  DELIM := ',';

  v_Return := PARSETOARRAY(STR => STR, DELIM => DELIM );

FOR i IN v_Return.first .. v_Return.last LOOP
     DBMS_OUTPUT.PUT_LINE(v_Return(i));
END LOOP;

-- call to  isBranchOpenDate method
v_Return2 := ISBRANCHOPENDATE(BRCODE => BRCODE);
DBMS_OUTPUT.PUT_LINE(v_Return2.mResBrDt);
-- call to  isValidBranch method
v_Return3 := ISVALIDBRANCH(BRCODE => BRCODE);
DBMS_OUTPUT.PUT_LINE(v_Return3);

  
END;






Wednesday, April 25, 2012

Spring Annotations


Context Configuration Annotations :
These annotations are used by Spring to guide creation and injection of beans

@Required indicates that the affected bean property must be populated at configuration time Method
@Autowired Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. Constructor, Field,
Method
@Inject can be used in place of Spring's @Autowired. does not have a required property

@Qualifier @Qualifier which takes a string property to discriminate among multiple injection candidates and can be placed on annotations as well as types, fields, methods,
constructors, and parameters.
Field, Parameter,
Type,
Annotation Type
@Configurable Marks a class as eligible for Spring-driven configuration Type
@Order Annotation that defines ordering Type, Method,
Field
@Scope Specifies the scope of a bean, either singleton, prototype, request, session,or some custom scope. Type







Spring Java Configuration :

@Configuration Indicates that a class declares one or more Bean methods and may be processed by the Spring container to generate bean definitions Type
@Bean Indicates that a method produces a bean to be managed by the Spring container. Method
@Import allows for loading @Bean definitions from another configuration class: Type
@ExternalValue same as @Value annotation and use of Spring EL. Method,
Field
@ImportXml allows for loading bean definitions from another xml Type
@AnnotationDrivenConfig enable the @Autowired annotation Type
@ComponentScan Spring's @Service and @Repository stereotype annotations are each meta-annotated with Type
@AnnotationDrivenTx Like Spring XML's <tx:annotation-driven> element, @AnnotationDrivenTx expects the presence of a bean named transactionManager Type
@AspectJAutoProxy detects any@Aspect beans and generates proxies as appropriate to weave the advice methods in those aspectsagainst other beans in the containe Type
@MBeanExport equivalent to Spring XML's <context:mbean-export/> element, JavaConfig provides the @MBeanExport annotation. Type
@DependsOn Beans on which the current bean depends. Type
@Primary indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. methods
annotated with Bean.
@Lazy Indicates whether a bean is to be lazily initialized. Type
@ImportResource Like @Import Type,
Method
@Async Annotation that marks a method as a candidate for asynchronous execution. Can also be used at the type level, in which case all of the type's methods are considered as asynchronous. Type

Stereotyping Annotations :

These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration.

@Component Generic stereotype annotation for any Spring-managed component. Type
@Controller Stereotypes a component as a Spring MVC controller Type
@Repository Stereotypes a component as a repository. Also indicates that SQLExceptions thrown from the component’s methods should be translated into Spring DataAccessExceptions. Type
@Service Stereotypes a component as a service Type


Spring MVC Annotations:

These annotations were introduced in Spring 2.5 to make it easier to create Spring MVC applications,<context:component-scan> is required

@PathVariable Annotation which indicates that a method parameter should be bound to a URItemplate variable. Supported for RequestMapping annotated handler methods in Servlet environments. Parameter
@InitBinder Annotation that identifies methods which initialize the WebDataBinder which will be used for populating command and form object arguments of annotated handler methods. Method
@ModelAttribute @ModelAttribute is a Spring-MVC specific annotation used for preparing the model data. It is also used to define the command object that would be bound with the HTTP request data. The annotation works only if the class is a Controller class. ModelAttribute can be applied on both methods as well as method-parameters. It accepts an optional "value", which indicates the name of the attribute. If no value is supplied to the annotation, then the value would be defaulted to the return type name in case of methods and parameter type name in case of
method-parameters.

The way Spring processes this annotation is, Before invoking the handler method, Spring invokes all the methods that have @ModelAttribute annotation. It adds the data returned by these methods to a temporary Map object. The data from this Map would be added to the final Model after the execution of the handler method.Then it prepares to invoke the the handler method. To invoke this method, it has to resolve the arguments. If the method has a parameter with @ModelAttribute, then it would search in the temporary Map object with the value of @ModelAttribute. If it finds, then the value from the Map is used for the handler method parameter.It it doesn't find it in the Map, then it checks if there is a SessionAttributes annotation applied on the controller with the given value. If the annotation is present, then the object is retrieved from the session and used for the handler method parameter. If the session doesn't contain the object despite of the @SessionAttributes, then an error is raised.If the object is not resolved through Map or @SessionAttribute, then it creates an instance of the parameter-type and passes it as the handler method parameter. Therefore, for it to create the instance, the parameter type should be a concrete-class-type (interfaces or abstract class types would again raise an error).Once the handler is executed, the parameters marked with @ModelAttributes are added to the Model.
Parameter
Method
@RequestMapping Maps a URL pattern and/or HTTP method to a method or controller . Method, Type
@RequestParam Binds a request parameter to a method parameter. Parameter,
Method
@SessionAttributes Specifies that a model attribute should be stored in the session. Type
@RequestHeader Allows a method parameter to be bound to a request header Parameter
@CookieValue Allows a method parameter to be bound to the value of an HTTP cookie Parameter
@ExceptionHandler

Method


Spring Validation Annotation :

@NumberFormat This annotation allows either a number style or pattern to be specified Field
@DateTimeFormat format a java.util.Date as required Field
@NotNull

Field
@Size

Field
@Min

Field
@Valid The Validator instance invoked when a @Valid method argument is encountered may be configured Parameter


Spring Expression Language (SpEL) :

@Value
Declares transactional boundaries and rules on a bean and/or its methods.
Method, Type

Transaction Annotations :
require <tx:annotation-driven>

@Transactional
Declares transactional boundaries and rules on a bean and/or its methods.
Method, Type

Aspect Annotations :
<aop:aspectj-autoproxy> required

@Aspect Declares a class to be an aspect. Type
@After Declares a method to be called after a pointcut completes. Method
@AfterReturning Declares a method to be called after a pointcut returns successfully. Method
@AfterThrowing Declares a method to be called after a pointcut throws an exception. Method
@Around Declares a method that will wrap the pointcut. Method
@Before Declares a method to be called before proceeding to the pointcut. Method
@DeclareParents Declares that matching types should be given new parents,that is, it introduces new functionality into matching types. Static Field
@Pointcut the method serving as the pointcut signature must have a void return type. method must have an empty method body and must not have any throws clause .
upported Pointcut Designators are execution,within,this, target, args, @target, @args,@within,@annotation
Method


JMX Annotations :
<context:mbean-export/> required

@ManagedAttribute Used on a setter or getter method to indicate that the bean's property should be exposed as a MBean attribute Method
@ManagedNotification Indicates a JMX notification emitted by a bean. Type
@ManagedNotifications Indicates a JMX notifications emitted by a bean. Type
@ManagedOperation Specifies that a method should be exposed as a MBean operation. Method
@ManagedOperationParameter Used to provide a description for an operation parameter. Method
@ManagedOperationParameters Used to provide a descriptions for an operation parameter. Method
@ManagedResource Specifies that all instances of a class should be exposed a MBeans. Type


JSR-250 ANOTATION :

@Resource Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods Method,Field
@PostConstruct indicates a method to be invoked after a bean has been created and dependency injection is complete. Used to perform any initialization work necessary. Method
@PreDestroy Indicates a method to be invoked just before a bean is removed from the Spring context. Used to perform any cleanup work necessary. Method


Testing Annotations :

@AfterTransaction Used to identify a method to be invoked after a transaction has completed. Method
@BeforeTransaction Used to identify a method to be invoked before a transaction starts. Method
@ContextConfiguration Configures a Spring application context for a test. Type
@DirtiesContext Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes. Method
@ExpectedException Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown. Method
@IfProfileValue Indicates that the test class or method is enabled for a specific profile configuration. Type, Method
@NotTransactional Indicates that a test method must not execute in a transactional context. Method
@ProfileValueSourceConfiguration Identifies an implementation of a profile value source. The absence of this annotation cause profile values to be loaded from system properties Method
@Repeat Indicates that the test method must be repeated a specific number of times. Method
@Rollback Specifies whether or not the transaction for the annotated method should be rolled back or not. Method
@TestExecutionListeners Identifies zero or more test execution listeners for a test class. Type
@Timed Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail. Method
@TransactionConfiguration Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class. Type
@RunWith specifies the Spring configuration to load for this test fixture Type
@Test Indicate test Method


Friday, October 7, 2011

RabbitVCS icon is missing in contex menu

In my last post try to explain how to install  RabbitVCS in ubuntu. i later when i start to use Ubutu10.10 found that all the steps are fine for Ubutu10.4 and i need a fix for it. after spending a lot I found that Gnome in  10.10 is different. see that it's a bug in the extension code, but you might be able to work  around it if you disable "show attributes" in the settings

try this command to enable:

gconftool-2 --type boolean --set /desktop/gnome/interface/menus_have_icons  true

i hope this time RabbiVcs will appear in you Context Menu.

Tuesday, April 5, 2011

New jQuery version into Liferay Portal

Copy the file "top_head.jsp" located in folder "liferay-portal-src-[version]\portal-web\docroot\html\common\themes\" into the EXT-folder 'liferay-portal-ext\ext-web\docroot\html\common\themes\'

>Open the copied file in your EXT
>Add the following lines:
<script  src="/html/js/jQuery1.3.2/jquery1.3.2.js" type="text/javascript"></script>
<script  src="/html/js/jQuery1.3.2/ui.jquery1.7.js" type="text/javascript"></script>
<script >="" src="/html/js/jQuery1.3.2/ui.stars.js" type="text/javascript"></script>

<script type="text/javascript">
var $132 = jQuery.noConflict(true);
 </script>
> Now you can access jQuery 1.3.2'.

Saturday, December 25, 2010

how to use ZTE Modem in linux


To intall Citycell ZTE Modem in linux you should follow following steps

  1. Plug Modem to PC
  2. open terminal and use lsusb command which will show usb device plugged at the time in my case I get following out put
#lsusb
    Bus 007 Device 002: ID 0a5c:2101 Broadcom Corp. Bluetooth Controller
    Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
    Bus 006 Device 002: ID 15d9:0a4c Trust International B.V.
    Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
    Bus 005 Device 003: ID 19d2:fff1 ONDA Communication S.p.A.
    Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
    Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
    Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 002: ID 064e:a101 Suyin Corp. Acer CrystalEye Webcam
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
bold line is my ZTE Modem from that output I get vendor is 19d2 and product id fff1

  1. now load driver using modprobe command
    # sudo modprobe usbserial vendor=0x19d2 product=0xfff
  2. now edit wvdial config
    #sudo gedit /etc/wvdial.conf
    insert followin lines
    [Dialer Defaults]
    Init2 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0
    Modem Type = Analog Modem
    ISDN = 0
    Init1 = ATZ
    Modem = /dev/ttyUSB0
    Baud = 9600
    [Modem0]
    Init1 = ATZ
    SetVolume = 0
    Modem = /dev/ttyUSB0
    Baud = 230400
    FlowControl = Hardware (CRTSCTS)
    Dial Command = ATDT
    [Dialer citycell]
    Stupid Mode = 1
    Inherits = Modem0
    Password = waps
    Username = waps
    Phone = #777
  3. now dial you moden using following command
    #sudo wvdial citycell
If you do not have wvdial installed in you pc then install follwing:
  1. wvdial_1.60.1
  2. libxplc0.3.13_0.3.13-1
  3. libwvstreams4.4-base
  4. libwvstreams
  5. libuniconf

Thursday, December 23, 2010

Ubuntu USB file transfer is slow

Some time you might experence Ubuntu USB file transfer is slow then you can try following solution
$ sudo gedit /etc/default/grub

edit as following
#GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash pci=noacpi pci=routeirq"

then reload
$ sudo grub-mkconfig -o /boot/grub/grub.cfg


This fix might not work for every one.

AWS Services

      1.         Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources).                   1....