Tuesday, December 30, 2014

JAVA CODE TO GET COMPLETE JVM DETAIL

import java.io.*;

class JVMFlight{
public static void main(String bag[]){
System.out.println("--start--");

StringWriter stringBuffer = new StringWriter();
PrintWriter out = new PrintWriter(stringBuffer);

out.println();
out.println();
out.println("    java.home: " + System.getProperty("java.home"));
out.println("    java.vendor: " + System.getProperty("java.vendor"));
out.println("    java.version: " + System.getProperty("java.version"));
out.println("    java.vm.name: " + System.getProperty("java.vm.name"));
out.println("    java.vm.version: " + System.getProperty("java.vm.version"));
out.println("    os.name: " + System.getProperty("os.name"));
out.println("    os.arch: " + System.getProperty("os.arch"));
out.println("    os.version: " + System.getProperty("os.version"));
out.println("");

System.out.println(stringBuffer.toString());
System.out.println("--end--");
}
}

Monday, December 22, 2014

Difference between sendRedirect() vs forward()

sendRedirect()

response.sendRedirect();

sendRedirect can let the servlet to move on to a completely new Application Url

Need response object to call the method.

It takes the string url path as an Argument. The value may be a complete url path or a relative path

Created new request and response object to the redirected URL

Assume that the client originally typed in:
http://www.myworld.com/com/raj/info.do

When the request comes into the servlet named “info.do”, 
the servlet calls sendRedirect() with a relative URL that does NOT start with a forward slash:
sendRedirect(“personal/Information.html”); // NO SLASH AT THE BEGINNING

The Container builds the full URL (it needs this for the “Location” header it
puts in the HTTP response) relative to the original request URL:
http://www.myworld.com/com/raj/personal/Information.html

But if the argument to sendRedirect() DOES start with a forward slash:
sendRedirect(/personal/Information.html); // SLASH AT THE BEGINNING

The Container builds the complete URL relative to the web Container itself, instead
of relative to the original URL of the request. So the new URL will be:
http://www.myworld.com/personal/Information.html

sendRedirect() change the Url as per the usage of the string value in the argument

Browser created new request object to the redirected url

.forward()

RequestDispatcher view = request.getRequestDispatcher(“Process.jsp”);
view.forward(request,response);

Need RequestDispatcher object with the string Url value as an Argument

Need to pass request, response object into the forward method

Takes the same (existing) request and response object to the redirected URL

The Url is not getting changed in the browser location bar.

JSP page vs PageContext

page

class: java.lang.Object
page represents the current servlet/jsp object.
page represents 'this'.

pageContext

class: javax.servlet.jsp.PageContext
Use to foward/redirect to particular url.
Use to include particular url.
Use to store/retrieve page level values.
It provides the following list of objects 

ServletRequest
ServletResponse
ServletContext
ServletConfig
HttpSession

application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
request = pageContext.getRequest();
response = pageContext.getResponse();
out = pageContext.getOut(); 


It provides following list of constants

public static final String APPLICATION
public static final int APPLICATION_SCOPE
public static final String CONFIG
public static final String EXCEPTION
public static final String OUT
public static final String PAGE
public static final int PAGE_SCOPE
public static final String PAGECONTEXT
public static final String REQUEST
public static final int REQUEST_SCOPE
public static final String RESPONSE
public static final String SESSION
public static final int SESSION_SCOPE

Object obj = pageContext.getAttribute("BeginnersBook", PageContext. REQUEST_CONTEXT);
Object obj = pageContext.getAttribute("BeginnersBook", PageContext. PAGE_CONTEXT);
Object obj = pageContext.getAttribute("BeginnersBook", PageContext. APPLICATION_CONTEXT);
If it finds the attribute it would assign it to Object obj else it would return Null.

pageContext.setAttribute(“userName”, “RAJ”, PageContext.APPLICATION_CONTEXT);
pageContext.removeAttribute(“userName”, PageContext.APPLICATION_CONTEXT);

Keep Visiting :)
Give your valuable Comment

EL Expression Implicit Objects/Variables


  1. pageContext
  2. pageScope
  3. requestScope
  4. sessionScope
  5. applicationScope
  6. param
  7. paramValues
  8. header
  9. headerValues
  10. cookie
  11. initParam
Keep Visiting :)
Give your valuable Comment


JSP ELEMENTS

PAGE DIRECTIVE 

         <%@ page import=”java.util.*” %>

