Tuesday, December 1, 2009

gcc library missing during run

edit /etc/ld.so.conf and run ldconfig.

In fedora
/etc/ld.so.conf -> include /etc/ld.so.conf.d/

all config in the above folder should include lib directory

e.g. pbc.conf
/usr/local/lib


http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dlls.html

Tuesday, October 20, 2009

SunJDK weblogic

Reference: http://buttso.blogspot.com/2009/09/switching-between-jrockit-and-sun-jdk.html


Switching Between JRockit and Sun JDK with WebLogic Server

Need to swap between JRockit and the Sun JDK when starting your WebLogic Server instance?

Looking at the start scripts $DOMAIN_HOME/bin/setDomainEnv.cmd, I just realized that this operational task is basically taken care of in the scripts we have.

To swap between the Sun JDK and JRockit to launch a WLS instance, all you need to do is set the JAVA_VENDOR environment variable to either "Sun" or "Oracle" and the scripts will take of launching WLS using the specified JDK.

Snippets from setDomainEnv.cmd:
set BEA_JAVA_HOME=d:\wls1031\jrockit_160_05_R27.6.2-20
set SUN_JAVA_HOME=d:\wls1031\jdk160_11

if "%JAVA_VENDOR%"=="Oracle" (
set JAVA_HOME=%BEA_JAVA_HOME%
) else (
if "%JAVA_VENDOR%"=="Sun" (
set JAVA_HOME=%SUN_JAVA_HOME%
) else (
set JAVA_VENDOR=Sun
set JAVA_HOME=d:\wls1031\jdk160_11
)
)

Where JAVA_HOME is then used by startWebLogic.cmd script when it launches the WLS instance to identify the JDK to use.

Snippets from startWebLogic.cmd
%JAVA_HOME%\bin\java %JAVA_VM% %MEM_ARGS%
-Dweblogic.Name=%SERVER_NAME%
-Djava.security.policy=%WL_HOME%\server\lib\weblogic.policy
%JAVA_OPTIONS%
%PROXY_SETTINGS%
%SERVER_CLASS%

With this information at hand, then switching between the two different JDKs is as simple as setting an environment variable before launching WebLogic Server.

Using JRockit:
>set JAVA_VENDOR=Oracle
>startWebLogic.cmd
...
d:\wls1031\JROCKI~1.2-2\bin\java -jrockit -Xms512m -Xmx512m -Dweblogic.Name=AdminServer ...

And just as easy to switch back to Sun. Note here that you could just unset the JAVA_HOME environment variable, which will set the script to use whatever default was configured when the domain was created.

Using Sun JDK:
>set JAVA_VENDOR=Sun
>startWebLogic.cmd
...
d:\wls1031\JDK160~1\bin\java -client -Xms256m -Xmx512m -Dweblogic.Name=AdminServer ...

Monday, October 12, 2009

OpenSSL resources

http://www.dylanbeattie.net/docs/openssl_iis_ssl_howto.html
http://www.herongyang.com/crypto/OpenSSL_Signing_keytool_CSR_5.html
http://security.ncsa.uiuc.edu/research/grid-howtos/usefulopenssl.php

To view the details of the certificate signing request contained in the file server.csr, use:
openssl req -noout -text -in server.csr


c:\OpenSSL\bin\openssl asn1parse -inform der -in demo.p7 -i > c:\demo.asn1

c:\OpenSSL\bin\openssl pkcs7 -inform der -in demo.p7 -text -print_certs -noout

View certificate details
C:\Program Files\LunaPCI\keys>openssl x509 -inform PEM -in cert0.cer -text


------------------------------------------------------------------------------

1) Generate RSA key:
$ openssl genrsa -out key.pem 1024
$ openssl rsa -in key.pem -text -noout

2) Save public key in pub.pem file:
$ openssl rsa -in key.pem -pubout -out pub.pem
$ openssl rsa -in pub.pem -pubin -text -noout

3) Encrypt some data:
$ echo test test test > file.txt
$ openssl rsautl -encrypt -inkey pub.pem -pubin -in file.txt \
-out file.bin
$ ll file.bin
-rw-r--r-- 1 root root 128 2007-07-11 01:58 file.bin

4) Decrypt encrypted data:
$ openssl rsautl -decrypt -inkey key.pem -in file.bin
test test test

But you should have public key in so called SubjectPublicKeyInfo format
(look at RFC2459).
You can look at ASN.1 structure of public key with command:
$ openssl asn1parse -in pub.pem
0:d=0 hl=3 l= 159 cons: SEQUENCE
3:d=1 hl=2 l= 13 cons: SEQUENCE
5:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
16:d=2 hl=2 l= 0 prim: NULL
18:d=1 hl=3 l= 141 prim: BIT STRING

Sample Public key
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRzVwcS4JP8K5iihVc4j26QZWp
4n4Bh9cTxdCovsrCd50lxPNRUPPGqPcPwYGLVyyTG8+DR9RtqcVrC3gYtI20G2+0
HbWTRWAAa/LF/x937nt3Q92CDu010eRY0CDtvyLcg90yLV/84TOc5PRwbCwuURgu
3Nzn+7BiEZ7lYCyXGQIDAQAB
-----END PUBLIC KEY-----


------------------------------------------------------------------------------
For public key in hex64 ending with '==', use openssl asn1parse -in c:\maybank.pem

-----BEGIN PUBLIC KEY-----
MIGIAoGAq74V/tQfDXWpO821eujW9MOpSROdVKQXncV3m+k1K0Vmnu8QGSzvFq5cBe7R6uHB
/J5gHKwFVG6XgrqjVa46gprk+8vQFfLfshHcFf/Vv79Ykpj0/PWaCAvp7uvcFKKByb1cDhAu
PDmzbBJYMyg7nG3dmAzhEqPK+LLOQ5s7mHkCAwEAAQ==
-----END PUBLIC KEY-----

------------------------------------------------------------------------------








Thursday, October 8, 2009

Netbeans Sign jar

http://ezzatron.com/2009/09/29/automatically-signing-jar-files-in-netbeans/

Wednesday, September 9, 2009

Vmware: Weblogic 9.2, solaris 9, JDK 1.5_12

1. Download solaris 9 from sun.com //Hint: Use Sun download manager
2. Download Weblogic 9.2 from BEA(Oracle) website
3. Download Sun JDK 1.5_12 from sun.com for solaris.

4. Install Solaris 9 iso onto vmware
http://pubs.vmware.com/guestnotes/wwhelp/wwhimpl/common/html/wwhelp.htm?context=guestnotes&file=guestos_solaris9.html

