Thursday, 30 June 2016

What is the structure of Modern Servlet Web Applications ?


A web application exists as a structured hierarchy.
The root of this hierarchy serves as a document root.

WEB-INF
  • This directory contains all things related to the application that aren’t in the document root of the application.
  • No file contained in the WEB-INF directory may be served directly to a client by the container.
  • But, A servlet can access contents of WEB-INF using :
    • ServletContext.gerResource()
    • ServletContext.getResourceAsStream()

Contents under WEB-INF
  • /WEB-INF/web.xml
    Deployment descriptor
  • /WEB-INF/classes/*
    Directory for servlet and utility classes
    The classes in this directory are available to the application class loader.
  • /WEB-INF/lib/*.jar
    contains JAR files (Java ARchive)
    • JAR contain servlets, beans, and utility classes useful to the web application.
    • The web application class loader
      • can load class from any of these JAR files.
      • loads classes from the WEB-INF/classes first, and then from JARs in the WEB-INF/lib directory

forward vs. include


Forward
  • Forwards a request from a Servlet to another resource (Servlet, JSP file, or HTML file) on the server.
  • forward should be called before the response has been committed to the client (before response body output has been flushed)

Include
  • Includes the content of a resource (servlet, JSP page, HTML file) in the response.
  • The included servlet cannot change the response status code or set headers.

Tuesday, 28 June 2016

What will happen if forward is called after the response already has been committed ?


forward should be called before the response has been committed to the client
(before response body output has been flushed)


If the response already has been committed, this method throws an IllegalStateException

How to use RequestDispatcher to include or forward to a web resource ?


ServletContext.getRequestDispatcher(String path)
  • A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response.
  • The resource can be dynamic or static.
  • The path must begin with a "/" and is interpreted as relative to the current context root.

ServletRequest.getRequestDispatcher(String path)
  • The pathname specified may be relative, although it cannot extend outside the current servlet context.
  • If the path begins with a "/" it is interpreted as relative to the current context root.

Monday, 27 June 2016

How and when life cycle methods are invoked ?


Servlet interface provide life-cycle methods.

1. init() : The servlet is constructed, and then initialized with the init method.
2. service() : Any calls from clients to the service method are handled.
3. destroy() : The servlet is taken out of service, then destroyed with the destroy method.
    Then garbage collected and finalized.

It also provides :
4. getServletConfig() : used to get any startup information
5. getServletInfo() : allows the servlet to return basic information like, author, version, and copyright

How to access values and resources and to set object attributes within 3 scopes ?


Request scope

Methods in ServletRequest interface
  • Object getAttribute(String name)
    Returns the value of an attribute from request or null if attribute is not present
  • Enumeration getAttributeNames()
    Returns an Enumeration containing the names of the attributes
  • ServletInputStream getInputStream()
    Retrieves the body of the request as binary data
  • setAttribute(String name, Object o)
    Stores an attribute in current request
    Most often used in conjunction with RequestDispatcher
  • removeAttribute(String name)
    Removes an attribute from current request
    Not needed as attributes only persist as long as the request is being handled.


Session scope
Methods in HttpSession interface 
Works same way as ServletRequest but associated to Session
  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • setAttribute(String name, Object o)
  • removeAttribute(String name)



Context scope
Methods in ServletContext interface
Works same way as ServletRequest but associated to the entire Application
  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • setAttribute(String name, Object o)
  • removeAttribute(String name)

ServletContext also provides direct access to the hierarchy of static content documents that are part of the web application, including HTML, GIF, and JPEG files.
  • getResource(String resource)
    Example : getResource("/index.jsp") will return JSP source code
  • getResourceAsStream(String resource)

What will happen if you call sendRedirect after committing the response ?


After using sendRedirect() method, the response should be considered to be committed.

If the response has already been committed, this method throws an IllegalStateException.

How to redirect an HTTP request to another URL ?


Method in HttpServletResponse interface
  • sendRedirect(String location)
    sends a temporary redirect response to the client using the specified redirect location URL
    .
    It can accept relative URLs ( without a leading '/'
    ) which must converted to the absolute URL by Servlet container
After using this method, the response should be considered to be committed.
If the response has already been committed, this method throws an IllegalStateException.

How to acquire a binary stream for the response ?


Method of ServletResponse interface
  • ServletOutputStream getOutputStream()
    Returns ServletOutputStream for writing binary data in the response.


    Calling flush() on the ServletOutputStream commits the response.

How to acquire a text stream for the response ?


Method of ServletResponse interface
  • PrintWriter getWriter()
    Returns a PrintWriter object that can send character text to the client


    Calling flush() on the PrintWriter commits the response.

How to set the content type of the response ?


Method of ServletResponse interface
  • setContentType(String) 
    • Sets the content type of the response being sent to the client 
    • It may include character encoding as well. 
    • Example : text/html; charset=ISO-8859-4

What will happen if headers are set after the response is committed ?


Headers must be set before the response is committed.

If headers are set after the response is committed, that will be ignored by the servlet container

How to set a HTTP response header ?


Methods of the HttpServletResponse interface
  • setHeader : sets a header with a given name and value
    If header name already exists, it will replace all the n existing values with 1 new value
  • addHeader : adds a header value to a given name
  • setIntHeader : sets a int type header
  • setDateHeader : sets a Date type header
  • addIntHeader : adds a int type header
  • addDateHeader : adds a Date type header

* Headers must be set before the response is committed.

How to retrieve HTTP request header information ?


Methods of HttpServletRequest interface
  • getHeader : returns a header value by given header name
    If there are multiple headers with the same name, it returns the first head in the request.
  • getHeaders : returns all the header values associated with the given header name (Enumeration of Strings)
  • getHeaderNames : returns names of all the headers
  • getIntHeader : returns header value (String) into int format
    If it cannot translate the header value to an int, a NumberFormatException is thrown.
  • getDateHeader : returns header value (String) into Date format
    If it cannot translate the header to a Date object, an IllegalArgumentException is thrown.

Sunday, 26 June 2016

How to retrieve a servlet initialization parameter ?


Methods of ServletConfig interface
  • public String getInitParameter(String)returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.
     
  • public Enumeration getInitParameterNames()returns the names of the servlet’s initialization parameters as an Enumeration of String objects.

How to retrieve HTML form parameters from the request ?


All form data from both the query string + post body are aggregated into the request parameter set.
The parameters sent in URI query string are stored by the servlet container as a set of name/value pairs.


Multiple parameter values can exist for any given parameter name. (Like, a=123&a=567)
 

Methods in ServletRequest interface
  • getParameter : returns value for a given parameter
  • getParameterNames : returns array of all names of parameters (No value)
  • getParameterValues : returns an array of String objects containing all the parameter values associated with a parameter name

Scenario : If a request is made with :

  • A query string of a=hello
    and
  • A post body of a=goodbye&a=world
The resulting parameter set would be ordered a=(hello, goodbye, world)

What are the triggers that cause a browser to use a HTTP method ?


HTTP POST
  • Allows the client to send data of unlimited length to server
  • Usage : Useful when sending sensitive information like, Credit card numbers

HTTP GET

  • Retrieves whatever information sent in Request URI

HTTP HEAD

  • It is a GET request that returns no body in the response, on the request header fields.
  • The client sends a HEAD request when it wants to see only the headers of a response, such as Content Type or Content-Length.
    • This method counts the number of output bytes in the response to set the Content-Length header accurately.
  • Usage :
    • can be used for obtaining meta-information about the entity implied by the request without transferring the entity-body itself.
    • often used for testing hypertext links for validity, accessibility, and recent modification.

What methods I should ovveride in a servlet ?


For creating a website, create a HTTP servlet.
  • Extend HttpServlet (an Abstract class)
  • Override at least one method (usually one of the following) :
    • doGet : to support HTTP GET requests
    • doPost :  for HTTP POST requests
    • doPut :  for HTTP PUT requests
Don't override service method, as it handles HTTP requests by dispatching them to handler methods for each type of HTTP request.


Study material for SCWCD

What are the common Exception handling rules ?


Exception handling rules


#1. Prefer exceptions over Returning Error Codes
if (deletePage(page) == E_OK) {
   if (registry.deleteReference(page.name) == E_OK) {
     ....
   } else {
      .....
   }
} else {
   ....
}

try {
   deletePage(page);

   registry.deleteReference(page.name);
} catch (Exception e) {
    logger.log(e.getMessage());
}



#2. Extract Try/Catch Blocks
Example. More better than above - 1 method with core logic , other with try/catch block only
try {
   deletePageAndAllReferences(page);
} catch (Exception e) {
   logError(e);
}


private void deletePageAndAllReferences(Page page) throws Exception {….}


#3. Use Unchecked Exceptions
Checked exceptions :
  • increases error handling in many parts of our system
  • Breaking Encapsulation
So, Use checked exceptions only when :
  • If the caller knows & wants how to handle it
  • Dealing with Critical Systems or libraries

#4. Don’t Eat the Exception
try {
  ...
} catch (Exception ex) { }


try {
   ...
} catch (Exception ex) {
   ex.printStackTrace();
}



#5. Resist Temptation to write a Single Catchall
Single handler for many errors reduces the reliability of your program.

#6. Always use Catchall after handling known ones
You may not be sure that you handled all possible exceptions, so provide a default handler (catchall)

#7. Don’t Return NULL
Returning null needs its handling at all the places, which makes code awful.
Solution
  • Return a special case object
  • Wrap with another method that throws exception

#8. Don’t Pass NULL
Passing NULL should be handled inside the method or NullPointerException will be thrown
Unless the used API is passing NULL, you should avoid it.

What are the common Method writing rules ?


METHOD WRITING RULES

#1. Small
Method should be :
  • Small
  • A screen-full or 
  • should hardly ever be 20 lines long.
Example
public static String renderPage (PageData pageData, boolean isSuite) throws Exception {
   if (isTestPage(pageData))
         includeSetupAndTeardownPages(pageData, isSuite);
   return pageData.getHtml();
}


#2. Do One Thing
  • Method should do one thing only and should do it well.

#3. One Level of Abstraction per Method
  • Don't mix levels of abstraction within a method 
    • Confusion between a essential and detail

#4. Avoid switch statements
  • It violates "Do One Thing" rule
  • Convert switch statement into Abstract Factory
  • Always not possible but Try to get rid of Switch statements

#5. Use descriptive names
Consider : 
  • It may take time to choose a good name
  • Name can be long

#6. Minimize method arguments
  • Pass the objects

#7. Have no side effects
Example : Below method name is checkPassword but it also initializing session
public boolean checkPassword(String userName, String password) {
  User user = UserGateway.findByName(userName);
  if (user != User.NULL) {
     String codedPhrase = user.getPhraseEncodedByPassword();
     String phrase = cryptographer.decrypt(codedPhrase, password);
     if ("Valid Password".equals(phrase)) {
          Session.initialize();
          return true;
     }
  }
  return false;
}


Problem. If someone doesn't know it is also initializing session, and calls it just for checking password only, it may cause data loss.

Solution. If we can't divide it, change its name to : checkPasswordAndInitializeSession


#8. Separate Command from Query
Methods should either do something or answer something
if (set("username", "unclebob"))...

if (attributeExists("username")) {
  setAttribute("username", "unclebob");
  ...
}


What are the common Naming rules ?


NAMING RULES

#1. Use Intention-Revealing Names
int d; // elapsed time in days
int elapsedTimeInDays;

#2. Avoid Disinformation
Use below name only if this variable is a List type
accountList

#3. Long names which can take long time to differentiate
XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings

#4. Use searchable names
Karakter
7
DAYS_PER_WEEK
week



#5. Make Meaningful Distinction
public static void copyChars(char a1[], char a2[]) {
  for (int i = 0; i < a1.length; i++) {
     a2[i] = a1[i];
  }
}


public static void copyChars(char[] source, char[] destination) {
   for (int i = 0; i < source.length; i++) {
      destination[i] = source[i];
   }
}



#6. Use Pronounceable Names
genymdhms

#7. Avoid Encodings
Example : Prefixing member variable with 'm_'
m_countryCode

Example : Interfaces & Implementation
Interface IShapeFactory {...}
Class ShapeFactory implements IShapeFactory {...}


Interface ShapeFactory {...}
Class ShapeFactoryImpl implements ShapeFactory {...}



#8. Avoid Mental Mapping
String url;
instead of 
String r;

#9. Don’t Be Cute
DeleteItems()
instead of
HolyHandGrenade()

dispatchRequest()
instead of
edenyFelRequest()

* Names based on cultural base or sense of humor will only be remembered by people who know it


#10. Pick One Word per Concept
Example : using fetch(), retrieve(), and get() in the same layer
* Caller will be confused which method to call ?


#11. Don’t Add Extra-free Context
Example : Prefixing every class with MBS in a Mobile Banking System
class MBSCustomer
class MBSSimCard

Saturday, 25 June 2016

What is GoF (Gang of Four) ?


The authors of book "Design patterns" are known as "Gang of Four" :

What is the GRASP principle ?


General Responsibility Assignment Software Principles
  • Guidelines for assigning responsibility to classes and objects in OO design.
  • uses various patterns :
    • Controller
      • A non-user interface object responsible for receiving or handling a system event.
    • Creator
      • Factory Pattern (GoF)
    • Indirection
      • Proxy Pattern (GoF)
    • Information Expert
      • Information Hiding
    • High Cohesion
    • Low Coupling
    • Polymorphism
    • Protected Variations
      • Open Close Principle of SOLID principle
    • Pure Fabrication
      • System as a set of related software functionalities that can be reused for different purposes

'IS A' vs. 'HAS A'


has-a
  • A composition relationship where one object "belongs to" another object and behaves according to the rules of ownership.

is-a 
  • A relationship between abstractions (e.g. types, classes), where one class A is a subclass of another class B

Favor Composition over inheritance

What are the Software Design considerations ?


Software Design considerations
  • Compatibility
  • Extensibility
  • Fault-tolerance
  • Maintainability
  • Modularity
  • Reliability
  • Reusability
  • Robustness
  • Security
  • Usability
  • Performance
  • Portability
  • Scalability
  • Availability
  • Recoverability
  • Monitorability

What are the principles of Software Design ?


Software design principles
  • SOLID
  • GRASP
  • DRY (Don’t Repeat Yourself)
  • KISS (Keep It Simple and Stupid)
  • YAGNI (You Aren’t Gonna Need It)
  • If it ain’t broken, don’t fix it !
 

What are the common practices for improving SLRs ?


Redundancy
  • Load Balancing
  • Failover
  • Clustering

Availability
  • Active replication : performed by processing the same request at every replica
  • Passive replication : involves processing each single request on a single replica and then transferring its resultant state to the other replicas


Performance
  • Increase system capacity
  • Increase computational efficiency 

Extensibility
  • Clearly define the scope in the service-level agreement
  • Anticipate expected changes
  • Design a high-quality object model

Scalability
  • Vertical Scalability : more processors, memory, and disks
  • Horizontal Scalability : more servers

Reliability
  • Increase computational efficiency
  • Transactions
  • Monitor and restart
  • Redundancy
  • Degradation
  • Bound execution time

What is the impact of dimensions on SLRs (Service level requirements) ?


Capacity
  • Raw power in an element - CPU, fast network connection, or large storage capacity
  • increased through vertical scaling
  • can improve performance, availability, and scalability

Redundancy
  • Multiple systems that work on the same job - Load balacing
  • increased through horizontal scaling
  • can increase performance, reliability, availability, extensibility, and scalability
  • can decrease manageability and security

Modularity
  • Dividing a computational problem into separate elements
  • can increase scalability, extensibility, maintainability, and security
  • can decrease performance, reliability, availability, and manageability

Tolerance
  • Time available to fulfill a request from a user
  • can increase performance, scalability, reliability, and manageability

Workload
  • Computational work being performed at a particular point within the system
  • consumes available Capacity
  • can increase performance, scalability, and availability

Heterogeneity
  • Diversity in technologies that is used within a system
  • can increase performance and scalability
  • can decrease performance, scalability, availability, extensibility, manageability, and security