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 :)


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...