5. Install JDK 1.5_12 into iso
http://java.sun.com/j2se/1.5.0/install-solaris.html
6. Install BEA Weblogic 9.2 referencing JDK 1.5_12
http://download.oracle.com/docs/cd/E13196_01/platform/suppconfigs/configs/solaris/solaris9_91.html#96804

Friday, September 4, 2009

WebLogic truststore keystore

references:
http://jonwilliams.wordpress.com/2009/07/27/configure-ssl-for-nodemanager/
http://download.oracle.com/docs/cd/E13222_01/wls/docs92/ConsoleHelp/taskhelp/security/ConfigureKeystoresAndSSL.html
http://download.oracle.com/docs/cd/E13222_01/wls/docs92/secmanage/ssl.html


Weblogic default
-keystore : DemoIdentity.jks \ DemoIdentityKeyStorePassPhrase
-truststore : DemoTrust.jks \ DemoTrustKeyStorePassPhrase

Sunday, August 2, 2009

Java Tracing & logging

Reference from: http://java.sun.com/javase/6/docs/technotes/guides/deployment/deployment-guide/tracing_logging.html

Tracing

Tracing is a facility to redirect any output in the Java Console to a trace file.

Java Plug-in

Tracing can be turned on by enabling the property javaplugin.trace. However, it turns on all tracing facilities inside Java Plug-in. To enable more fine-grained tracing, javaplugin.trace.option may be used. You can set trace-level options (0-5) in the Java Console, shown in the previous chapter, with the following meanings:

  • 0 — off
  • 1 — basic
  • 2 — network, cache, and basic
  • 3 — security, network and basic
  • 4 — extension, security, network and basic
  • 5 — LiveConnect, extension, security, network, temp, and basic

This enables tracing on the fly.

Another way to set fine-grained tracing is through the Java Control Panel. For instance, to enable tracing for everthing (option 5 above), enter the following in the "Java Run Time Parameters" textfield:

-Djavaplugin.trace=true
-Djavaplugin.trace.option=basic|net|cache|security|ext|liveconnect|temp

Tracing set through the Control Panel will take effect when the Plug-in is launched, but changes made through the Control Panel while a Plug-in is running will have no effect until restart.

Java Web Start

To set the initial trace level for a Java Web Start application set the deployment property deployment.trace.level. The deployment.trace.level property can have one of the following values:

  • basic
  • cache
  • net
  • security
  • ext
  • liveconnect

To use all the tracing level set deployment.trace.level to all.

Logging

Similar to tracing, logging is a facility to redirect any output in the Java Console to a log file using the Java Logging API. To enable logging perform the following actions:

  • Open Java Control Panel
  • Click Advanced tab.
  • Select Enable Logging under the Debugging option

Other Options

File Names

The names of the trace and log files are

plugin.trace
plugin.log

where the includes the major, minor and patch version numbers; e.g., plugin142_06.trace or plugin150.log

File Locations

The default location (directory) of the trace and log files is:

  • /.java/deployment/log on Unix/Linux
  • \Sun\Java\Deployment\log on Windows

where is as defined here.

If the environment variable USER_JPI_PROFILE is set to then the trace and log files will be written to:

  • /.java/deployment/log on Unix/Linux
  • \Sun\Java\Deployment\log on Windows

Wednesday, July 29, 2009

Personal 2D barcode

http://mobilecodes.nokia.com/create.jsp?terms=accepted

Tuesday, July 28, 2009

log4J internationalization & localisation

http://java.sun.com/developer/technicalArticles/Intl/ResourceBundles/
http://java.sun.com/docs/books/tutorial/i18n/index.html
http://forums.sun.com/thread.jspa?threadID=5370732&tstart=60
http://blogs.sun.com/CoreJavaTechTips/entry/logging_localized_message

Log4J internationalization
http://forums.sun.com/thread.jspa?threadID=770074



Debug java util MissingResourceException

java.util.MissingResourceException Can't find bundle for base name, locale...How did I get this exception? The crux of this problem is the requested resource, in most cases, a properties file, is not configured correctly in the classpath. For example, you have a properties file, connection.properties, in the same source directory as Java source files. Javac will compile *.java into *.class in a target directory such as build/classes, which is in your runtime classpath. But connection.properties is not copied into build/classes directory unless you either add a task after in the Ant build file, or do so manually.

How to fix it? Make sure this resource is configured correctly in the classpath through one of the following:

  • Like I said above, copy the resource from source directory to build/classes directory, which is in the classpath.
    • If your code is like ResourceBundle.getBundle("connection"), then after copying you should have build/classes/connection.properties.
    • If your code is like ResourceBundle.getBundle("com.javahowto.test.connection"), then after copying you should have build/classes/com/javahowto/test/connection.properties.
  • Or you can choose package resources into a jar file, say, connection-info.jar, which is included in runtime classpath (not needed in Javac classpath).
    • If your code is like ResourceBundle.getBundle("connection"), then connection-info.jar should contain this entry: connection.properties.
    • If your code is like ResourceBundle.getBundle("com.javahowto.test.connection"), then connection-info.jar should contain this entry: com/javahowto/test/connection.properties.
  • Or you can choose to put the resource in a separate resources directory, include resources directory in runtime classpath. This way you don't have to duplicate the resource in multiple directories/jar. The disadvantage is it's a little inconvenient at development time to have resource in a separate directory than Java code.
    • If your code is like ResourceBundle.getBundle("connection"), then you should have resources/connection.properties.
    • If your code is like ResourceBundle.getBundle("com.javahowto.test.connection"), then you should have resources/com/javahowto/test/connection.properties.

J2ME barcode libraries

available Java ME barcode libraries:
http://sourceforge.net/projects/readbarj/
http://code.google.com/p/zxing/
http://code.google.com/p/zxing/wiki/GetTheReader
http://people.inf.ethz.ch/adelmanr/batoo/index.php
http://code.google.com/p/jjil/
http://code.google.com/p/pp-barcode-reader/

http://www.jappit.com/ - mobile and web blog

articles
http://blog.erikdebruijn.nl/archives/78-Camera-phones-as-barcode-readers-increased-buying-power.html

Saturday, July 25, 2009

java localisation & Internalization

java
http://java.sun.com/docs/books/tutorial/i18n/intro/after.html
http://java.sun.com/docs/books/tutorial/i18n/resbundle/propfile.html
http://www.velocityreviews.com/forums/t153252-resourcebundle-cant-find-properties-file-unless-in-package.html
http://www.rgagnon.com/javadetails/java-0135.html

Wednesday, July 22, 2009

XML Schema

http://www.datypic.com/books/defxmlschema/chapter13.html
http://www.w3schools.com/schema/schema_simple.asp

Tuesday, July 21, 2009

Blog Recommendation

java exception handling

- http://tutorials.jenkov.com/

