Wednesday Jul 29, 2009

Java Basics - good to know - nice to use

Hi ,

After quite some time I'm back , busy with my automation project and one parser development.

Recently I am exploring some java stuff which was ignore knowingly or do not care to understand funda behind it as long as work is getting done. So i thought of sharing some know items one more time to give them special attention.

Duplicate in HashMap : If new object hash code is same as existing member hashcode then if either new object == to existing object or new objects equals() return true then existing object will be updated. So overwite hashcode and equals() if you want to prevent duplicate based on class variable.

Ex .

Class Employee

{ int empNo; String name; int age; }

You want collection to be store non duplicate based on empNo.

Then add following two overriding version of hashCode() and equals() public int hashCode()

{ return empNo; }

public boolean equals(Employee e)

{ return (this.empNo == e.empNo)?true:false; }

Now when you will add to hashmap object of Employee , it will add new pair if and only if empNo will be different otherwise it will update the existing one

Float.isNaN - Returns true if this Float value is a Not-a-Number (NaN), false otherwise.

ex.

float f = (float) Math.sqrt(-10);

boolean b1 = Float.isNaN(f);

System.out.println(b1); // result is : true

Transient - It flags a field as something that should not be considered part of an object's persistent state. i.e. in simple terms it will not get written to persistence store (whatever it may be) if this keyword is associated with variable Reading and Writing shared variable by


Thread : Each thread has a working memory, in which it may keep copies of the values of variables from the main memory that is shared between all threads.

To access a shared variable, a thread usually first obtains a lock and flushes its working memory. This guarantees that shared values will thereafter be loaded from the shared main memory to the threads working memory. When a thread unlocks a lock it guarantees the values it holds in its working memory will be written back to the main memory.

Monitor : Not class monitor , its object monitor , Each object got monitor. Thread calling synchronized method or synchronized block of this object gets monitor(if available otherwise wait wait). if thread get monitor then others has to wait till finish to execute the same.

Reentrant Monitor : The Java runtime system allows a thread to re-acquire a monitor that it already holds because Java monitors are reentrant. Reentrant monitors are important because they eliminate the possibility of a single thread deadlocking itself on a monitor that it already holds.

notifyAll() : After effects , If multiple threads are waiting for a monitor, the Java runtime system chooses one of the waiting threads to run, making no commitments or guarantees about which thread will be chosen.

Lost a monitor blame wait() : When the thread enters the wait method, the monitor is released atomically, and when the thread exits the wait method, the monitor is acquired again

Lock a Class , what ? : Java virtual machine loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object. But why ? To enter in synchronized static method you need class lock.

Wait() ,notify(),notifyAll() : from where you will invoke , anywhere , no no , only from synchronized method/statement. You need to lock to execute this methods.

serialVersionUID : you better write if your object getting serialized. If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during de-serialization

Error Class : lost frontier , how long it will survive . An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch . A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. ex. IOError , LinkageError , VirtualMachineError etc etc. Quite a few never knew they have good big family :-).

throw ? , what you can throw ? Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement

catch ? What you can catch ? Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

RunTimeException : luxury for not required to catch , should not be thrown in first place , go and fix root cause . A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught

comment / views / enlightment of concepts are welcome. 

Learning never ends and re-learning also never ends. :-)

Enjoy your time. 



Thursday Aug 07, 2008

Hibernate - POJO and HBM file creation best practice

Recently I was working on Hibernate and created a number of POJO and their corresponding hbm file. I am  using Netbeans (who has support for Hibernate plugin , real helpful , http://netbeans.org )

Certain best practice I would like to make work more interesting.

  • Keep table name and POJO name same.

ex. Create new Java Class  i.e Person , Use hibernate plugin to create .hbm file , Give same name as Class file , Select Person as class name on next screen.

  This will create .hbm file with name as Person , no need to provide table attribute. Hibernate will create table with same name.

This aovides unnecessary complexities in distinguice table name and class name

  • Keep POJO variable name same as Field name

      Do no mention Column attribute while declaring <Property> in .hbm file. Hibernate will create column with same name.

  • Try to keep ID as primaray key for all the Tables where possible. Less to remember and more time to figure out solution to problem on hand. 
  • How can I forgot my Dear I18n. There is nothing much as long as you make sure that created Database has UTF-8 encoding.
  • One more point , Certain tables are used to keep default list. If the list compoment is localizable make sure you take care of fetching localized values from proper resource bundle before publishing to User Interface.

Resources :

More will follow as I learn more ... enjoy your life ... n keep doing innovation ... only way to survive ...


Monday Jun 09, 2008

I18n Best practices for web application- Part 1

I have created clear and concise best practices list for making your application I18n'ed.

General

  • No hardcoded strings
  • Data format I18n
  • Number format I18n
  • Usage of  Apostrophe in Message Format class. 
  • Currency I18n
  • Sort I18n
  • Calendar I18n
  • Read/write file in UTF-8
    • Use methods like :public OutputStreamWriter(OutputStream out, String charsetName); public InputStreamReader(InputStream in, String charsetName)
  • Locale lookup should be correct - Find out what lookup mechanism needs to be used.
  • Send/Receive Locale when communicating with other compoments
  • If any property in property file does not need to be locaized put a comment on top property file.
  • Make sure property file does not have duplicate properties
  • When you use Message format to parse string make sure "'"(aphostrophy) in string is escaped.
  • File system name should be allowed to i18n

JSP Prgoram

  • Encoding of file should be "UTF-8"
    • <%@ page contentType="mimeType ;charset=characterSet ?" | "text/html; charset=UTF-8" %>
  • Use JSTL taglib to include the messages in the JSP file.
  • Request and Response should be in "UTF-8"

Resource Bundle

  • Should not use duplicate key properties file
  • Try to create less number of Property files
  • Try to use same message which already found in other components or even products if it make sense.
  • Do not change layout of message once translated
  • Property file for UI message and Log message should be SEPARATE
  • Message should not be slang or culturally sensitive
  • Always create _en.properties file along with base property file

GUI

  • Each button/textfield should have enough space to accommodate localized sentences
  • Layout and Text rendering
  • Input validation should consider multibyte data

Logging

  • If you are writing a WEB UI, the UI should appear in the client locale, not the server locale. Logging should be done in the server locale to avoid log messages with mixed data from different locales. Use UTF-8 as encoding for the web UI, because UTF-8 supports all languages.

Database

  • Reading and writing data to/from database should be in UTF-8

JUnit Testcase

  • Make sure all your Junit Testcase is I18n'ed. This will help in great way to integrate i18n testing in Unit testing.

AJAX

Refer AJAX I18n

References

About

Mahipalsinh Rana

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today