DECLARATION

          <! int num = 10;>

SCRIPLET

          <% out.println(num) %>

EXPRESSION

          <%=num%>
          <%= pageContext.getAttribute(“foo”) %>

ACTION

          <jsp:include page=”foo.html” />

EL EXPRESSION

           ${pageContext.request.contextPath}
           ${pageContext.foo}

JSP USEBEAN

<jsp:useBean id="" class="" type="" scope="">BODY</jsp:useBean>

*id = Unique Name of the Bean (i.e. Object Name)<br>

 type (reference type) = Type of the Bean<br>

*class (object type) = Class of the Bean<br>

Scope = Scope of the Bean (i.e. page, request, session, application)<br>

i.e. Type id = new Class();


jsp:useBean =  
Create the new object of the specified class. with type specified in the type="" attribute. First it will find the object in the specified scope. and if it is not available then it will create the object and will store the object in the specified scope.  
Body gets evaluated only if new object is getting created.

<jsp:getProperty name=”beanId” property=”name” />

using get tag we can get particular property of the bean object.

<jsp:setProperty name=”beanId” property=”name” value=”Fred” />
using set tag we can set particular property value for the bean object

Keep Visiting :)
Give your valuable Comment



Sunday, December 21, 2014

Enable Disable Scripting and EL Expression in all JSP pages with only Two Line Configuration

<web-app ...>

     <jsp-confi g>
           <jsp-property-group>
           <url-pattern> *.jsp</url-pattern>
           <el-ignored>  true/false <el-ignored>
           <scripting-invalid> true/fals </scripting-invalid>
           </jsp-property-group>
     </jsp-confi g>

</web-app>

Explanation
By configuration above jsp-config element and it subelements in the web.xml file
it will enable/disable the EL expression and Scripting (scriplet,expression and declaration)
in the mentioned url jsp pages.

Give your valuable Comment
Keep Visiting :)

Swap Index of Two values in Java List

boolean idFlag = false;

if(propertyList.contains("ID")){
idFlag = true;
int index = propertyList.indexOf("ID");
Collections.swap(propertyList, index, 0);
}

if(propertyList.contains("NAME")){
int index = propertyList.indexOf("NAME");
if(idFlag){
Collections.swap(propertyList, index, 1);
}else{
Collections.swap(propertyList, index, 0);
}
}


Give your valuable comment
Keep Visiting :)

Monday, December 15, 2014

Java ArrayStack Code

interface Stack {
  public void push(int elt);
  public int pop();
  public boolean isEmpty();
}

public class ArrayStack implements Stack{
  private final int MAX_ELEMENTS = 10;
  private int[] stack;
  private int index;
  public ArrayStack() {
    stack = new int[MAX_ELEMENTS];
    index = -1;
  }
  public void push(int elt) {
    if (index != stack.length - 1) {
      index++;                                        //1
      stack[index] = elt;                             //2
    } else {
      throw new IllegalStateException("stack overflow");
    }
  }
  public int pop() {
    if (index != -1) {
      return stack[index--];
    } else {
      throw new IllegalStateException("stack underflow");
    }
  }
  public boolean isEmpty() { return index == -1; }
}

Thursday, December 11, 2014

STRUTS2 client side validation with Wild card usage

struts.xml

<struts>
    
    <constant name="struts.devMode" value="true" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
     <constant name="struts.enable.SlashesInActionNames" value="true" />

  <package name="policy" extends="struts-default">
        
               
        <global-results>
    <result name="success">/view/commons/Success.jsp</result>
    <result name="error">/view/commons/Error.jsp</result>
    <result name="*"> /view/commons/InvalidResult.jsp</result>
         </global-results>
        
       <action name="*/*/*"  class="com.policydesigner.controller.{1}.{2}CTRL" method="{3}" >                                     
            <result name="create">/view/{1}/{2}Create.jsp</result>
            <result name="update">/view/{1}/{2}Update.jsp</result>                       
            <result name="view">/view/{1}/{2}View.jsp</result>
            <result name="list">/view/{1}/{2}Search.jsp</result>            
        </action>
        
    </package>  
      
</struts>


Action class


import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.elitecore.nvsmx.policydesigner.controller.constants.Results;
import com.elitecore.nvsmx.policydesigner.model.policy.PolicyData;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * @author kirpalsinh.raj
 *
 */
