Thursday, November 21, 2013

Car Driving - L01

Lesson 1

Pre trip inspection 
Exterior inspection
starting from anti clockwise.

How to start car

Key on engine
check parking brake is on and gear should be neutral.
press full clutch by foot
change gear to  1st
make parking brake off
release clutch slowly halfway 



How to stop a car from above position

press clutch fully 
Bring back gear to neutral
make parking brake on
press foot brake slowly


End of lesson - Confidence level .05 %

Tuesday, March 5, 2013

Query Optimization ...........1

  • ----- This post is excerpt of Pinal Dave 's article published on www.sqlauthority.com ----
  • ----- Try to get causes of each sentence  -----
  •  
  • Notes prepared for “Good, Better and Best Programming Techniques” meeting
  • Do not prefix stored procedure with SP_ prefix. As they are first searched in master database, before it is searched in any other database.
  • Always install latest server packs and security packs.
  • Make sure your SQL Server runs on optimal hardware. If your operating system supports 64 bit SQL Server, install 64 bit SQL Server on it. Raid 10 Array.
  • Reduce Network Traffic by using Stored Procedure. Return only required result set from database. If application needs paging it should have done in SQL Server instead of at application level.
  • After running query check Actual Execution Plan for cost of the query. Query can be analyzed in Database Engine Tuning Advisor.
  • Use User Defined Functions sparsely, use Stored Procedures instead.
  • Stored Procedure can achieve all the tasks UDF can do. SP provides much more features than UDFs.
  • Test system with realistic data rather than sample data. Realistic data provides better scenario for testing and reveals problems with real system before it goes to production.
  • Do not use SELECT *, use proper column names to decrease network traffic and fewer locks on table.
  • Avoid Cursors as it results in performance degradation. Sub Query, derived tables, CTE can perform same operation.
  • Reduces the use of nullable columns.
  • NULL columns consumes an extra byte on each column used as well as adds overhead in queries. Also NULL is not good for logic development for programmers.
  • Reduce deadlocks using query hints and proper logic of order in columns.
  • Normalized database always increases scalability and stability of the system. Do not go over 3rd normal form as it will adversely affect performance.
  • Use WHERE clauses to compare assertive logic. Use IN rather than NOT IN even though IN will require more value to specify in clause.
  • BLOBS must be stored filesystem and database should have path to them only. If path is common stored them in application variable and append with filename from the BLOBColumnName.
  • Always perform referential integrity checks and data validations using constraints such as the foreign key and check constraints.
  • SQL Server optimizer will use an index scan if the ORDER BY clause is on an indexed column.
  • Stored Procedure should return same numbers of resultset and same columns in any input parameters. Result Set of Stored Procedure should be deterministic.
  • Index should be created on highly selective columns, which are used in JOINS, WHERE and ORDER BY clause.
  • Format SQL Code. Make it readable. Wrap it.
  • Use Column name in ORDER BY clause instead of numbers.
  • Do not use TEXT or NTEXT if possible. In SQL Server 2005 use VARCHAR(MAX) or NVARCHAR(MAX).
  • Join tables in order that they always perform the most restrictive search first to filter out the maximum number of rows in the early phases of a multiple table join.
  • Remember to SET NOCOUNT ON at the beginning of your SQL bataches, stored procedures, triggers to avoid network traffic. This will also reduct the chances of error on linked server.
  • Do not use temp tables use CTE or Derived tables instead.
  • Always take backup of all the data.
  • Never ever work on production server.
  • Ask someone for help if you need it. We all need to learn.

Saturday, March 2, 2013

What is JNDI

The Java Naming and Directory Interface (JNDI) is an application programming interface (API) for accessing different kinds of naming and directory services. JNDI is not specific to a particular naming or directory service, it can be used to access many different kinds of systems including file systems; distributed objects systems like CORBA, Java RMI, and EJB; and directory services like LDAP, Novell NetWare, and NIS+.
JNDI is similar to JDBC in that they are both Object-Oriented Java APIs that provide a common abstraction for accessing services from different vendors. While JDBC can be used to access a variety of relational databases, JNDI can be used to access a variety of of naming and directory services.
check http://www.jguru.com/faq/view.jsp?EID=10852

To know JNDI one should know first what is Naming and Directory Service.

Tuesday, January 22, 2013

Servlet 3.0 ( Tidbits ) ......2

  • Difference between response.sendRedirect("path" ) & req.getRequestDispatcher("path").forward(req,resp);

In former method a fresh request will be directed to url hence loosing all req level attributes and param in the redirected page . client will be notified that req is being redirected. In later  the current req attributes and params will be preserved  & client wont be  intimated that it is being taken to another page .

  • Difference between RequestURI /URL

http://localhost:8080/myWebapp/FirstServlet/second.jsp?blogname=thevoid

