Thursday, 17 August 2017

Which is the best framework for generating html from java code

Are you looking for answers of any of the following questions

  • Building HTML in Java code only
  • Better Html Builder in java
  • Building HTML in Java code only
  • HTML code in Java class
  • Is it a good practice to write Java methods to return HTML strings that will be returned to the display/presentation layer
  • Which is the best opensource java library/jar for html reporting
Then please have a look at webfirmframework. When you can well maintain the code it's always fine to return html by even a method.



Buy me a chocolate if I'm the first one brought it in your attention!

Saturday, 31 August 2013

How to trim all strings in a bean (pojo/value object) in Java

(Check out these blogs to improve your java skills : top-10-most-common-java-development-mistakes written by Mikhail Selivanov)

Forms are used everywhere in a web/desktop/other applications. In these forms, the user may enter values starting and/or ending with spaces. But we may not need theses spaces at the starting and ending, so we may want to trim it. As we know, we may simply use a trim() method to trim a string. But, what if we want to trim all strings in a bean/pojo/value object. Suppose, consider a form having some fields, first name, last name, address etc... The user may enter the values as

First Name :

Last Name :

Address : 

The values have spaces in the beginning and ending. So, to write code to trim every string separately is a kind of messing sometimes.

Here is a method which can trim all strings in a bean/pojo/value object (Only the strings will be trimmed, so it doesn't matter if it contains data types other than strings). Before that let us make a value object (POJO/bean) for these fields.
Consider it as a profile information :

So


package com.company.project.valueobjects;

import java.io.Serializable;


public class Profile implements Serializable {


private static final long serialVersionUID = 6378955155265367593L;

private String firstName;
private String lastName;
private String address;
private double latitude;
private double longitude;

public String getFirstName() {

return firstName;
}

public void setFirstName(String firstName) {

this.firstName = firstName;
}

public String getLastName() {

return lastName;
}

public void setLastName(String lastName) {

this.lastName = lastName;
}

public String getAddress() {

return address;
}

public void setAddress(String address) {

this.address = address;
}

public double getLatitude() {

return latitude;
}

public void setLatitude(double latitude) {

this.latitude = latitude;
}

public double getLongitude() {

return longitude;
}

public void setLongitude(double longitude) {

this.longitude = longitude;
}
}


And the utility class is as follows :


package com.company.project.common.helpers;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 
 * <b>File Name :</b> <i>BeanUtils.java</i> <br>
 * <b>Description :</b>
 * <p>
 * This class contains the activities of skill program. <br/>
 * <br/>
 * <b>Copyright :</b> Copyright© yyyy description
 * </p>
 * <h1>Version History :</h1>
 * 
 * Date : 20-06-2013<br/>
 * Description : First Draft
 * 
 * @version 1.0.0.1
 * @since 1.0.0.0.1
 * @author visruth
 * 
 */
public class BeanUtils implements Serializable {

/**
* This method trims all String variables defined in the bean if they have
* corresponding getter setter methods. <br/>
* Eg : BeanUtils beanUtils=new BeanUtils();<br/>
* StudentVO studentVO=new StudentVO();<br/>
* studentVO.setName("   foo   ");<br/>
* studentVO.setAddress("   bar   ");<br/>
* beanUtils.trimAllStrings(studentVO);<br/>
* System.out.println(studentVO.getName());//prints foo<br/>
* System.out.println(studentVO.getAddress());//prints bar<br/>

* @param beanObject
* @throws Exception
*             If a variable has its getter method defined but not setter
*             method will throw NoSuchMethodException instance as
*             Exception.
* @author visruth
*/
public void trimAllStrings(Object beanObject) throws Exception {
Exception noSuchMethodException = null;
boolean throwNoSuchMethodException = false;
if (beanObject != null) {

Method[] methods = null;

try {
methods = beanObject.getClass().getMethods();
} catch (SecurityException e) {
throw new Exception(e);
}

if (methods != null) {

for (Method method : methods) {

String methodName = method.getName();

if (!methodName.equals("getClass")) {

String returnType = method.getReturnType().toString();
String commonMethodName = null;

if (methodName.startsWith("get")
&& "class java.lang.String".equals(returnType)) {

commonMethodName = methodName.replaceFirst("get",
"");
String returnedValue = null;

try {
returnedValue = (String) method
.invoke(beanObject);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw e;
} catch (InvocationTargetException e) {
e.printStackTrace();
throw e;
}

if (returnedValue != null) {

StringBuilder setterMethodName = new StringBuilder();
setterMethodName.append("set");
setterMethodName.append(commonMethodName);
Method setterMethod = null;

try {
setterMethod = beanObject
.getClass()
.getMethod(
setterMethodName.toString(),
String.class);
if (setterMethod != null) {
setterMethod.invoke(beanObject,
(returnedValue.trim()));
}
} catch (SecurityException e) {
e.printStackTrace();
throw e;
} catch (NoSuchMethodException e) {
e.printStackTrace();
if (!throwNoSuchMethodException) {
noSuchMethodException = e;
}
throwNoSuchMethodException = true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw e;
} catch (InvocationTargetException e) {
e.printStackTrace();
throw e;
}
}
}
}
}
}
}

if (throwNoSuchMethodException && noSuchMethodException != null) {
throw noSuchMethodException;
}
}

/**
* converts an Object to String

* @param object1
* @return String
* @author visruth
*/
public String toString(Object object) {
if (object != null) {
return object.toString();
} else {
return null;
}
}

}

To test :


public static void main(String[] args) {
BeanUtils beanUtils = new BeanUtils();

ProfileVO profileVO = new ProfileVO();

profileVO.setFirstName("      Visruth         ");
profileVO.setLastName("       CV              ");
profileVO.setAddress("        Address         ");

System.out.println(profileVO.getFirstName());
System.out.println(profileVO.getLastName());
System.out.println(profileVO.getAddress());

try {
beanUtils.trimAllStrings(profileVO);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(profileVO.getFirstName());
System.out.println(profileVO.getLastName());
System.out.println(profileVO.getAddress());
}


And the output : 


      Visruth         
       CV              
        Address         
Visruth
CV
Address


Please share if you know any other utility methods which is not available as a ready-made component....










Wednesday, 25 July 2012

Example for Outer class reference

/*
 * This is a real time example for out class reference
 *
 */
package tcase;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author visruth cv
 */
public class Outer extends JFrame {

    private String outerClassField = "some value1";

    public Outer() {
        super("title of the frame");
        setSize(600, 600);
        setLayout(new FlowLayout());
        JButton b = new JButton("Ok");
        b.addActionListener(new ActionListener() {
            private String outerClassField = "some value2";
            public void actionPerformed(ActionEvent e) {
                System.out.println(Outer.this.outerClassField); //line 29
                System.out.println(outerClassField); //line 30
            }
        });
        add(b);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Outer();
    }
}
The line no.29 gives the current reference of outer class Outer.
Line no. 29 prints as 'some value1' and line no. 29 prints as 'some value2'

Why is Class.this (ClassName.this) used?


//What is Class.this

package tcase;

/**
 *
 * @author visruth cv
 *
 */
public class First {

    final String visru;
    final Second second;

    First(String visru) {
        this.visru = visru;
        this.second = new Second(visru + "-second");
    }

    class Second {

        final String visru;
        final Third third;

        Second(String visru) {
            this.visru = visru;
            this.third = new Third(visru + "-third");
        }

        class Third {

            final String visru;
            final Fourth fourth;

            Third(String visru) {
                this.visru = visru;
                this.fourth = new Fourth(visru + "-fourth");
            }

            class Fourth {

                final String visru;

                Fourth(String visru) {
                    this.visru = visru;
                }

                void toPrint() {
                    System.out.println("By Current Obect: " + this.visru);
                    System.out.println("First: " + First.this.visru); // current object of class First
                    System.out.println("Second: " + Second.this.visru); // current object of class Second
                    System.out.println("Third: " + Third.this.visru); // current object of class Third
                    System.out.println("Fourth: " + Fourth.this.visru); // current object of class Fourth

                    System.out.println("below prints addresses");

                    System.out.println("Address of current Obect: " + this);
                    System.out.println("Address of First: " + First.this); // current object of class First
                    System.out.println("Address of Second: " + Second.this); // current object of class Second
                    System.out.println("Address of Third: " + Third.this); // current object of class Third
                    System.out.println("Address of Fourth: " + Fourth.this); // current object of class Fourth
                }
            }
        }
    }

    static public void main(String[] args) {      
        final First first = new First("first");
        first.second.third.fourth.toPrint();
    }
}



This gives output as follows (printing addresses may vary in each execution).

By Current Obect: first-second-third-fourth
First: first
Second: first-second
Third: first-second-third
Fourth: first-second-third-fourth
below prints addresses
Address of current Obect: tcase.First$Second$Third$Fourth@15f5897
Address of First: tcase.First@b162d5
Address of Second: tcase.First$Second@1cfb549
Address of Third: tcase.First$Second$Third@186d4c1
Address of Fourth: tcase.First$Second$Third$Fourth@15f5897


It's a good example....
`Class.this` means that the current object is referred from that particular class.
Here,
`First.this` means the current object of the class First.
`Second.this` means the current object of the class Second.
`Third.this` means the current object of the class Third and so on.
And also, see the relation of all addresses.
The two objects (given as bold above) are having the same memory addresses (15f5897).
Why it happened so,??., because
the method toPrint is called under the reference of Class Fourth. Therefore, the current object at the point is the object of the class Fourth. So,
these two lines
System.out.println("By Current Obect: " + this.visru); and
System.out.println("Address of Fourth: " + Fourth.this);
print the same output as 'first-second-third-fourth' in those prints.

if anybody has the doubts, please comment on the post.....