- http://www.javaworld.com/javaworld/jw-07-2005/jw-0711-exception.html?page=5

static Intialiser
- http://www.developer.com/java/other/article.php/2238491
- http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

Wednesday, July 15, 2009

Netbeans UTF 8 encoding

/etc folder of netbeans directory, called netbeans.conf
-J-Dfile.encoding=UTF-8

Wednesday, June 3, 2009

Java Jar files


jar cvf app.jar MyApp.class

execute jar files
java -jar app.jar

java -classpath app.jar foo.Main

Thursday, May 28, 2009

bouncycastle

Bouncycastle supported Encodings and Algorithm
http://www.bouncycastle.org/specifications.html

fedora last reboot, poweroff

who command
You need to use who command, to print who is logged on. It also displays the time of last system boot. Use last command to display system reboot and shutdown date and time.

$ who –b

Output:system boot Apr 30 15:08

Use last command to display listing of last logged in users and system last reboot time and date:

$ last reboot lessOr better try:$ last reboot head -1
Output:reboot system boot 2.6.15.4 Sun Apr 30 15:08 - 16:22 (01:13)

last command searches back through the file /var/log/wtmp and displays a list of all users logged in (and out) since that file was created. The pseudo user reboot logs in each time the system is rebooted. Thus last reboot command will show a log of all reboots since the log file was created.

To display last shutdown date and time use following command:

$ last -x grep down
$ last -xgrep shutdown head -1
Output:shutdown system down 2.6.15.4 Sun Apr 30 13:31 - 15:08 (01:37)

Where,


-x: Display the system shutdown entries and run level changes.

fedora logs

Fedora's /etc/syslog.conf follows a standard logic:

mail logs are stored in /var/log/maillog,
system's logs are in /var/log/messages,
cron jobs activities are in /var/log/cron,
authentication data are in /var/log/secure.

Sunday, April 26, 2009

Active directory remote administration

References: http://www.computerperformance.co.uk/w2k3/utilities/ldp.htm

Monday, April 20, 2009

Increase Glassfish memory(heap)

Application Server->JVM Settings->JVM Options

Change -Xmx512m to -Xmx1024m or more.

OR if you are get out of PermGen memory add a property

-XX:MaxPermSize=256m

Tuesday, April 14, 2009

glassfish remove http instance port xx80

Goto /opt/glassfish/domain/dsss/config
vi domain.xml

Change below

<http-listener acceptor-threads="1" address="0.0.0.0" blocking-enabled="false" default-virtual-server="server" enabled="true" family="inet" id="http-listener-1" port="2080" security-enabled="false" server-name="" xpowered-by="true">
<property name="proxiedProtocols" value="ws/tcp"/>
</http-listener>

<http-listener acceptor-threads="1" address="0.0.0.0" blocking-enabled="false" default-virtual-server="server" enabled="true" family="inet" id="http-listener-2" port="2081" security-enabled="true" server-name="" xpowered-by="true">
<ssl cert-nickname="s1as" client-auth-enabled="false" ssl2-enabled="false" ssl3-enabled="true" tls-enabled="true" tls-rollback-enabled="true"/>
</http-listener>

to:

<http-listener acceptor-threads="1" address="0.0.0.0" blocking-enabled="false" default-virtual-server="server" enabled="true" family="inet" id="http-listener-1" port="2081" security-enabled="true" server-name="" xpowered-by="true">
<ssl cert-nickname="s1as" client-auth-enabled="false" ssl2-enabled="false" ssl3-enabled="true" tls-enabled="true" tls-rollback-enabled="true"/>
<property name="proxiedProtocols" value="ws/tcp"/>
</http-listener>



remove http-listener-2 from below:

<http-listener acceptor-threads="1" address="0.0.0.0" blocking-enabled="false" default-virtual-server="__asadmin" enabled="true" family="inet" id="admin-listener" port="2048" security-enabled="false" server-name="" xpowered-by="true"/>
<virtual-server hosts="${com.sun.aas.hostName}" http-listeners="http-listener-1,http-listener-2" id="server" log-file="${com.sun.aas.instanceRoot}/logs/server.log" state="on">
<property name="docroot" value="${com.sun.aas.instanceRoot}/docroot"/>
<property name="accesslog" value="${com.sun.aas.instanceRoot}/logs/access"/>
<property name="sso-enabled" value="false"/>
</virtual-server>

Monday, April 13, 2009

Netbeans combine library jar and output jar

Combine library jar and executing jars into one jar


<target name="-post-jar">
<jar jarfile="dist/Combined-dist.jar">
<zipfileset src="${dist.jar}" excludes="META-INF/*" />
<zipfileset src="lib/commons-io-1.4.jar" excludes="META-INF/*" />
<manifest>
<attribute name="Main-Class" value="com.example.mypackage.Main"/>
</manifest>
</jar>
</target>

Sunday, April 12, 2009

BouncyCastle JSSE

References:
http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml
http://java.sun.com/developer/JDCTechTips/2004/tt0116.html
http://www.bouncycastle.org/specifications.html

Saturday, April 11, 2009

Netbean JDK 1.1 support

References from : http://wiki.netbeans.org/FaqJdk11


Can I use JDK 1.1 for my project?



The IDE does not support JDK 1.1 directly but it can be made to work if you want. Here are some sample
instructions which were tested with a NB 5.0 development build running under JDK 6 on Fedora Core 4 Linux
with an installation of Blackdown's JDK 1.1.8:


1. Make a new Java "class library" project.


2. In the Files tab, open project.properties. Edit the definition of javac.source to read:




javac.source=1.2

(the 1.2 language doesn't really differ from 1.1, so this is just to make sure the editor doesn't think assert or generics are allowed!)


and also add to either project.properties or private.properties the location of your JDK 1.1 installation,
e.g.:




jdk11.home=/space/jdk118_v3

3. Openbuild.xmland add



<target name="-init-macrodef-javac">
<macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3">

<attribute name="srcdir" default="${src.dir}"/>
<attribute name="destdir" default="${build.classes.dir}"/>
<attribute name="classpath" default="${javac.classpath}"/>

<attribute name="debug" default="${javac.debug}"/>
<element name="customize" optional="true"/>
<sequential>

<javac srcdir="@{srcdir}" destdir="@{destdir}" debug="@{debug}"
deprecation="${javac.deprecation}" source="1.1" target="1.1"

includeantruntime="false" bootclasspath="${jdk11.home}/lib/classes.zip">
<classpath>
<path path="@{classpath}"/>
</classpath>

<compilerarg line="${javac.compilerargs}"/>
<customize/>
</javac>
</sequential>
</macrodef>