reqURL = http://localhost:8080/myWebapp/FirstServlet/second.jsp ( except Qry String)
reqURI = /FirstServlet/second.jsp ( excluding context and qey string )
path info = /second.jsp ( between urlPattern for servlet  and Qry string  ) 
Qry String  =  blogname=thevoid ( after  ? )

  • Difference between req.getReader() req.getInputStream()

getReader() returens Buffered Reader  & givers character data of req body  .
getInputStream() returns ServletInputStream & gives binary Data of req body .
** body doesnt include  headers


Servlet 3.0 ( Tidbits ) ......1

Different between RequestDispatcher  in context and request .

RequestDispatcher can be obtained either from ServletContext or from ServletRequest.

An object implementing the RequestDispatcher interface may be obtained from the ServletContext via the following methods:
■ getRequestDispatcher(String Path)
■ getNamedDispatcher(String Servletname)

The getRequestDispatcher method takes a String argument path. This path must be relative to the root of the
ServletContext and begin with a ‘/’, or be empty. The method uses the path to look up a servlet, using the servlet path matching rules,and wraps it with a RequestDispatcher object, and returns the resulting object. If no servlet can be resolved based on the given path, a RequestDispatcher is provided that returns the content for that path.

The getNamedDispatcher method takes a String argument indicating the name of a servlet known to the ServletContext. If a servlet is found, it is wrapped with a RequestDispatcher object and the object is returned. If no servlet is associated with the given name, the method must return null.

To allow RequestDispatcher objects to be obtained using relative paths that are relative to the path of the current request (not relative to the root of the ServletContext) (if omitting the / slash ), the  getRequestDispatcher method is provided in the ServletRequest interface.
The servlet container uses information in the request object to transform the given relative path against the current servlet to a complete path. For example,
 in a context rooted at ’/’ and a request to /garden/tools.html, a request dispatcher obtained via ServletRequest.getRequestDispatcher("header.html") will behave exactly like a call to ServletContext.getRequestDispatcher("/garden/header.html").

Query Strings in Request Dispatcher Paths

The ServletContext and ServletRequest methods that create RequestDispatcher objects using path information allow the optional attachment of query string information to the path. For example, a Developer may obtain a RequestDispatcher by using the following code:

String path = “/raisins.jsp?orderno=5”;
RequestDispatcher rd = context.getRequestDispatcher(path);
rd.include(request, response);


Parameters specified in the query string used to create the RequestDispatcher take precedence over other parameters of the same name passed to the included servlet.
The parameters associated with a RequestDispatcher are scoped to apply only for the duration of the include or forward call.

Saturday, January 19, 2013

Servlet 3.0 ( Asynchronous Support for Web )



In Servlet 3.0 one can create Asynchronous servlets /Filters . Detach request/response from thread.

3 ways to set asyn servlets support

  • < async-supported > true < async-supported >
  • or by annotations @WebServlet(asyncSupported = true,name = "HelloAnnotationServlet", urlPatterns = {"/helloanno"})
  • or by configuring dynamically while registering servlet .. ServletRegistration.Dynamic.setAsyncSupported(true);


see an example here  https://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3 
 Important interfaces for Async web apps are 

1 . interface AsyncContext 
An AsyncContext is created and initialized by a call to ServletRequest.startAsync() or ServletRequest.startAsync(ServletRequest, ServletResponse). Repeated invocations of these methods will return the same AsyncContext instance, reinitialized as appropriate.
In the event that an asynchronous operation has timed out, the container must run through these steps:
  1. Invoke, at their onTimeout method, all AsyncListener instances registered with the ServletRequest on which the asynchronous operation was initiated.
  2. If none of the listeners called complete() or any of the dispatch() methods, perform an error dispatch with a status code equal to HttpServletResponse.SC_INTERNAL_SERVER_ERROR.
  3. If no matching error page was found, or the error page did not call complete() or any of the dispatch() methods, call complete().
  4. There are 3 flavors of dispatch() for AsyncContext.
 void dispatch()
          Dispatches the request and response objects of this AsyncContext to the servlet container.
 void dispatch(ServletContext context, java.lang.String path)
          Dispatches the request and response objects of this AsyncContext to the given path scoped to the given context.
 void dispatch(java.lang.String path)
          Dispatches the request and response objects of this AsyncContext to the given path.


Servlet 3.0 ( Dynamic registration of Servlet and Filters )

One can add / register  servlet or filters dynamically at context initialization time . ServletContext has methods to register is dynamically.

 ServletRegistration.Dynamic addServlet(java.lang.String servletName, java.lang.Class  < ? extends Servlet > servletClass )
Adds the servlet with the given name and class type to this servlet context.
 ServletRegistration.Dynamic addServlet(java.lang.String servletName, Servlet servlet)