public class PolicyCTRL extends ActionSupport implements   ServletRequestAware, SessionAware, ParameterAware, Preparable {

private static final long serialVersionUID = 1L;
private static final String MODULE = PolicyCTRL.class.getSimpleName(); 
private static final Logger LOG = LoggerFactory.getLogger(PolicyCTRL.class);
private HttpServletRequest request;
private Map<String, String[]> parameters;
private Map<String, Object> session;
private String message;
private PolicyData policy = new PolicyData();

/* This method will be used to set a success/failure message.
* Message will be displayed on the same respected page */
public void setMessage(String message){
this.message=message;
}

public String getMessage(){
return message;
}

/* This method gives All the request parameter in Map */
@Override
public void setParameters(Map<String, String[]> thatParameters) {
this.parameters = thatParameters;
}

/* This method gives map of all the attributes stored in current session */
@Override
public void setSession(Map<String, Object> thatSession) {
this.session =  thatSession;
}

/* This method gives the current request object*/
@Override
public void setServletRequest(HttpServletRequest thatRequest) {
this.request = thatRequest;
}

/* In each call to any method, this method will be called first.*/
@Override
public void prepare() throws Exception {
}

/* This method will be used to create the policy.
* If the create page violets the validation rules then @InputConfig(resultName="create") 
* will take the page back to create page by returning "create" string in result*/

@InputConfig(resultName="create")
public String create(){
LOG.info(MODULE, "Method called create()");
setMessage("Policy Created Successfully");
return SUCCESS;
}

/* This method will be used to update the policy.
* If the update page violets the validation rules then @InputConfig(resultName="update") 
* will take the page back to update page by returning "update" string in result*/
@InputConfig(resultName="update")
public String update(){
setMessage("Policy Updated Successfully");
return SUCCESS;
}

public String view(){
setMessage("Viewing Policy");
return Results.VIEW;
}

public String delete(){
setMessage("Policy deleted Successfully");
return SUCCESS;
}


public String initCreate(){
setMessage("Create Policy");
System.out.println("inside initCreate()");
return Results.CREATE;
}

public String initUpdate(){
setMessage("Update Policy");
return Results.UPDATE;
}

public String list(){
return Results.LIST;
}

public PolicyData getPolicy() {
return policy;
}

public void setPolicy(PolicyData policy) {
this.policy = policy;
}

public void validate() {  
System.out.println("Method called validate()");
}
}



VALIDATION FILE

PolicyCTRL-validation.xml
Note: this file must be place at the same location where PolicyCTRL.java file resides

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
    
<validators>

<field name="policy.name">
<field-validator type="requiredstring">
<message key="error.policy.name.required"/>
</field-validator>

<field-validator type="stringlength">
<param name="minLength">2</param>
<param name="maxLength">16</param>
<param name="trim">true</param>
<message key="error.length.field" />
</field-validator>
</field>


</validators>

JSP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page import="com.policydesigner.model.policy.PolicyData"%>

<html>
<head>
<title>Create</title>
<s:head/>
</head>

<body> 
<center>
<div class="msg" >
<s:form action="policy/Policy/create"  validate="true" id="createForm"   name="createForm">
<table>
<tr><td><s:textfield name="policy.name" id="name"  label="Name" /></td></tr>
<tr><td> <s:submit/> </td></tr>
</table>
</s:form>
</div>
</center>  
</body>


</html>

Take Care
Note: see the action attribute of s:form tag 
<s:form action="policy/Policy/create"  validate="true" id="createForm"   name="createForm">

in this tag action attribute contains the values policy/Policy/create 
this will be map with the wild cards used in the struts.xml file.
and remember to not begin the action attribute value with slash "/"

not do this :  action="/policy/Policy/create" because it will make a call to the validate method of the respected action class. means it will load the page.

and action ="policy/Policy/create" : this will not load the page and it will perform the client side validation withe the generated java script. 

:) Keep Visiting :)


Wednesday, November 26, 2014

Define Error page in Java web App



Page which will display the Error detail : ErrorPage.jsp

<%@ page isErrorPage=”true” %>
<html>
<body>
<strong>I am Error Page.</strong><br>
Error is : ${pageContext.exception}<br>
</body>
</html>

Page which will cause Error : Hello.jsp

<%@ page errorPage=”ErrorPage.jsp” %>
<html>
<body>
<%=1/0%>
</body>
</html>

Web.xml

<error-page>
          <error-code>404</error-code>
           <location>/jsp/ErrorPage.jsp</location>
</error-page>