</target>
<target name="-init-macrodef-java">
<macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1">
<attribute name="classname" default="${main.class}"/>

<element name="customize" optional="true"/>
<sequential>
<java fork="true" classname="@{classname}" dir="${work.dir}"

jvm="${jdk11.home}/bin/java">
<jvmarg line="${run.jvmargs}"/>
<classpath>
<path path="${run.classpath}:${jdk11.home}/lib/classes.zip"/>

</classpath>
<syspropertyset>
<propertyref prefix="run-sys-prop."/>
<mapper type="glob" from="run-sys-prop.*" to="*"/>

</syspropertyset>
<customize/>
</java>
</sequential>
</macrodef>
</target>


These Ant targets should suffice to make basic compilation and execution of Java apps work. If your JDK 1.1
installation has a different file layout from Blackdown's, you may need to adjust these targets a bit (update
this Wiki page if so).


3a. If you are using NetBeans 6.0, the macrodef for 'depend' should also be added in <target name="-init-macrodef-javac"> after macrodef for javac, as follows:



<target name="-init-macrodef-javac">
<macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3">

...
</macrodef>
<macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3">
<attribute default="${src.dir}" name="srcdir"/>

<attribute name="destdir" default="${build.classes.dir}"/>
<attribute name="classpath" default="${javac.classpath}"/>
<sequential>

<depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}">
<classpath>

<path path="@{classpath}"/>
</classpath>
</depend>
</sequential>
</macrodef>

</target>

4. Make a new Java GUI Forms / AWT Forms / Applet Form. Build whatever GUI you like, using e.g.
GridBagLayoutas the layout manager (Matisse won't work), and of course using just AWT components (no Swing). (Unfortunately, the form designer will still use constants like BorderLayout.PAGE_START that don't exist in Java 1.1, and these will show up in generated code that can't be hand-modified. Use the source view to check for these errors. You'll have to simply avoid using those features of the form designer that cause problems, or code your app without using the designer at all.)


5. You will need to correct the init() method to call initComponents() directly (EventQueue.invokeLater

does not exist in this JDK, but you do not need it anyway).


6. Press Shift-F6 (or select Run / Run File / Run from the menu) to build and run your applet. The JDK 1.1 version ofappletviewershould start with
your applet.


7. Running a main class should work similarly.


The above setup does not include code completion, i.e. the IDE will show you code completion from your default
JDK (whatever the IDE runs on - 1.4+), even though your project will be compiled by Ant against JDK 1.1. Also,
the background error stripes will not show accidental usage of JDK 1.2+ APIs. To make code completion and
background error detection work is a little tricky since the Java Platform Manager does not recognize JDK 1.1
installations. But you can set it up manually:


1. Close the IDE.


2. In your user directory (available from Help | About), locate the directory
config/Services/Platforms/org-netbeans-api-java-Platform and make a new text file called JDK11.xml
with contents like:



<?xml version='1.0'?>

<!DOCTYPE platform PUBLIC
'-//NetBeans//DTD Java PlatformDefinition 1.0//EN'
'http://www.netbeans.org/dtds/java-platformdefinition-1_0.dtd'>
<platform name='JDK11' default='no'>
<properties>
<property name='platform.ant.name' value='JDK11'/>
</properties>
<sysproperties>
<property name='sun.boot.class.path' value='/space/jdk118_v3/lib/classes.zip'/>

<property name='java.specification.version' value='1.1'/>
<property name='java.class.path' value=''/>
<property name='java.ext.dirs' value=''/>
</sysproperties>
<jdkhome>
<resource>file:/space/jdk118_v3/</resource>

</jdkhome>
<sources>
<resource>jar:file:/space/jdk118_v3/src.zip!/src/</resource>
</sources>
</platform>


Of course replace the three occurrences of /space/jdk118_v3 with the location of your JDK 1.1 installation.
The second two are URLs so you need to use / not \ on Windows.


3. Restart the IDE. You should see an entry JDK11 in the Java Platform Manager.