Registers the given servlet instance with this ServletContext under the given servletName.
 ServletRegistration.Dynamic addServlet(java.lang.String servletName, java.lang.String className)


 Below is an example 

MyCtxInitializer extends ServletcontextInitializer {

void contextInitialized(ServletContextEvent sce )
{

             ServletContext ctx = sce.getServletContext();
             ServletRegistration.Dynamic dyna = 
                           sce.addServlet("newServlet " , NewServlet.class);  
             //NewServlet  must  be  a  servlet class extending Servlet
             dyna.addMapping("/OneServlet");  // map to  URL Pattern

           try{

                  Servlet xyz = ctx.createServlet (SecondServlet.class);
                 dyna.addServlet("secondServlet",xyz);
                 dyna.addMapping("/TwoServlet");

                }catch(Exception ex) {}
 
}

void contextDestroyed(ServletContextEvent sce){ }

}

Similarly for Filter and Listener .

Servlet 3.0 ( ServletContainerInitializer )

ServletContainerInitializer is an interface that provides the ability to do some task even before context intializes. It can be used to register  servlets/filters. It has annotation @HandleTypes that can tell which class type it can handle.
The class implementing ServletContainerInitializer  must be packed in a jar and a file  configuing its FQN must be kept in meta-inf/services folder .   
check   http://piotrnowicki.com/2011/03/using-servlets-3-0-servletcontainerinitializer/

SCI.onstartup() will be called before any listener is initialized.

Servlet 3.0 ( web-fragment )



metadata-complete is set for web.xml, both the annotation processing and fragments processing are disabled.


reference  https://blogs.oracle.com/swchan/entry/servlet_3_0_web_fragment


absolute-ordering in web.xml The in web.xml provides a way to specify the ordering of loading web-fragment.xml and annotation processing of web fragment. For instance,
< web-app >
...
< absolute-ordering >
               < name >A< / name >
               < others />
               < name >B</ name >
< absolute-ordering >
</ web-app > In the above example, the web fragment A would be processed first and web fragment B would be processed last.

ordering in web-fragment.xml If there is no in web.xml, then one would look at in web-fragment.xml. The details are described in section 8.2.3 of Servlet 3.0 spec.

< web-fragmen t>
    < name>A</ name>
    ...
    < ordering >
        < before >
            < others />
        </ before >
    </ ordering >
</ web-fragment > 


Wednesday, January 16, 2013

Servlet 3.0 ( Security ) ...........3

3.) Dynamic Security :
Dynamic Servlet Security Annotations @DeclareRoles("role1","role2")  & @RunAs("rolename")
above 2 annotations can be given at the time of context initialization ( while servlets are registered dynamically) 
in Servlet3.0 interface ServletRegistration.Dynamic has below imp methods 


 void setLoadOnStartup(int loadOnStartup)
          Sets the loadOnStartup priority on the Servlet represented by this dynamic ServletRegistration.
 void setMultipartConfig(MultipartConfigElement multipartConfig)
          Sets the MultipartConfigElement to be applied to the mappings defined for this ServletRegistration.
 void setRunAsRole(java.lang.String roleName)
          Sets the name of the runAs role for this ServletRegistration.
 java.util.Set setServletSecurity(ServletSecurityElement constraint)
          Sets the ServletSecurityElement to be applied to the mappings defined for this ServletRegistration.

Check web for more examples

4.) HttpOnly cookie and tags are supported ..refer  servlet 3.0 specs.
HttpOnly cookies indicate to the client that they should not be exposed to client-side scripting code (It’s not filtered out unless the client knows to look for this attribute). The use of HttpOnly cookies helps mitigate certain kinds of cross-site scripting attacks.

Servlet 3.0 ( Security ) ...........2

2. ) Use of Annotations :
@ServletSecurity & @Inherited

We can define all security configuration in DD by use of annotations while creating a servlet.
for @ServletSecurity @WebServlet must be given with attribute urlPatterns [ else it will take as per defined in DD]. example

Only guest is allowed without  any transport layer authentication check

@WebServlet(urlPattern="/secureServlet")
@ServletSecurity ( 
           @ HttpConstraint ( rolesAllowed={"guest"}, transport.Guarantee=TransportGaurantee.NONE) )

-------------------------------------------------------------------------
No user is allowed
@ServletSecurity ( EmptyRoleSemantic.DENY  )

-------------------------------------------------------------------------
All roles are allowed for all methods ; GET/POST only for guest user ; for Post transport layer needs to authenticated.
@ServletSecurity ( 
           httpConstraint ={
@HttpMethodConstraint(value="GET", rolesAllowed="guest")
@HttpMethodConstraint(value="POST", rolesAllowed="guest",                                                                                                                               transport.Guarantee=TransportGaurantee.CONFIDENTIAL)
                                    } )