<error-page>
          <error-code>java.lang.ArithMeticException</error-code>
           <location>/jsp/ErrorPage.jsp</location>
</error-page>

How to define Error Page in web.xml


Exception Based

<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/ExceptionError.jsp</location>
</error-page>

HTTP status code based 

<error-page>
<error-code>404</error-code>
<location>/NotFound.jsp</location>
</error-page>

Friday, November 21, 2014

RADIUS protocol's one line Question/Answer

RADIUS : Remote Authentication Dial In User Service

RADIUS RFC'S : 2865, 2866

0)  Radius is Stateless protocol, Extensible protocol

1) Radius supports protocol for Authentication are : PAP,CHAP,PPP,UNIX-LOGIN

2) Radius Authentication port : 1812

3) Radius Accounting Port : 1813

4) Radius uses UDP

5) Radius Packet Format

6) Code : 1 Octet,   Identifier : 1 Octet,  Length : 2 Octet, Authenticator : 16 Octet

7) Length : Min 20 and Max 4096

8) Radius Attributes
   
CodeAttributes
1User-Name
2User-Password
3CHAP-Password
4NAS-IP-Address
5NAS-Port
6Service-Type
7Framed-Protocol
8Framed-IP-Address
9Framed-IP-Netmask
10Framed-Routing
11Filter-Id
12Framed-MTU
13Framed-Compression
14Login-IP-Host
15Login-Service
16Login-TCP-Port
17(unassigned)
18Reply-Message
19Callback-Number
20Callback-Id
21(unassigned)
22Framed-Route
CodeAttributes
23Framed-IPX-Network
24State
25Class
26Vendor-Specific
27Session-Timeout
28Idle-Timeout
29Termination-Action
30Called-Station-Id
31Calling-Station-Id
32NAS-Identifier
33Proxy-State
34Login-LAT-Service
35Login-LAT-Node 3
36Login-LAT-Group
37Framed-AppleTalk-Link
38Framed-AppleTalk-Network
39Framed-AppleTalk-Zone
40-59(reserved for accounting)
60CHAP-Challenge
61NAS-Port-Type
62Port-Limit
63Login-LAT-Port

9) Diameter Protocol is double than Radius

10) Diameter works on TCP or SCTP protocol

11) Diameter uses Transport level security IPSEC , TLS




Wednesday, November 19, 2014

Include directive vs jsp:include action


Include directive

include directive should be use to include the static contents
which is not getting changed frequently.

It includes the content at the translation time

example
<%@include file="/jsp/core/includes/common/Footer.jsp" %>

<jsp:include> action tag

include action tag is used to include the content which is getting changeg frequently

it includes the content at the runtime

example
<jsp:include page="/jsp/data/dynamic.jsp"/>

Tuesday, November 18, 2014

HTTP Status code Range


1) 100 to 199 (Informational)

This range include the Informational codes about the kind of action client should use or respond

2) 200 to 299 (Request success)

This range include the success codes that indicates the success of the request

3) 300 to 399 (Request File is moved)

This range include the code to indicate that the particular document/file location is moved to another location

4) 400 to 499 (Client side Error)

This range codes indicates the error generated by the client side

5) 500 to 599 (Server side Error)

This range codes indicates the error generated by the server side

How to use

To set the status code one should  use the predefined constants for the respective status code using the method :  response.setStatus(response.SC_ABC_XYZ);


Status Code
Purpose
100-199
Informational
200-299
Request was successful
300-399
Request file has moved.
400-499
Client error
 500-599
Server error.



Some Status Code with their Short Meaning

100 : Continue

200 : OK
202 : Accepted
204 : No Content
205 : Reset Content

301 : Moved Permanentely
302 : Found
303 : See Other
304 : Not Modified


400 : Bad Request
: Bad syntax of the request

401 : Unauthorized
: client tries to access the password protected resource, 

403 : Forbidden
: server refuse to supply the requested resource

404 : Not Found
: when the requested resource is not found on the server.

405 : Method Not Allowed
: put,trace,delete,options if server doesnt support the method requested.

415 : Unsupported Media Type
: request contain the document that the server doesnt know how to handle.

417 : Expectation Failed
: request ask to process some document with 100 code in header, in this request response
 server can respond with code 417


500 : Internal Server Error
: When Server is Confused.

501 : Not Implemented
: doesnt support the functionality to fullfill the request.

503 : Service Unavailable
: When server is not able to fullfill the request service. because of overloading or maintenance or etc




Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...