4. Open the properties of your Java project, and set Libraries | Java Platform to JDK11. The IDE will ask
you to set the source level to 1.1; you can accept this offer (shouldn't matter).


5. Now try code completion on your project - you should see only JDK 1.1 classes. (However, this does not fix the problem noted above with the form designer using constants that are not valid in Java 1.1.)



Friday, April 10, 2009

Linux firewall allow glassfish access

vi /etc/sysconfig iptables

# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT //add this for ssh
-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT //add this for mysql
-A INPUT -m state --state NEW -m tcp -p tcp --dport 2048 -j ACCEPT //add this for domain administration
-A INPUT -m state --state NEW -m tcp -p tcp --dport 2080 -j ACCEPT //add this for http
-A INPUT -m state --state NEW -m tcp -p tcp --dport 2081 -j ACCEPT //add this for https
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5901 -j ACCEPT
#-A RH-Firewall-1-INPUT -p tcp -m state -m tcp --dport 3306 --state NEW -j ACCEPT
#-A RH-Firewall-1-INPUT -p udp -m state -m udp --dport 3306 --state NEW -j ACCEPT
#-A RH-Firewall-1-INPUT -p tcp -m state -m tcp --dport 2048:2081 --state NEW -j ACCEPT
#-A RH-Firewall-1-INPUT -p udp -m state -m udp --dport 2048:2081 --state NEW -j ACCEPT
COMMIT


References:
http://www.yolinux.com/TUTORIALS/LinuxTutorialInitProcess.html

fedora disable gnome desktop

1. while computer is running
#: init 3 //switch to run level 3(text mode) //gnome window in level 5(default mode)
#:

2. Permanent
#: vi /etc/inittab
find "id:number:initdefault:" //default is id:5:initdefault:
change line to "id:3:initdefault:"

ref: http://www.fedorafaq.org/basics/

Thursday, April 9, 2009

Cron job (MYSQLDUMP FTP SCRIPT)

Cron commands
crontab -e //edit user cronjob

Add the below script to the cron
50 10 * * * /opt/logScripts/mysqlbackup.sh > /opt/logs/mysqlbackup.log


crontab -l //list
crontab -r //remove



#!/bin/bash

DATADIR=/home/database

NOW=$(date +%d%m%Y%H%M%S)
#T=$(date +%H%M%S)
#echo ${T}

mysqldump -uroot -p12345678 webservice > "${DATADIR}/db${NOW}.sql"
tar -zcf "${DATADIR}/db${NOW}.tgz" "${DATADIR}/betterthanpindb${NOW}.sql"
rm -f "${DATADIR}/db${NOW}.sql"

HOST='192.168.1.250'
USER='ftpuser'
PASSWD='12345678'

TARFILE="db${NOW}.tgz"

ftp -i -n ${HOST} << END_SCRIPT
user ${USER} ${PASSWD}

binary
lcd ${DATADIR}
put $TARFILE
quit
END_SCRIPT

rm -f "${DATADIR}/db${NOW}.tgz"


http://www.adminschoice.com/docs/crontab.htm
http://www.webmasterworld.com/databases_sql_mysql/3277413.htm
http://www.unixgeeks.org/security/newbie/unix/cron-1.html

Wednesday, April 8, 2009

Linux Glassfish startup service

1. Add the script glassfish below to /etc/init.d
Name of file = glassfish- e.g., glassfish-domain1
-chmod a+x /etc/init.d/glassfish-

2. To support service, the script must fulfill the below criteria:
-3 functions: start, stop, restart
-chkconfig level
3. debug script # bash -x glassfish-
4. to have glassfish start during boot (and stop during halt)

run level: 2345
start priority:64
stop priority:36

ln -s /etc/init.d/glassfish- /etc/rc0.d/K36glassfish-
ln -s /etc/init.d/glassfish- /etc/rc1.d/K36glassfish-
ln -s /etc/init.d/glassfish- /etc/rc2.d/S64glassfish-
ln -s /etc/init.d/glassfish- /etc/rc3.d/S64glassfish-
ln -s /etc/init.d/glassfish- /etc/rc4.d/S64glassfish-
ln -s /etc/init.d/glassfish- /etc/rc5.d/S64glassfish-
ln -s /etc/init.d/glassfish- /etc/rc6.d/K36glassfish-

5. reboot

Linux command to chkconfig service start on boot
#: ntsysv

ps U
service glassfish- status
service glassfish- start

************glassfish****************************

#!/bin/bash
# chkconfig: 2345 64 36
# description: GlassFish is a Java Application Server.
# processname: glassfish
# pidfile: /var/run/glassfish.pid

# filename glassfish-

# source function library
. /etc/init.d/functions

RETVAL=0
GLASSFISH_BIN="/opt/glassfish/bin"
PASSWORDPATH="/opt/glassfish/domains/dsss/config/startup-password"
GFUSER="atworld"

# Basename works with symbolic links.
NAME="$(basename $0)"
unset ISBOOT
# Trim off the Sxx/Kxx prefix
if [ "${NAME:0:1}" = "S" -o "${NAME:0:1}" = "K" ]; then
NAME="${NAME:3}"
ISBOOT="1"
fi
# Trim off the glassfish- prefix
NAME=${NAME:10}

# /etc/init.d/glassfish should never be called directly.
if [ -z $NAME ]; then
echo -n $"Cannot start Glassfish without specifying a domain."
failure
echo
exit 1
fi

start() {
echo -n $"Starting Glassfish V2 domain $NAME: "
daemon --user $GFUSER --pidfile /var/run/glassfish-$NAME.pid "$GLASSFISH_BIN/asadmin start-domain --passwordfile $PASSWORDPATH $NAME"
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
PID=`ps U $GFUSER | grep $NAME | awk '{ print $1}'`
echo $PID > /var/run/glassfish-$NAME.pid
touch /var/lock/subsys/glassfish-$NAME
fi
echo
}
stop() {
echo -n $"Shutting down Glassfish V2 domain $NAME: "
$GLASSFISH_BIN/asadmin stop-domain $NAME
RETVAL=$?
[ $RETVAL -eq 0 ]
rm -f /var/lock/subsys/glassfish-$NAME
rm -f /var/run/glassfish-$NAME success || failure
echo
}

case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload)
stop
start
;;
condrestart)
if [ -f /var/lock/subsys/glassfish-$NAME ]; then
stop
start
fi
;;
status)
status glassfish-$NAME
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|condrestart|status}"
exit 1
esac

exit $RETVAL

****************************************************

References:
http://www.thelinuxblog.com/adding-a-service-on-fedora/
http://computingwithjasper.blogspot.com/2008/01/installing-glassfish-2-on-ubuntu-710.html
http://www.cyberciti.biz/faq/rhel5-update-rcd-command/
http://www.linux.com/feature/46892
http://www.linuxjournal.com/article/4445
http://www.comptechdoc.org/os/linux/startupman/linux_surcsysinit.html
http://www.vias.org/linux-knowhow/fwpx_appendix_a_03.html
http://www.cricalix.net/archives/2008/07/22/autostarting-glassfish-on-centos/
http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch07_:_The_Linux_Boot_Process
http://www.zimbra.com/forums/installation/10553-solved-sudo-sorry-you-must-have-tty-run-sudo.html
http://www.linuxmanpages.com/man5/sudoers.5.php#lbAM
http://www.yolinux.com/TUTORIALS/LinuxTutorialInitProcess.html

Cron job to backup mysql database

date=`date -I`; mysqldump -uyourusername -pyourpassword ——all-databases > /home/LOGIN/backups/xbackup_$date.sql; gzip /home/LOGIN/backups/xbackup_$date.sql

he date line formats the date so that we can append it to our backup filename. We then ask mysql to dump all databases into /home/LOGIN/public_html/backups/xbackup_$date.sql,
where LOGIN is your Cpanel name, using “yourusername” as user (-u) and
“yourpassword” as the password (-p). Notice the date variable inserted
in the filename. Finally our SQL file is gzipped using the gzip directive.

Setup file owner and group. Current process

******Change file owner*******
chown
chown . //all

******Change group***********
chgrp
chgrp . //all

******Current process***********
ps aux | grep
ps U

Wednesday, March 18, 2009

Sync Linux server Time w. NTP server

Synchronize
ntpdate -b pool.ntp.org

configuration
vi /etc/ntp.conf


References: http://www.brennan.id.au/09-Network_Time_Protocol.html

  1. Logged in as root, check which timezone your machine is currently using by executing `date`. You'll see something like Mon 17 Jan 2005 12:15:08 PM PST, PST in this case is the current timezone.
  2. Change to the directory /usr/share/zoneinfo here you will find a list of time zone regions. Choose the most appropriate region, if you live in Canada or the US this directory is the "America" directory.
  3. If you wish, backup the previous timezone configuration by copying it to a different location. Such as
    mv /etc/localtime  /etc/localtime-old
  4. Create a symbolic link from the appropiate timezone to /etc/localtime. Example:
    ln -sf /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime
  5. If you have the utility rdate, update the current system time by executing
    /usr/bin/rdate -s time.nist.gov
  6. Set the ZONE entry in the file /etc/sysconfig/clock file (e.g. "America/Los_Angeles")
  7. Set the hardware clock by executing:
    /sbin/hwclock --systohc

Glassfish web container tuning settings

Reference: http://docs.sun.com/app/docs/doc/820-4343/abedw?a=view

Web Container Settings