-------------------------------------------------------------------------
All methods can be accessed only by role of guest ; TRACE is denied for all.
@ServletSecurity ( 
           httpConstraint ={
@HttpMethodConstraint(value="TRACE", EmptyRoleSemantic.DENY )
@HttpMethodConstraint( rolesAllowed="guest")
                                    } )
-------------------------------------------------------------------------

@Inherited

If superclass has provided annotation @ServletSecurity by default all its subclasses will inherit  its Secirity contraints by the rules defined by @Inherited annotation.
If subclass provided its own @SS constraint then it will override base classes SS constraints.

Servlet 3.0 ( Security ) ............1

In Servlet 3.0 use of annotations has made  ease to provide security. through annotations one can provide security dynamically  at the time of  servlet registration. Key features  on which servlet 3.0 security is based are listed below.
1) Authentication methods
2) Annotations
3) HttpOnly cookie (also SSO for which i have not much idea)
4) Http method Ommision tag
* Before 3.0 one has to map security  configuration in DD ( web.xml ) , but in 3.0 use of annotations is enriched. Here a snap shot of servlet security is given ( that is not sufficient but necessary to know )

1) Authentication methods: HttpServletRequest has 3 imp methods that can check / validate user .
boolean authenticate(HttpServletResponse response)
          Use the container login mechanism configured for the ServletContext to authenticate the user making this request.
 java.security.Principal getUserPrincipal()
          Returns a java.security.Principal object containing the name of the current authenticated user.
 boolean isRequestedSessionIdFromCookie()
          Checks whether the requested session ID came in as a cookie.


 boolean isRequestedSessionIdFromURL()
          Checks whether the requested session ID came in as part of the request URL.
 boolean isRequestedSessionIdValid()
          Checks whether the requested session ID is still valid.
 boolean isUserInRole(java.lang.String role)
          Returns a boolean indicating whether the authenticated user is included in the specified logical "role".
 void login(java.lang.String username, java.lang.String password)
          Validate the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext.
 void logout()
          Establish null as the value returned when getUserPrincipal, getRemoteUser, and getAuthType is called on the request.



       

Sunday, January 13, 2013

Web Listeners ( Servlets/Session)

There are 7 Listeners that are important  for servlet and session 

1 . ServletContextListener
public void contextDestroyed(ServletContextEvent arg0) {}
public void contextInitialized(ServletContextEvent arg0) {}

2. SessionListener / HttpSessionListener
sessionCreated(HttpSessionEvent evt ){}
sessionDestroyed(HttpSessionEvent evt) {}

HttpSessionActivationListener
sessionDidActivate(HttpSessionEvent ) {}
sessionWillPassivate(HttpSessionEvent ) {}


3. ServletContextAttributeListener / HttpSessionAttributeListener / ServletRequestAttributeListener 
attributeAdded()
attributeRemoved()
attributeReplaced()
in attributelistener the argument to the methods will be different as per the  interface.
for HttpSessionAttributeListener arg will be HttpSessionSessionBindingEvent.

4. HttpSessionBindingListener will be implemented by attribute
valuebound(HttpSessionBindingListener )
valueunbound(HttpSessionBindingListener )



 



Monday, January 7, 2013

Servlet 3.0

With the advent pf 3.0 drastic change has come while working with  servlets . J2EE 6  has many changes .
Few imp changes are 

  • No need of having 1 big web.xml .instaed multiple web-fragment.xml can be there
  • Dynamic registration of servlets , filters
  • Use of annotations


Here i am putting few important annotations provided by specs servlet 3.0  .


@WebServlet
(asyncSupported = false, name = "HelloServlet", urlPatterns = {"/hello"},
initParams = {@WebInitParam(name="param1", value="value1")
@WebInitParam(name="param2", value="value2")}
)
 
 public class TestServlet extends javax.servlet.http.HttpServlet { 
    ....   } 
----------------------------------------------------------  
 @WebFilter
(urlPatterns={"/myurl"},
   initParams={ @InitParam(name="mesg", value="my filter") }) 
  public class TestFilter implements javax.servlet.Filter {
        ....
        public void init(FilterConfig filterConfig) throws ServletException {   
      
   ....   }

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            ....
        }

        public void destroy() {
            ....
        }
    }
---------------------------------------------------------

@WebServletContextListener
    public class TestServletContextListener implements javax.servlet.ServletContextListener {
        ....
        public void contextInitialized(ServletContextEvent sce) {
            ....
        }

        public void contextDestroyed(ServletContextEvent sce) {
            ....
        }
    } 

---------------------------------------------------------

@MultipartConfig(location="c:\\tmp", fileSizeThreshold=1024*1024,
 maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
 
Above annotation can be used along with @WebServlet
 
For ordering of Filter  / Servlets  < absolute - ordering > tag 
should be configured in web.xml