Monday, 29 June 2015

Simple CRUD with JSF and Hibernate

Leave a Comment
This example shows how to develop a simple CRUD (Create Read Update Delete) by using JSF2, Hibernate and MySQL.
This application lets you manage customer database such as add new customer and update/delete customer info.

These two frameworks can be used for different purposes according to the usefulness and power of individual frameworks.

  1. JSF can be used to implement presentation layer.
  2. Hibernate can be used in the business logic tier to manage business objects, resource management.
You may read :  CRUD with Mysql in Java

First, lets create the database and table for customer.

CREATE DATABASE IF NOT EXISTS jsfhibercrud;
USE jsfhibercrud;
--
-- Definition of table `customer`
--
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `cust_id` int(10) unsigned NOT NULL auto_increment,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  `dob` date NOT NULL,
  PRIMARY KEY  (`cust_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Now create a netbean project using hibernate and jsf framework. While creating project choose or connect to your created database.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/jsfhibercrud</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">pass</property>
    <mapping resource="com/geekonjava/entity/Customer.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
After that add three packages named com.geekonjava.entity, com.geekonjava.util and com.geekonjava.dao.
Interested in AndroidCRUD using JSON in Android
Now generate POJOs using reverse engineering at your entity package.

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="jsfhibercrud"/>
  <table-filter match-name="customer"/>
</hibernate-reverse-engineering>

Customer.java

package com.geekonjava.entity;
import com.geekonjava.dao.CustomerDao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
/**
 * @author geekonjava
 */
@ManagedBean
@SessionScoped
public class Customer implements java.io.Serializable {
 
    private Integer custId;
    private String firstName;
    private String lastName;
    private String email;
    private Date dob;
    private String sd, msg, selectedname;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
    public Customer() {
    }
 
    public Customer(String firstName, String lastName, String email, Date dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.dob = dob;
    }
 
    public String getSd() {
        return sd;
    }
 
    public void setSd(String sd) {
        this.sd = sd;
    }
 
    public Integer getCustId() {
        return this.custId;
    }
 
    public void setCustId(Integer custId) {
        this.custId = custId;
    }
 
    public String getFirstName() {
        return this.firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return this.lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public String getEmail() {
        return this.email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public Date getDob() {
        return this.dob;
    }
 
    public void setDob(Date dob) {
        this.dob = dob;
    }
 
    public String getMsg() {
        return msg;
    }
 
    public void setMsg(String msg) {
        this.msg = msg;
    }
 
    public String getSelectedname() {
        return selectedname;
    }
 
    public void setSelectedname(String selectedname) {
        this.selectedname = selectedname;
    }
 
    public void saveCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.addCustomer(this);
        this.msg = "Member Info Saved Successfull!";
        clearAll();
    }
    public void updateCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.updateCustomer(this);
        this.msg = "Member Info Update Successfull!";
        clearAll();
    }
    public void deleteCustomer() {
        CustomerDao dao = new CustomerDao();
        dao.deleteCustomer(custId);
        this.msg = "Member Info Delete Successfull!";
        clearAll();
    }
 
    public List<Customer> getAllCustomers() {
        List<Customer> users = new ArrayList<Customer>();
        CustomerDao dao = new CustomerDao();
        users = dao.getAllCustomers();
        return users;
    }
 
    public void fullInfo() {
        CustomerDao dao = new CustomerDao();
        List<Customer> lc = dao.getCustomerById(selectedname);
        System.out.println(lc.get(0).firstName);
        this.custId = lc.get(0).custId;
        this.firstName = lc.get(0).firstName;
        this.lastName = lc.get(0).lastName;
        this.email = lc.get(0).email;
        this.dob = lc.get(0).dob;
        this.sd = sdf.format(dob);
    }
 
    private void clearAll() {
        this.firstName = "";
        this.lastName = "";
        this.sd = "";
        this.email = "";
        this.custId=0;
    }
}

Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jul 5, 2013 10:57:32 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="com.geekonjava.entity.Customer" table="customer" catalog="jsfhibercrud">
        <id name="custId" type="java.lang.Integer">
            <column name="cust_id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="45" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="45" not-null="true" />
        </property>
        <property name="email" type="string">
            <column name="email" length="45" not-null="true" />
        </property>
        <property name="dob" type="date">
            <column name="dob" length="10" not-null="true" />
        </property>
    </class>
</hibernate-mapping>
In util package add a HibernateUtil.java file and change this as follows-

Are you know advanced HibernateHibernate CRUD example using HQL

HibernateUtil.java

package com.geekonjava.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
  
public class HibernateUtil {
  
    private static final SessionFactory sessionFactory=buildSessionFactory();
  
   public static SessionFactory buildSessionFactory(){
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
  
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
This class will read the configuration in our hibernate.cfg.xml file which handles the database connection to our MySQL server.

Next, create a new class in com.geekonjava.dao package, name it CustomerDao.java. DAO stands for Data Access Object. It contains the logic for database operation.

CustomerDao.java

package com.geekonjava.dao;
 
import com.geekonjava.entity.Customer;
import com.geekonjava.util.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
 
/**
 *
 * @author geekonjava
 */
public class CustomerDao {
 
    public void addCustomer(Customer cust) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            session.save(cust);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }
 
    public void deleteCustomer(int custid) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            Customer cust = (Customer) session.load(Customer.class, new Integer(custid));
            session.delete(cust);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }
 
    public void updateCustomer(Customer cust) {
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            session.update(cust);
            session.getTransaction().commit();
        } catch (RuntimeException e) {
            if (trns != null) {
                trns.rollback();
            }
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
    }
 
    public List<Customer> getAllCustomers() {
        List<Customer> users = new ArrayList<Customer>();
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            users = session.createQuery("select concat(first_name, ' ', last_name) as name from Customer").list();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return users;
    }
 
    public List<Customer> getCustomerById(String custid) {
        System.out.println(custid);
//        Customer cust = null;
        Transaction trns = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            trns = session.beginTransaction();
            String queryString = "from Customer where concat(first_name, ' ', last_name) = :id";
            Query query = session.createQuery(queryString);
            query.setString("id", custid);
            //cust = (Customer) query.uniqueResult();
            List<Customer> list = query.list();
            if (list.size() > 0) {
                return list;
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.close();
        }
        return null;
    }
}
Finally create the view page using jsf2.

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <title>JSF Hibernate CRUD Example</title>
        <style>
            tfoot{
                text-align: center;
            }
            thead{
                background-color: magenta;
                color: white;
            }
            td{
                font-weight: bold;
            }
            .msg{
                font-size: small;
                color: blue;
            }
        </style>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid id="panel1" columns="2" border="1"
                         cellpadding="5" cellspacing="1">
                <f:facet name="header">
                    <h:outputText value="Add Customer Information"/>
                </f:facet>
                <h:outputLabel value="First Namer:"/>
                <h:inputText value="#{customer.firstName}" id="fn"/>
                <h:outputLabel value="Last Name:"/>
                <h:inputText value="#{customer.lastName}" id="ln"/>
                <h:outputLabel value="Email:"/>
                <h:inputText value="#{customer.email}" id="eml"/>
                <h:outputLabel value="Date of Birth:"/>
                <h:inputText value="#{customer.sd}" id="s"/>
                <f:facet name="footer">
                    <h:outputLabel value="#{customer.msg}" id="msg" styleClass="msg"/>
                    <h:commandButton value="Save" action="#{customer.saveCustomer}">
                    <f:ajax render="fn ln eml s msg" execute="@form"/>
                        </h:commandButton>
                </f:facet>
            </h:panelGrid>
             
        </h:form>
         
        <h:form>
                <h:panelGrid id="panel2" columns="2" border="1"
                             cellpadding="5" cellspacing="1">
                    <f:facet name="header">
                        <h:outputText value="Update/Delete Customer Info"/>
                    </f:facet>
                    <h:outputLabel value="Select Customer:"/>
                    <h:selectOneMenu value="#{customer.selectedname}" id="ulist">
                        <f:selectItems value="#{customer.allCustomers}"/>
                        <f:ajax event="change" render="cid fname lname email sd" listener="#{customer.fullInfo}"/>
                    </h:selectOneMenu>
                      <h:outputLabel value="Customer ID:"/>
                      <h:inputText value="#{customer.custId}" id="cid" readonly="true"/>
                    <h:outputLabel value="First Name:"/>
                    <h:inputText value="#{customer.firstName}" id="fname"/>
                    <h:outputLabel value="Last Name:"/>
                    <h:inputText value="#{customer.lastName}" id="lname"/>
                    <h:outputLabel value="Email:"/>
                    <h:inputText value="#{customer.email}" id="email"/>
                    <h:outputLabel value="Date of Birth:"/>
                    <h:inputText value="#{customer.sd}" id="sd"/> 
                    <f:facet name="footer">
                        <h:outputLabel value="#{customer.msg}" id="msg2" styleClass="msg"/>
                        <h:commandButton value="Update Info" action="#{customer.updateCustomer}">
                            <f:ajax render="ulist cid fname lname email sd msg2" execute="@form"/>
                        </h:commandButton>
                        <h:commandButton value="Delete Info" action="#{customer.deleteCustomer}">
                            <f:ajax render="ulist cid fname lname email sd msg2" execute="@form"/>
                        </h:commandButton>
                    </f:facet>
                </h:panelGrid>
            </h:form>
    </h:body>
</html>
Read More

Friday, 26 June 2015

Align String to left, right or center in Java

Leave a Comment
In this example, we will learn to align a string to left ,right or center. I have created a utility class StringAlignUtils.java, which wraps all the logic inside it, and provide you convenient methods which you can call directly.

Sourcecode of StringAlignUtils

StringAlignUtils class extends java.text.Format class. This help you in some cases where references are of type java.text.Format.
Interest in Android Two free tools for all Android Developers
It defines three enum constants for alignment orders i.e. LEFT, CENTER, RIGHT.




It also needs a parameter maxChars, which is the length of characters in a single line if number of chars in input string is greater than certain limit.
package com.blogspot.geekonjava.examples;
 
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
 
public class StringAlignUtils extends Format {
 
    private static final long serialVersionUID = 1L;
 
    public enum Alignment {
        LEFT, CENTER, RIGHT,
    }
 
    /** Current justification for formatting */
    private Alignment currentAlignment;
 
    /** Current max length in a line */
    private int maxChars;
 
    public StringAlignUtils(int maxChars, Alignment align) {
        switch (align) {
        case LEFT:
        case CENTER:
        case RIGHT:
            this.currentAlignment = align;
            break;
        default:
            throw new IllegalArgumentException("invalid justification arg.");
        }
        if (maxChars < 0) {
            throw new IllegalArgumentException("maxChars must be positive.");
        }
        this.maxChars = maxChars;
    }
 
    public StringBuffer format(Object input, StringBuffer where, FieldPosition ignore)
    {
        String s = input.toString();
        List<String> strings = splitInputString(s);
        ListIterator<String> listItr = strings.listIterator();
         
        while (listItr.hasNext())
        {
            String wanted = listItr.next();
             
            //Get the spaces in the right place.
            switch (currentAlignment) {
                case RIGHT:
                    pad(where, maxChars - wanted.length());
                    where.append(wanted);
                    break;
                case CENTER:
                    int toAdd = maxChars - wanted.length();
                    pad(where, toAdd / 2);
                    where.append(wanted);
                    pad(where, toAdd - toAdd / 2);
                    break;
                case LEFT:
                    where.append(wanted);
                    pad(where, maxChars - wanted.length());
                    break;
                }
                where.append("\n");
        }
        return where;
    }
 
    protected final void pad(StringBuffer to, int howMany) {
        for (int i = 0; i < howMany; i++)
            to.append(' ');
    }
 
    String format(String s) {
        return format(s, new StringBuffer(), null).toString();
    }
 
    /** ParseObject is required, but not useful here. */
    public Object parseObject(String source, ParsePosition pos) {
        return source;
    }
 
    private List<String> splitInputString(String str) {
        List<String> list = new ArrayList<String>();
        if (str == null)
            return list;
        for (int i = 0; i < str.length(); i = i + maxChars)
        {
            int endindex = Math.min(i + maxChars, str.length());
            list.add(str.substring(i, endindex));
        }
        return list;
    }
}
Now look at the examples, to understand the usage of StringAlignUtils.java.

Trick in Interview : Top 10 tricky java interview question with answer

LEFT Align Example

public static void main(String[] args)
{
    String sampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
            + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris "
            + "nisi ut aliquip ex ea commodo consequat.";
 
    StringAlignUtils util = new StringAlignUtils(50, Alignment.LEFT);
    System.out.println( util.format(sampleText) );
}

Output:


Are you use ? :  Shaking effect in Swing

RIGHT Align Example

public static void main(String[] args)
{
    String sampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
            + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris "
            + "nisi ut aliquip ex ea commodo consequat.";
 
    StringAlignUtils util = new StringAlignUtils(50, Alignment.RIGHT);
    System.out.println( util.format(sampleText) );
}

Output:


CENTER Align Example

public static void main(String[] args)
{
    String sampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
            + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris "
            + "nisi ut aliquip ex ea commodo consequat.";
 
    StringAlignUtils util = new StringAlignUtils(50, Alignment.CENTER);
    System.out.println( util.format(sampleText) );
}

Output:



Feel free to edit and customize StringAlignUtils.java as per your needs. And drop me your questions and comments below.
Read More

Thursday, 25 June 2015

Bad features of Java

Leave a Comment
When you first learn to develop you see overly broad statements about different features to be bad, for design, performance, clarity, maintainability, it feels like a hack, or they just don't like it.

This might be backed by real world experience where removing the use of the feature improved the code.  Sometimes this is because the developers didn't know how to use the feature correctly, or the feature is inherently error prone (depending whether you like it or not)

It is disconcerting when either fashion, or your team changes and this feature becomes fine or even a preferred methodology.
Are you know your mistake in JavaTop 10 Common Mistake in Java
In this post, I look at some of the feature people like to hate and why I think that used correctly, they should be a force for good.  Features are not as yes/no, good/bad as many like to believe.

Checked Exceptions

I am often surprised at the degree that developers don't like to think about error handling.  New developers don't even like to read error messages. It's hard work, and they complain the application crashed, "it's not working". They have no idea why the exception was thrown when often the error message and stack dump tell them exactly what went wrong if they could only see the clues. When I write out stack traces for tracing purposes, many just see the log shaped like a crash when there was no error.   Reading error messages is a skill and at first it can be overwhelming.

Similarly, handling exceptions in a useful manner is too often avoided.  I have no idea what to do with this exception, I would rather either log the exception and pretend it didn't happen or just blow up and let the operations people or to the GUI user, who have the least ability to deal the error.

Many experienced developers hate checked exceptions as a result.  However, the more I hear this, the more I am glad Java has checked exception as I am convinced they really will find it too easy ignore the exceptions and just let the application die if they are not annoyed by them.

Checked exceptions can be overused of course.  The question should be when throwing a checked exception; do I want to annoy the developer calling the code by forcing them to think a little bit about error handling? If the answer is yes, throw a checked exception.
Java-PHP together ?Run Java Program in PHP using PHP/Java Bridge
IMHO, it is a failing of the lambda design that it doesn't handle checked exception transparently. i.e. as a natural block of code would by throwing out any unhandled exception as it does for unchecked exceptions and errors. However, given the history of lambdas and functional programming, where they don't like side effect at all, let alone short cut error handling, it is not surprising.

You can get around the limitation of lambdas by re-throwing a checked exception as if it were an unchecked one.  This works because the JVM has no notion of checked exceptions, it is a compile time check like generics.  My preferred method is to use Unsafe.rethrowException but there is 3 other ways of doing this. Thread.currentThread().stop(e) no longer working in Java 8 despite the fact it was always safe to do.

Was Thread.currentThread().stop(e) unsafe?

The method Thread.stop(Throwable) was unsafe when it could cause another thread to trigger an exception in a random section of code.  This could be a checked exception in a portion of code which didn't expect it, or throw an exception which is caught in some portions of the thread but not others leaving you with no idea what it would do.
What is WebScrap4J ?Extract website data in Java using webscrap4j library
However, the main reason it was unsafe is that it could leave atomic operations in as synchronized of locked section of code in an inconsistent state corrupting the memory in subtle and untestable ways.
To add to the confusion, the stack trace of the Throwable didn't match the stack trace of the thread where the exception was actually thrown.

But what about Thread.currentThread().stop(e)?  This triggers the current thread to throw an exception on the current line.  This is no worse than just using throw exception you are performing an operation the compiler can't check.  The problem is that the compiler doesn't always know what you are doing and whether it is really safe or not.  For generics this is classed as an "unchecked cast" which is a warning which you can disable with an annotation.  Java doesn't support the same sort of operation with checked exception so well and you end up using hacks, or worse hiding the true checked exception as a runtime exception meaning there is little hope the caller will handle it correctly.

Is using static bad?

This is a new "rule" for me.  I understand where it is coming from, but there is more exceptions to this rule than where it should apply.  Let us first consider all the contexts where the overloaded meaning of static can be used.

  • static mutable fields
  • static immutable field (final primitive or final fields pointing to objects which are not changed)
  • static methods.
  • static classes (which have no implicit reference to an outer instance)
  • static initialiser blocks.

I would agree that using static mutable fields is likely to be either a newbie bug, or something to be avoided if at all possible. If you see static fields being altered in a constructor, it is almost certainly a bug.(Even if not, I would avoid it)  I believe this is the cause of the statement to avoid all static.
You should knowWhat is reflection and use in real life
However, in all the other cases, using static is not only more performant, it is clearer.  It shows this field isn't different for each instance, or that the method or class doesn't implicitly depend on than instance.

In short, static is good, and mutable static fields are the exception, not the rule.

Are Singletons bad?

The problems with singletons come from two directions.  They are effectively global mutable state making them difficult to maintain or encapsulate e.g. in a unit test, and they support auto-wiring. i.e. any component can access it making your dependencies unclear and difficult to manage.  For these reasons, some developers hate them.

However, following good dependency injection is a methodology which should be applied to all your components, singletons or not, and you should avoid global mutable state via singletons or not.

If you exclude global state and self wiring components, you are left with Singletons which are immutable and passed via dependency injection and in this case they can work really elegantly.  A common pattern I use to implement strategies is to use an enum with one instance which implement an interface.
enum MyComparator implements Comparator {
       INSTANCE;
       public int compare(MyObject o1, MyObject o2) {
           // something a bit too complicated to put in a lambda
       }
    }
This instance can be passed as an implementation of Comparator via dependency injection and without mutable state can be used safely across threads and unit tests.

Can I get a library or framework to do that very simple thing for me?

Libraries and frameworks can save you a lot of time and wasted effort getting you own code to do something which already works else where.

Even if you want to write you own code I strongly suggest you have an understanding of what existing libraries and frameworks do so you can learn from them.  Writing it yourself is not a short cut to avoid having to understand any existing solutions.  A journalist once wrote with despair about an aspiring journalist that; didn't like to read, only to write.  The same applies in software development.

However, I have seen (on Stackoverflow) developers so to great lengths to avoid using their own code for even trivial examples.  They feel like if they use a library it must be better than anything they have written.  The problem with this is it assumes; adding libraries don't come at a cost to complexity, you have a really good understanding of the library, and you will never need to learn to write code you can trust.
Do you know , How to ? Use Notification Tray in Java Application
Some developers use frameworks to help learn what is actually a methodology.  Often developers use a framework for dependency injection when actually you could just do this in plain Java, but they either don't trust themselves or their team to do this.

In the high performance space, the simpler the code, the less work your application does, the easier it is to maintain with less moving parts and the faster it will go.  You need to use the minimum of libraries and frameworks which are reasonably easy to understand so you can get your system to perform at it best.

Is using double for money bad?

Using fractional numbers without any regard for rounding will give you unexpected results.  On the plus side, for double, are usually obviously wrong like 10.99999999999998 instead of 11.

Some have the view that BigDecimal is the solution.  However, the problem is that BigDecimal has it's own gotchas, is much harder to validate/read/write but worst of all can look correct when it is not.

Take this example

double d = 1.0 / 3 * 3 + 0.01;
    BigDecimal bd1 = BigDecimal.valueOf(1.0)
            .divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP)
            .multiply(BigDecimal.valueOf(3))
            .add(BigDecimal.valueOf(0.01))
            .setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal bd2 = BigDecimal.valueOf(1.0)
            .divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP)
            .multiply(BigDecimal.valueOf(3)
            .add(BigDecimal.valueOf(0.01)))
            .setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("d: " + d);
    System.out.println("bd1: " + bd1);
    System.out.println("bd2: " + bd2);
This produces three different results.  By sight, which one produces the right result?  Can you tell the difference between bd1 and bd2?

This prints
d: 1.01
bd1: 1.00
bd2: 0.99
Can you see from the output which is wrong? Actually the answer should be 1.01.

Another gotcha of BigDecimal is that equals and compareTo do not behave the same.  equals() can be false when compareTo() returns 0. i.e. in BigDecimal 1.0 equals 1.00 is false as the scales are different.

The problem I have with BigDecimal is that you get code which is often harder to understand and produces incorrect results which look like they could be right.  BigDecimal is significantly slower and products lots of garbage.  (This is improving in each version of Java 8) There are situations where BigDecimal is the best solution, but it is not a given as some would protest.

If BigDecimal is not a great alternative, is there any other?  Often int and long are used with fixed precision e.g. whole number of cents instead of a fraction of dollars.  This has some challenges in you have to remember where the decimal place is.  If Java supports values types, it might makes sense to use these as wrappers for money and give you more safety, but the control, clarify and performance of dealing with whole number primitives.

Using null values

For developers new to Java, getting repeated NullPointerException is a draining experience.  Do I really have to create a new instance of every object, every element in an array in Java?  Other language don't require this as it is often done via embedded data structures. (Something which is being considered for Java)

Even experienced Java developers have difficulty dealing with null values and see it as a big mistake to have null in the language. IMHO The problem is that the replacements are often far worse. such as NULL objects which don't NPE, but perhaps should have been initialised to something else.  In Java 8, Optional is a good addition which makes the handling of a non-result clearer.  I think it is useful for those who struggle with NullPointerException as it forces you to consider that there might not be a result at all.  This doesn't solve the problem of uninitialised fields.

I don't like it personally as it solves a problem which can be solved more generally by handling null correctly, but I recognise that for many it is an improvement.

A common question is;  how was I supposed to know a variable was null?  This is the wrong way around in my mind.  It should be, why assume it couldn't be null?  If you can't answer that, you have to assume it could be null and an NPE shouldn't be any surprise if you don't check for it.

You could argue that Java could do with more syntactic sugar to make code which handles null cleaner such as the Elvis operator, but I think the problem is that developers are not thinking about null values enough. e.g. do you check that an enum variable is null before you switch on it?. (I think there should be a case null: in switch but there isn't or to fall through to default: but it doesn't)

How important is it to write code fast?

Java is not a terse language and without an IDE to write half the code for you, it would be really painful to write esp if you spent all day writing code.

But this is what developers do all day don''t they?  Actually, they don't.  Developers don't spend much of their time writing code, they spend 90% (for new code) to 99% (for legacy code) understanding the problem.

You might say; I write 1000 lines of code all day long and later and re-write the code (often making it shorter) and some time later I fixed the code   However, while the code is still fresh in your mind, if you were to write just the code you needed in the end (or you do this from a print out) and you divide it by the total time you spent on the project, end to end,  you are likely to find it was actually less than 100 lines of code per day, possibly less than 10 lines per day.

So what were you really doing over that time if it wasn't writing the finished product.  It was understand what was required by the end users, and what was required to implement the solution.

Someone once told me; it doesn't matter how fast, how big, how deep or how many holes you dig, if you are digging them in the wrong place.

Conclusion

I hear views from beginners to distinguished developers claiming you shouldn't/I can't imagine why you would/you should be sacked if you use X, you should only use Y.  I find such statements are rarely 100% accurate.  Often there is either edge cases, and sometimes very common cases where such statement are misleading or simply incorrect.

I would treat any such broad comments with scepticism, and often they find they have to qualify what was said once they see that others don't have the same view.
Read More

Check That The Number Is Automorphic Or Not in Java

Leave a Comment
An Automorphic  Number is a number whose square "ends" in the same digits as the number itself.

Are you knowDifference between ArrayList and CopyOnWriteArrayList

Example:


Fact you need to know : Some fact on public static void main String(args[])
import java.util.*;
class Automorphic
{
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("ENTER THE NUMBER");
        int n=sc.nextInt();
        int d=1; int i;
        for(i=n;i>0;i=i/10)
        {
            d=d*10;
        }
        if((n*n)%d==n)
        {
            System.out.println(n+"\t"+"is Automorphic Number");
        }
        else
        {
             System.out.println(n+"\t"+"is not Automorphic Number");
            }
        }
    }
Read More

Tuesday, 23 June 2015

Use Javadoc comment in Java

Leave a Comment
Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code which has required documentation in a predefined format.

This document describes the style guide, tag and image conventions we use in documentation comments for Java programs written at Java Software, Oracle. It does not rehash related material covered elsewhere:

Need to know some Linux Putty Command : Basic Shell Putty Commands

Some Javadoc Tags :

TagDescriptionSyntax
@authorAdds the author of a class.@author name-text
{@code}Displays text in code font without interpreting the text as HTML markup or nested javadoc tags.{@code text}
{@docRoot}Represents the relative path to the generated document's root directory from any generated page{@docRoot}
@deprecatedAdds a comment indicating that this API should no longer be used.@deprecated deprecated-text
@exceptionAdds a Throws subheading to the generated documentation, with the class-name and description text.@exception class-name description
{@inheritDoc}Inherits a comment from the nearestinheritable class or implementable interfaceInherits a comment from the immediate surperclass.
{@link}Inserts an in-line link with visible text label that points to the documentation for the specified package, class or member name of a referenced class. T{@link package.class#member label}
{@linkplain}Identical to {@link}, except the link's label is displayed in plain text than code font.{@linkplain package.class#member label}
@paramAdds a parameter with the specified parameter-name followed by the specified description to the "Parameters" section.@param parameter-name description
@returnAdds a "Returns" section with the description text.@return description
@seeAdds a "See Also" heading with a link or text entry that points to reference.@see reference
@serialUsed in the doc comment for a default serializable field.@serial field-description | include | exclude
@serialDataDocuments the data written by the writeObject( ) or writeExternal( ) methods@serialData data-description
@serialFieldDocuments an ObjectStreamField component.@serialField field-name field-type field-description
@sinceAdds a "Since" heading with the specified since-text to the generated documentation.@since release
@throwsThe @throws and @exception tags are synonyms.@throws class-name description
{@value}When {@value} is used in the doc comment of a static field, it displays the value of that constant:{@value package.class#field}
@versionAdds a "Version" subheading with the specified version-text to the generated docs when the -version option is used.@version version-text
Repeat work with time Repeat Task at particular time in Java

Example :

Following program uses few of the important tags available for documentation comments. You can make use of other tags based on your requirements.
package com.blogspot.geekonjava;

import java.io.*;

/**
* <h1>Add Two Numbers!</h1>
* The AddNum program implements an application that
* simply adds two given integer numbers and Prints
* the output on the screen.
* <p>
* <b>Note:</b> Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
*
* @author  GeekOnJava
* @version 1.0
* @since   2015-06-24
*/
public class AddNum {
   /**
   * This method is used to add two integers. This is
   * a the simplest form of a class method, just to
   * show the usage of various javadoc Tags.
   * @param numA This is the first paramter to addNum method
   * @param numB  This is the second parameter to addNum method
   * @return int This returns sum of numA and numB.
   */
   public int addNum(int numA, int numB) {
      return numA + numB;
   }

   /**
   * This is the main method which makes use of addNum method.
   * @param args Unused.
   * @return Nothing.
   * @exception IOException On input error.
   * @see IOException
   */
   public static void main(String args[]) throws IOException
   {

      AddNum obj = new AddNum();
      int sum = obj.addNum(10, 20);

      System.out.println("Sum of 10 and 20 is :" + sum);
   }
}




Now, process above AddNum.java file using javadoc utility as follows:
Read something new : What is MySQL Stored Procedures
$ javadoc AddNum.java
Loading source file AddNum.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_51
Building tree for all the packages and classes...
Generating /AddNum.html...
AddNum.java:36: warning - @return tag cannot be used in method with void return type.
Generating /package-frame.html...
Generating /package-summary.html...
Generating /package-tree.html...
Generating /constant-values.html...
Building index for all the packages and classes...
Generating /overview-tree.html...
Generating /index-all.html...
Generating /deprecated-list.html...
Building index for all classes...
Generating /allclasses-frame.html...
Generating /allclasses-noframe.html...
Generating /index.html...
Generating /help-doc.html...
1 warning
$
Read More