Set Web container properties with the Admin Console at Configurations > config-name > Web Container.

Session Properties: Session Timeout

Session timeout determines how long the server maintains a session if a user does not explicitly invalidate the session. The default value is 30 minutes. Tune this value according to your application requirements. Setting a very large value for session timeout can degrade performance by causing the server to maintain too many sessions in the session store. However, setting a very small value can cause the server to reclaim sessions too soon.

Manager Properties: Reap Interval

Modifying the reap interval can improve performance, but setting it without considering the nature of your sessions and business logic can cause data inconsistency, especially for time-based persistence-frequency.

For example, if you set the reap interval to 60 seconds, the value of session data will be recorded every 60 seconds. But if a client accesses a servlet to update a value at 20 second increments, then inconsistencies will result.

For example, consider an online auction scenario as follows:

  • Bidding starts at $5, in 60 seconds the value recorded will be $8 (three 20 second intervals).

  • During the next 40 seconds, the client starts incrementing the price. The value the client sees is $10.

  • During the client’s 20 second rest, the Application Server stops and starts in 10 seconds. As a result, the latest value recorded at the 60 second interval ($8) is be loaded into the session.

  • The client clicks again expecting to see $11; but instead sees is $9, which is incorrect.

  • So, to avoid data inconsistencies, take into the account the expected behavior of the application when adjusting the reap interval.

Disable Dynamic JSP Reloading

On a production system, improve web container performance by disabling dynamic JSP reloading. To do so, edit the default-web.xml file in the config directory for each instance. Change the servlet definition for a JSP file to look like this:


jsp
org.apache.jasper.servlet.JspServlet

development
false


xpoweredBy
true


genStrAsCharArray
true
3

Tuesday, March 17, 2009

MySQL Database Replication

http://aciddrop.com/2008/01/10/step-by-step-how-to-setup-mysql-database-replication/

http://www.howtoforge.com/mysql_database_replication

http://www.onlamp.com/pub/a/onlamp/2005/06/16/MySQLian.html

http://osdir.com/ml/db.mysql.java/2004-10/msg00011.html

Putty show server ipaddress

Add the below to vi ~/.bashrc

add IP=`ifconfig eth0|grep inet\ addr|cut -d " " -s -f 12|cut -d : -s -f 2`
export PS1='${debian_chroot:+($debian_chroot)}\u@$IP:\w\$ '

Monday, March 16, 2009

How to Get the Best Performance Out of a Java Persistence Implementation

Ref: http://blogs.sun.com/enterprisetechtips/entry/how_to_get_the_best

http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html

Multiple MYSQL Instance reference

http://code.openark.org/blog/mysql/manually-installing-multiple-mysql-instances-on-linux-howto
http://www.ducea.com/2009/01/19/running-multiple-instances-of-mysql-on-the-same-machine/
http://dev.mysql.com/doc/refman/5.1/en/multiple-unix-servers.html
http://blog.dbadojo.com/2008/01/multiple-mysql-instances-on-ec2.html
http://forums.mysql.com/read.php?79,27,85#msg-85

Tuesday, March 10, 2009

Java Access Control

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Public – access allowed to public. E.g., constants
Protected – allow child to access parent.
No modifier – allow package member to access only.
Private – non-accessible.


Static Initialize
- init static constant variables or object
- loaded before class is loaded
- prevents lock scenario

static
{
*action
}

Install metro 1.4 on tomcat 5

1. Download metro-1.4.jar 
2. java -jar metro-1_4.jar
3.
jars from extracted metro jar /lib
Jars What? Needed at runtime
webservices-api.jar
webservices-extra-api.jar
"javax.*" JCP APIs Yes
webservices-rt.jar
webservices-extra.jar
Runtime code that implements the API Yes
webservices-tools.jar Development time tools No

shared.loader property in /conf/catalina.properties

For Tomcat 5.0
-> copy webservices-api.jar, webservices-extra-api.jar, webservices-rt.jar,
webservices-extra.jar,webservices-tools.jar
to /shared/lib
->default: shared.loader=${catalina.base}/shared/classes,
${catalina.base}/shared/lib/*.jar

else if want to standardise w. tomcat 6
-> do not copy file to /shared/lib, extract into external folder
c://metro/lib/*.jar
->configure
shared.loader=${catalina.base}/shared/classes,${catalina.base}/shared/lib/*.jar,
file:///c:/metro/lib/*.jar


For Tomcat 6.0
-> copy webservices-api.jar, webservices-extra-api.jar, webservices-rt.jar,
webservices-extra.jar,webservices-tools.jar
to c:/metro/lib/
-> configure shared.loader=file:///c:/metro/lib/*.jar
if using java 6 w. tomcat 6-> copy webservices-api.jar into c:/jdk6/jre/lib/

-Userful link for tutorial
https://metro.dev.java.net/getting-started/basic.html


JUNIT Testing

For JUnit Testing,

Each class that needs to be assertedEqual must overwrite the below 2 methods;
  • public boolean equals(Object obj) {
  • public int hashCode() {


  • Below information from http://www.geocities.com/technofundo/tech/java/equalhash.html

    Introduction

    The Java super class java.lang.Object has two very important methods defined in it. They are -
    • public boolean equals(Object obj)
    • public int hashCode()
    These methods prove very important when user classes are confronted with other Java classes, when objects of such classes are added to collections etc. These two methods have become part of Sun Certified Java Programmer 1.4 exam (SCJP 1.4) objectives. This article intends to provide the necessary information about these two methods that would help the SCJP 1.4 exam aspirants. Moreover, this article hopes to help you understand the mechanism and general contracts of these two methods; irrespective of whether you are interested in taking the SCJP 1.4 exam or not. This article should help you while implementing these two methods in your own classes.

    public boolean equals(Object obj)

    This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison". However, the classes providing their own implementations of the equals method are supposed to perform a "deep comparison"; by actually comparing the relevant data members. Since Object class has no data members that define its state, it simply performs shallow comparison.

    This is what the JDK 1.4 API documentation says about the equals method of Object class-

    Indicates whether some other object is "equal to" this one.
      The equals method implements an equivalence relation:
    • It is reflexive: for any reference value x, x.equals(x) should return true.
    • It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
    • It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
    • It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
    • For any non-null reference value x, x.equals(null) should return false.
    The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

    The contract of the equals method precisely states what it requires. Once you understand it completely, implementation becomes relatively easy, moreover it would be correct. Let's understand what each of this really means.

    1. Reflexive - It simply means that the object must be equal to itself, which it would be at any given instance; unless you intentionally override the equals method to behave otherwise.
    2. Symmetric - It means that if object of one class is equal to another class object, the other class object must be equal to this class object. In other words, one object can not unilaterally decide whether it is equal to another object; two objects, and consequently the classes to which they belong, must bilaterally decide if they are equal or not. They BOTH must agree.
      Hence, it is improper and incorrect to have your own class with equals method that has comparison with an object of java.lang.String class, or with any other built-in Java class for that matter. It is very important to understand this requirement properly, because it is quite likely that a naive implementation of equals method may violate this requirement which would result in undesired consequences.
    3. Transitive - It means that if the first object is equal to the second object and the second object is equal to the third object; then the first object is equal to the third object. In other words, if two objects agree that they are equal, and follow the symmetry principle, one of them can not decide to have a similar contract with another object of different class. All three must agree and follow symmetry principle for various permutations of these three classes.
      Consider this example - A, B and C are three classes. A and B both implement the equals method in such a way that it provides comparison for objects of class A and class B. Now, if author of class B decides to modify its equals method such that it would also provide equality comparison with class C; he would be violating the transitivity principle. Because, no proper equals comparison mechanism would exist for class A and class C objects.
    4. Consistent - It means that if two objects are equal, they must remain equal as long as they are not modified. Likewise, if they are not equal, they must remain non-equal as long as they are not modified. The modification may take place in any one of them or in both of them.
    5. null comparison - It means that any instantiable class object is not equal to null, hence the equals method must return false if a null is passed to it as an argument. You have to ensure that your implementation of the equals method returns false if a null is passed to it as an argument.
    6. Equals & Hash Code relationship - The last note from the API documentation is very important, it states the relationship requirement between these two methods. It simply means that if two objects are equal, then they must have the same hash code, however the opposite is NOT true. This is discussed in details later in this article.
    The details about these two methods are interrelated and how they should be overridden correctly is discussed later in this article.

    public int hashCode()

    This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc. This method must be overridden in every class that overrides the equals method.

    This is what the JDK 1.4 API documentation says about the hashCode method of Object class-

    Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
      The general contract of hashCode is:
    • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
    • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
    • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

    As compared to the general contract specified by the equals method, the contract specified by the hashCode method is relatively simple and easy to understand. It simply states two important requirements that must be met while implementing the hashCode method. The third point of the contract, in fact is the elaboration of the second point. Let's understand what this contract really means.
    1. Consistency during same execution - Firstly, it states that the hash code returned by the hashCode method must be consistently the same for multiple invocations during the same execution of the application as long as the object is not modified to affect the equals method.
    2. Hash Code & Equals relationship - The second requirement of the contract is the hashCode counterpart of the requirement specified by the equals method. It simply emphasizes the same relationship - equal objects must produce the same hash code. However, the third point elaborates that unequal objects need not produce distinct hash codes.
    After reviewing the general contracts of these two methods, it is clear that the relationship between these two methods can be summed up in the following statement -

    Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

    The rest of the requirements specified in the contracts of these two methods are specific to those methods and are not directly related to the relationship between these two methods. Those specific requirements are discussed earlier. This relationship also enforces that whenever you override the equals method, you must override the hashCode method as well. Failing to comply with this requirement usually results in undetermined, undesired behavior of the class when confronted with Java collection classes or any other Java classes.

    Correct Implementation Example

    The following code exemplifies how all the requirements of equals and hashCode methods should be fulfilled so that the class behaves correctly and consistently with other Java classes. This class implements the equals method in such a way that it only provides equality comparison for the objects of the same class, similar to built-in Java classes like String and other wrapper classes.

    1. public class Test
    2. {
    3. private int num;
    4. private String data;
    5.
    6. public boolean equals(Object obj)
    7. {
    8. if(this == obj)
    9. return true;
    10. if((obj == null) || (obj.getClass() != this.getClass()))
    11. return false;
    12. // object must be Test at this point
    13. Test test = (Test)obj;
    14. return num == test.num &&
    15. (data == test.data || (data != null && data.equals(test.data)));
    16. }
    17.
    18. public int hashCode()
    19. {
    20. int hash = 7;
    21. hash = 31 * hash + num;
    22. hash = 31 * hash + (null == data ? 0 : data.hashCode());
    23. return hash;
    24. }
    25.
    26. // other methods
    27. }

    Now, let's examine why this implementation is the correct implementation. The class Test has two member variables - num and data. These two variables define state of the object and they also participate in the equals comparison for the objects of this class. Hence, they should also be involved in calculating the hash codes of this class objects.

    Consider the equals method first. We can see that at line 8, the passed object reference is compared with this object itself, this approach usually saves time if both the object references are referring to the same object on the heap and if the equals comparison is expensive. Next, the if condition at line 10 first checks if the argument is null, if not, then (due to the short-circuit nature of the OR || operator) it checks if the argument is of type Test by comparing the classes of the argument and this object. This is done by invoking the getClass() method on both the references. If either of these conditions fails, then false is returned. This is done by the following code -
    if((obj == null) || (obj.getClass() != this.getClass())) return false; // prefer
    This conditional check should be preferred instead of the conditional check given by -
    if(!(obj instanceof Test)) return false; // avoid
    This is because, the first condition (code in blue) ensures that it will return false if the argument is a subclass of the class Test. However, in case of the second condition (code in red) it fails. The instanceof operator condition fails to return false if the argument is a subclass of the class Test. Thus, it might violate the symmetry requirement of the contract. The instanceof check is correct only if the class is final, so that no subclass would exist. The first condition will work for both, final and non-final classes. Note that, both these conditions will return false if the argument is null. The instanceof operator returns false if the left hand side (LHS) operand is null, irrespective of the operand on the right hand side (RHS) as specified by JLS 15.20.2. However, the first condition should be preferred for better type checking.

    This class implements the equals method in such a way that it provides equals comparison only for the objects of the same class. Note that, this is not mandatory. But, if a class decides to provide equals comparison for other class objects, then the other class (or classes) must also agree to provide the same for this class so as to fulfill the symmetry and reflexivity requirements of the contract. This particular equals method implementation does not violate both these requirements. The lines 14 and 15 actually perform the equality comparison for the data members, and return true if they are equal. Line 15 also ensures that invoking the equals method on String variable data will not result in a NullPointerException.
    While implementing the equals method, primitives can be compared directly with an equality operator (==) after performing any necessary conversions (Such as float to Float.floatToIntBits or double to Double.doubleToLongBits). Whereas, object references can be compared by invoking their equals method recursively. You also need to ensure that invoking the equals method on these object references does not result in a NullPointerException.

    Here are some useful guidelines for implementing the equals method correctly.
    1. Use the equality == operator to check if the argument is the reference to this object, if yes. return true. This saves time when actual comparison is costly.
    2. Use the following condition to check that the argument is not null and it is of the correct type, if not then return false.
      if((obj == null) || (obj.getClass() != this.getClass())) return false;
      Note that, correct type does not mean the same type or class as shown in the example above. It could be any class or interface that one or more classes agree to implement for providing the comparison.
    3. Cast the method argument to the correct type. Again, the correct type may not be the same class. Also, since this step is done after the above type-check condition, it will not result in a ClassCastException.
    4. Compare significant variables of both, the argument object and this object and check if they are equal. If *all* of them are equal then return true, otherwise return false. Again, as mentioned earlier, while comparing these class members/variables; primitive variables can be compared directly with an equality operator (==) after performing any necessary conversions (Such as float to Float.floatToIntBits or double to Double.doubleToLongBits). Whereas, object references can be compared by invoking their equals method recursively. You also need to ensure that invoking equals method on these object references does not result in a NullPointerException, as shown in the example above (Line 15).
      It is neither necessary, nor advisable to include those class members in this comparison which can be calculated from other variables, hence the word "significant variables". This certainly improves the performance of the equals method. Only you can decide which class members are significant and which are not.
    5. Do not change the type of the argument of the equals method. It takes a java.lang.Object as an argument, do not use your own class instead. If you do that, you will not be overriding the equals method, but you will be overloading it instead; which would cause problems. It is a very common mistake, and since it does not result in a compile time error, it becomes quite difficult to figure out why the code is not working properly.
    6. Review your equals method to verify that it fulfills all the requirements stated by the general contract of the equals method.
    7. Lastly, do not forget to override the hashCode method whenever you override the equals method, that's unpardonable. ;)
    Now, let's examine the hashCode method of this example. At line 20, a non-zero constant value 7 (arbitrary) is assigned to an int variable hash. Since the class members/variables num and data do participate in the equals method comparison, they should also be involved in the calculation of the hash code. Though, this is not mandatory. You can use subset of the variables that participate in the equals method comparison to improve performance of the hashCode method. Performance of the hashCode method indeed is very important. But, you have to be very careful while selecting the subset. The subset should include those variables which are most likely to have the greatest diversity of the values. Sometimes, using all the variables that participate in the equals method comparison for calculating the hash code makes more sense.
    This class uses both the variables for computing the hash code. Lines 21 and 22 calculate the hash code values based on these two variables. Line 22 also ensures that invoking hashCode method on the variable data does not result in a NullPointerException if data is null. This implementation ensures that the general contract of the hashCode method is not violated. This implementation will return consistent hash code values for different invocations and will also ensure that equal objects will have equal hash codes.
    While implementing the hashCode method, primitives can be used directly in the calculation of the hash code value after performing any necessary conversions, such as float to Float.floatToIntBits or double to Double.doubleToLongBits. Since return type of the hashCode method is int, long values must to be converted to the integer values. As for hash codes of the object references, they should be calculated by invoking their hashCode method recursively. You also need to ensure that invoking the hashCode method on these object references does not result in a NullPointerException.

    Writing a very good implementation of the hashCode method which calculates hash code values such that the distribution is uniform is not a trivial task and may require inputs from mathematicians and theoretical computer scientist. Nevertheless, it is possible to write a decent and correct implementation by following few simple rules.

    Here are some useful guidelines for implementing the hashCode method correctly.
    1. Store an arbitrary non-zero constant integer value (say 7) in an int variable, called hash.
    2. Involve significant variables of your object in the calculation of the hash code, all the variables that are part of equals comparison should be considered for this. Compute an individual hash code int var_code for each variable var as follows -
      1. If the variable(var) is byte, char, short or int, then var_code = (int)var;
      2. If the variable(var) is long, then var_code = (int)(var ^ (var >>> 32));
      3. If the variable(var) is float, then var_code = Float.floatToIntBits(var);
      4. If the variable(var) is double, then -
        long bits = Double.doubleToLongBits(var);
        var_code = (int)(bits ^ (bits >>> 32));
      5. If the variable(var) is boolean, then var_code = var ? 1 : 0;
      6. If the variable(var) is an object reference, then check if it is null, if yes then var_code = 0; otherwise invoke the hashCode method recursively on this object reference to get the hash code. This can be simplified and given as -
        var_code = (null == var ? 0 : var.hashCode());
    3. Combine this individual variable hash code var_code in the original hash code hash as follows -
      hash = 31 * hash + var_code;
    4. Follow these steps for all the significant variables and in the end return the resulting integer hash.
    5. Lastly, review your hashCode method and check if it is returning equal hash codes for equal objects. Also, verify that the hash codes returned for the object are consistently the same for multiple invocations during the same execution.
    The guidelines provided here for implementing equals and hashCode methods are merely useful as guidelines, these are not absolute laws or rules. Nevertheless, following them while implementing these two methods will certainly give you correct and consistent results.

    Summary & Miscellaneous Tips

    • Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.
    • The equals method provides "deep comparison" by checking if two objects are logically equal as opposed to the "shallow comparison" provided by the equality operator ==.
    • However, the equals method in java.lang.Object class only provides "shallow comparison", same as provided by the equality operator ==.
    • The equals method only takes Java objects as an argument, and not primitives; passing primitives will result in a compile time error.
    • Passing objects of different types to the equals method will never result in a compile time error or runtime error.
    • For standard Java wrapper classes and for java.lang.String, if the equals argument type (class) is different from the type of the object on which the equals method is invoked, it will return false.
    • The class java.lang.StringBuffer does not override the equals method, and hence it inherits the implementation from java.lang.Object class.
    • The equals method must not provide equality comparison with any built in Java class, as it would result in the violation of the symmetry requirement stated in the general contract of the equals method.
    • If null is passed as an argument to the equals method, it will return false.
    • Equal hash codes do not imply that the objects are equal.
    • return 1; is a legal implementation of the hashCode method, however it is a very bad implementation. It is legal because it ensures that equal objects will have equal hash codes, it also ensures that the hash code returned will be consistent for multiple invocations during the same execution. Thus, it does not violate the general contract of the hashCode method. It is a bad implementation because it returns same hash code for all the objects. This explanation applies to all implementations of the hashCode method which return same constant integer value for all the objects.
    • In standard JDK 1.4, the wrapper classes java.lang.Short, java.lang.Byte, java.lang.Character and java.lang.Integer simply return the value they represent as the hash code by typecasting it to an int.
    • Since JDK version 1.3, the class java.lang.String caches its hash code, i.e. it calculates the hash code only once and stores it in an instance variable and returns this value whenever the hashCode method is called. It is legal because java.lang.String represents an immutable string.
    • It is incorrect to involve a random number directly while computing the hash code of the class object, as it would not consistently return the same hash code for multiple invocations during the same execution.