Abstraction vs Encapsulation - Principles of Object Oriented Programming (OOPS)

Abstraction
In order to process something from the real world we have to extract the essential characteristics of that object.
Data abstraction can be viewed as the process of refining away the unimportant details of an object, so that only the useful characteristics that define it remain. Evidently, this is task specific.

Encapsulation
Encapsulation is one step beyond abstraction. Whilst abstraction involves reducing a real world entity to its essential defining characteristics, encapsulation extends this idea by also modeling and linking the functionality of that entity. Encapsulation links the data to the operations that can be performed upon the data.

OOP makes use of encapsulation to enforce the integrity of a type (i.e. to make sure data is used in an appropriate manner) by preventing programmers from accessing data in a non-intended manner


Through encapsulation, only a predetermined group of functions can access the data. The collective term for datatypes and operations (methods) bundled together with access restrictions (public/private, etc.) is a class

Basic differences between Oracle and SQL Server

ORACLE
  • Oracle provides password complexity enforcement rule.
  • Connect with one Schema and can work with other schema.
  • Oracle implemented the row versioning on the DB block level.
  • Oracle metadata is managed in the same manner as table data.So during data querying most of online DDL statements on the table can be performed simultaneously.
  • Starting from Oracle 9i the configuration of ROLLBACK SEGMENTS is automatic.
  • Oracle is well rich with Index Options.
  • Oracle provides Automatic Storage Management (ASM), which assists with RAC/Grid based cluster deployment.
  • Oracle provides proprietary cluster file system on Linux and Windows platforms that helps in avoiding the use of raw devices.
  • Oracle provides Materialized Views for performance improvements of Stored Data with multiple Tables.
  • Oracle has more recovery options for corrupted database, redo log or datafile than MSSQL.
MS SQL
Microsoft implemented row level lock based on each single row.
SQL Server
  • all DDL operations that are currently running on tables belong to database "Snapshot Isolation". "Snapshot Isolation" queries are prohibited.
  • SQL requires a complex setup of ROLLBACK Segments and Transaction Level use on it.
  • SQL has just BTREE Index while compare to Oracle.
  • SQL has limitations using Materialized Views.

What is the difference between DBMS and RDBMS?

DBMS :  Data Base Management System
1)A DBMS has to be persistent (it should be accessible when
the program created the data donot exist or even the
application that created the data restarted).
2) DBMS has to provide some uniform methods independent of a
specific application for accessing the information that is
stored.
3)DBMS does not impose any constraints or security with
regard to data manipulation. It is user or the programmer
responsibility to ensure the ACID PROPERTY of the database
4)In DBMS Normalization process will not be present

RDBMS:  Relational Data Base Management System

1)RDBMS is based on relational model, in which data is
represented in the form of relations, with enforced
relationships between the tables.
2)RDBMS defines the integrity constraint for the purpose of
holding ACID PROPERTY.
3)In RDBMS, normalization process will be present to check
the database table cosistency
4)RDBMS helps in recovery of the database in case of loss of
database due to system failure or any other reason

A DBMS has to be persistent, that is it should be accessible when theprogram created the data ceases to exist or even the application thatcreated the data restarted. A DBMS also has to provide some uniformmethods independent of a specific application for accessing theinformation that is stored.  
 Many DBA's think that RDBMS is a Client Server Database system but thats not the case with RDBMS.

5 Common Errors in Setting Java Heap Size

Two JVM options are often used to tune JVM heap size: -Xmx for maximum heap size, and -Xms for initial heap size. Here are some common mistakes I have seen when using them:

1. Only setting -Xms JVM option and its value is greater than the default maximum heap size, which is 64m. The default minimum heap size seems to be 0. For example,
      java -Xms128m BigApp
      Error occurred during initialization of VM
      Incompatible initial and maximum heap sizes specified
      The correct command should be java -Xms128m -Xmx128m BigApp. It’s a good idea to set the minimum and maximum heap size to the same value. In any case, don’t let the minimum heap size exceed the maximum heap size.
Heap size is larger than your computer’s physical memory. For example,
      java -Xmx2g BigApp
      Error occurred during initialization of VM
      Could not reserve enough space for object heap
      Could not create the Java virtual machine.
      The fix is to make it lower than the physical memory: java -Xmx1g BigApp
    2.Incorrectly use mb as the unit, where m or M should be used instead.
      java -Xms256mb -Xmx256mb BigApp
      Invalid initial heap size: -Xms256mb
      Could not create the Java virtual machine.
    3 The heap size is larger than JVM thinks you would ever need. For example,
      java -Xmx256g BigApp
      Invalid maximum heap size: -Xmx256g
      The specified size exceeds the maximum representable size.
      Could not create the Java virtual machine.
      The fix is to lower it to a reasonable value: java -Xmx256m BigApp
    4.The value is not expressed in whole number. For example,
      java -Xmx0.9g BigApp
      Invalid maximum heap size: -Xmx0.9g
      Could not create the Java virtual machine.
      The correct command should be java -Xmx928m BigApp
NOTE:
How to set java heap size in Tomcat?
Stop Tomcat server, set environment variable CATALINA_OPTS, and then restart Tomcat. Look at the file tomcat-install/bin/catalina.sh or catalina.bat for how this variable is used. For example,
set CATALINA_OPTS=”-Xms512m -Xmx512m”  (Windows)
export CATALINA_OPTS=”-Xms512m -Xmx512m”  (ksh/bash)
setenv CATALINA_OPTS “-Xms512m -Xmx512m”  (tcsh/csh)
In catalina.bat or catallina.sh, you may have noticed CATALINA_OPTS, JAVA_OPTS, or both can be used to specify Tomcat JVM options. What is the difference between CATALINA_OPTS and JAVA_OPTS? The name CATALINA_OPTS is specific for Tomcat servlet container, whereas JAVA_OPTS may be used by other java applications (e.g., JBoss). Since environment variables are shared by all applications, we don’t want Tomcat to inadvertently pick up the JVM options intended for other apps. I prefer to use CATALINA_OPTS.
How to set java heap size in JBoss?
Stop JBoss server, edit $JBOSS_HOME/bin/run.conf, and then restart JBoss server. You can change the line with JAVA_OPTS to something like:
JAVA_OPTS=”-server -Xms128m -Xmx128m”
How to set java heap size in Eclipse?
You have 2 options:
1. Edit eclipse-home/eclipse.ini to be something like the following and restart Eclipse.
-vmargs
-Xms64m
-Xmx256m
2. Or, you can just run eclipse command with additional options at the very end. Anything after -vmargs will be treated as JVM options and passed directly to the JVM. JVM options specified in the command line this way will always override those in eclipse.ini. For example,
eclipse -vmargs -Xms64m -Xmx256m
How to set java heap size in NetBeans?
Exit NetBeans, edit the file netbeans-install/etc/netbeans.conf. For example,
netbeans_default_options=”-J-Xms512m -J-Xmx512m -J-XX:PermSize=32m -J-XX:MaxPermSize=128m -J-Xverify:none
How to set java heap size in Apache Ant?
Set environment variable ANT_OPTS. Look at the file $ANT_HOME/bin/ant or %ANT_HOME%\bin\ant.bat, for how this variable is used by Ant runtime.
set ANT_OPTS=”-Xms512m -Xmx512m”  (Windows)
export ANT_OPTS=”-Xms512m -Xmx512m”  (ksh/bash)
setenv ANT_OPTS “-Xms512m -Xmx512m”  (tcsh/csh)
How to set java heap size in jEdit?
jEdit is a java application, and basically you need to set minimum/maximum heap size JVM options when you run java command. jEdit by default runs with a default maximum heap size 64m. When you work on large files, you are likely to get these errors:
java.lang.OutOfMemoryError: Java heap space
at java.lang.String.concat(String.java:2001)
at org.gjt.sp.jedit.buffer.UndoManager.contentInserted(UndoManager.java:160)
at org.gjt.sp.jedit.Buffer.insert(Buffer.java:1139)
at org.gjt.sp.jedit.textarea.JEditTextArea.setSelectedText(JEditTextArea.java:2052)
at org.gjt.sp.jedit.textarea.JEditTextArea.setSelectedText(JEditTextArea.java:2028)
at org.gjt.sp.jedit.Registers.paste(Registers.java:263)
How to fix it? If you click a desktop icon, or Start menu item to start jEdit: right-click the icon or menu item, view its property, and you can see its target is something like:
C:\jdk6\bin\javaw.exe -jar “C:\jedit\jedit.jar”
You can change that line to:
C:\jdk6\bin\javaw.exe -Xmx128m -Xms128m -jar “C:\jedit\jedit.jar”
If you run a script to start jEdit: just add these JVM options to the java line inside the script file:
java -Xmx128m -Xms128m -jar jedit.jar
If you start jEdit by running java command: just add these JVM options to your java command:
java -Xmx128m -Xms128m -jar jedit.jar
Note that when you run java with -jar option, anything after -jar jar-file will be treated as application arguments. So you should always put JVM options before -jar. Otherwise, you will get error:
C:\jedit>java -jar jedit.jar -Xmx128m
Unknown option: -Xmx128m
Usage: jedit [] []
How to set java heap size in JavaEE SDK/J2EE SDK/Glassfish/Sun Java System Application Server?
Stop the application server, edit
$GLASSFISH_HOME/domains/domain1/config/domain.xml, search for XML element name java-config and jvm-options. For example,

-Xmx512m
-XX:NewRatio=2
-XX:MaxPermSize=128m

You can also change these settings in the web-based admin console, typically at http://localhost:4848/, or https://localhost:4848/. Go to Application Server near the top of the left panel, and then on the right panel, click JVM Settings -> JVM Options, and you will see a list of existing JVM options. You can add new ones and modify existing ones there.
Yet another option is to use its Command Line Interface (CLI) tool command, such as:
./asadmin help create-jvm-options
./asadmin help delete-jvm-options
They may be a bit hard to use manually, but are well suited for automated scripts.

JavaScript: Dynamically Add/Remove rows in HTML table

This article shows you how to add rows to a HTML table dynamically, using DHTML and JavaScript - without requiring a round trip to the web server. I used this technique in a project to build a data entry grid, where the users wanted the flexibility to add or remove rows easily before doing a final submit/save. 
Source Code:

<HTML>
<HEAD>
     <TITLE> Dynamically Add/Remove rows in HTML table TITLE>
     <SCRIPT language="javascript">
          FUNCTION addRow(tableID) {
 
               VAR table = document.getElementById(tableID);
 
               VAR rowCount = table.rows.length;
               VAR row = table.insertRow(rowCount);
 
               VAR cell1 = row.insertCell(0);
               VAR element1 = document.createElement("input");
               element1.type = "checkbox";
               cell1.appendChild(element1);
 
               VAR cell2 = row.insertCell(1);
               cell2.innerHTML = rowCount + 1;
 
               VAR cell3 = row.insertCell(2);
               VAR element2 = document.createElement("input");
               element2.type = "text";
               cell3.appendChild(element2);
 
          }
 
          FUNCTION deleteRow(tableID) {
               TRY {
               VAR table = document.getElementById(tableID);
               VAR rowCount = table.rows.length;
 
               FOR(VAR i=0; i<rowCount; i++) {
                    VAR row = table.rows[i];
                    VAR chkbox = row.cells[0].childNodes[0];
                    IF(NULL != chkbox && TRUE == chkbox.checked) {
                         table.deleteRow(i);
                         rowCount--;
                         i--;
                    }
 
               }
               }CATCH(e) {
                    ALERT(e);
               }
          }
 
     SCRIPT>
HEAD>
<BODY>
 
     <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
 
     <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
 
     <TABLE id="dataTable" width="350px" border="1">
          <TR>
               <TD><INPUT type="checkbox" NAME="chk"/>TD>
               <TD> 1 TD>
               <TD> <INPUT type="text" /> TD>
          TR>
     TABLE>
 
BODY>
HTML>

How to Convert Exponential Form of a number to Decimal Form in java

In Java you will see that most of the value are displayed in Exponential form while using Doubles and Long.


Example:
In following we are multiplying 4.58 with 10000 and the result is printed.
Double a = 4.58d / 10000;
System.out.println( a.doubleValue());
 
a = 2.85d * 100000000;
System.out.println( a.doubleValue());
Result:
4.58E-4
 4.58E8
You can do this simply by using class java.math.BigDecimal. In following example we are using BigDecimal.valueOf() to convert the Double value to BigDecimal and than .toPlainString() to convert it into plain decimal string.

import java.math.BigDecimal;
Double a = 4.58d / 10000;
System.out.println(BigDecimal.valueOf(a).toPlainString());
 a = 4.58d * 100000000;
System.out.println(BigDecimal.valueOf(a).toPlainString());
Result:
0.000458 
458000000

How to get JVM heap size, used memory, total memory using Java Runtime

Java’s Runtime class provide lot of information about the resource details of Java Virtual Machine or JVM. The memory consumed by the JVM can be read by different methods in Runtime class.
Following is the small example of getting/reading JVM Heap Size, Total Memory and used memory using Java Runtime api.

public class Memoryusage{
 
    public static void main(String [] args) {
 
        int mb = 1024*1024;
 
        //Getting the runtime reference from system
        Runtime runtime = Runtime.getRuntime();
 
        System.out.println("Heap Space usage in MB");
 
        //Print used memory
        System.out.println("Used Memory:"
            + (runtime.totalMemory() - runtime.freeMemory()) / mb);
 
        //Print free memory
        System.out.println("Free Memory:"
            + runtime.freeMemory() / mb);
 
        //Print total available memory
        System.out.println("Total Memory:" + runtime.totalMemory() / mb);
 
        //Print Maximum available memory
        System.out.println("Max Memory:" + runtime.maxMemory() / mb);
    }

Increase heap size in Java to prevent java.lang.OutOfMemoryError

Java programs executes in JVM uses Heap of memory to manage the data. If your Java program requires a large amount of memory, it is possible that the virtual machine will begin to throw OutOfMemoryError instances when attempting to instantiate an object. The default heap size if 1 MB and can increase as much as 16 MB.

Setting/Increase JVM heap size

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.
Following are few options available to change Heap Size.

1
2
3
-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

What is Java Heap Space in Java virtual Machine JVM?

Java heap is the heap size allocated to JVM applications which takes care of the new objects being created. If the objects being created exceed the heap size, it will throw an error saying memoryOutof Bound
Java's default heap size limit is 128MB.
It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.
Following are few options available to change Heap Size.

-Xms        set initial Java heap size
-Xmx        set maximum Java heap size
-Xss        set java thread stack size

Tuning Garbage collection with the 1.4.2 Hotspot JVM

  • For many applications garbage collection performance is not significant
  • Default collector should be first choice
There are essentially two GC threads running. One is a very lightweight thread which does "little" collections primarily on the Eden (a.k.a. Young) generation of the heap. The other is the Full GC thread which traverses the entire heap when there is not enough memory left to allocate space for objects which get promoted from the Eden to the older generation(s).
If there is a memory leak or inadequate heap allocated, eventually the older generation will start to run out of room causing the Full GC thread to run (nearly) continuously. Since this process "stops the world", Resin won't be able to respond to requests and they'll start to back up.
Read More on Tuning Garbage collection with the 1.4.2 Hotspot JVM

DB/DBM configuration in DB2 on Z/OS, OS/390 or AS/400

Question:
I could connect to DB2 database on AS/400, but cannot> see any DBM or DB configuration. Is database or database manager> configuration available for DB2 on Z/OS, OS/390 or AS/400?
Solution:
Most of the config parms for DB2 for z/OS are in the zparms. The zparms arenot closely related to either the db or dbm configuration parms on DB2 forLinux, UNIX, and Windows. Usually only the DB2 systems programmer (not theDBA) can change the zparms.

How to Automate the process of importing file from IBM Mainframes to spreedsheet

Scenario:
I have a TAB Delimited and it contain 10 fields., and Presently this is downloading into testfile.txt importing into excel spreedsheet.
Now, I need to automate this process. by writing a program which sends this file to Spreadsheet.


Solution:
A spreadsheet is not a mainframe entity, so can not be created on the mainframe.

As far as I can remember, this could not be done by a mainframe process, and that the current way that this task is currently being performed is the only way.


Read More on this artcile from IBM Mainfarmes Forums

JCL to unzip the file zipped in unix by using gzip

Question:

Can Someone let me know how to ZIP file from UNIX system and UNZIP in Mainframes.
We have PKZIP in our system os/390
Can any one have the JCL to unzip the file zipped in unix by using gzip. 


Solution:


gunzip and gzip typically work under Unix System Services (USS) on USS files.
If you're asking for specific JCL to run PKZIP against your file, shouldn't you contact your site support group or the PKZIP vendor for assistance and/or the manual? The precise JCL will be site-dependent and may vary depending on how and where PKZIP was installed. 

How to convert File from UNIX to IBM Mainframes using PKZIP in os/390?

Question : We have a ZIP file in the Unix System and want to UNZIP it in the mainframes.

Solution:

The previous versions of PKZIP have supported GZIP, so I have to believe that the newest versions do also.

just downloaded a copy of the PKZIP for z/OS Version 9 User's Guide, and Chapter 12 is actually titled Processing with GZIP.

According to the manual, you need to specify:

-ARCHIVE_ZIPFORMAT(GZIP)

and has a few notes:

The GZIP standard does not support PKWARE archive attributes; therefore, some
SecureZIP features are not available for use when the GZIP format is enabled. Some
features which are excluded from use are: strong encryption, digital signatures,
multiple files per GZIP stream, self-extracting archives.
• When enabled with GZIP, password-based 96-bit encryption is supported for decryption
under PKZIP for MVS, PKZIP for zSeries, PKZIP for OS/400, PKZIP for i5/OS,
SecureZIP for i5/OS, PKZIP for z/OS, and SecureZIP for z/OS.
• When processing input GZIP archives, see also: GZIP_SUFFIX and GZIPCRC_IGNORE

How can I recursively grep through sub-directories ? | Unix Tutorial |Linux / UNIX Recursively Search All Files For A String

Question :How do i recursively grep (search text files) in unix?

For example, if i want to find the word "hello" in a unix directory /tmp and all its subdirectories in the .log files?  i want the file name, file path, and line number with context.


Solution:


find /tmp -name \*.log -exec grep pall {} \; -exec ls -l {} \;

The find command you probably know. It searches for files or directorys where you want him to search and to what pattern to match.

So :
"find /tmp" says only start searching in /tmp
"-name \*.log" says to look for all files or directory ending with "log" the \ before the star says to not look for a file or directory named "*log" but to make it a pattern
"-exec grep pall {} \;" says that the result of find in /tmp with the pattern ending on "log" should do the following : "grep hello /tmp/script" so {} \; is replaced with the current result. It's hard to explain the syntax, I think you should just take this as it is and copy the syntax when you need it
"-exec ls -l {} \;" has the same syntax and executes the ls -l command for the current result. If you don't do this last -exec you don't know what file he grep the text from.

How to Create a Blank DOM Document | Java DOM Tutorial complete guide to DOM

This tutorial shows you how to create blank DOM document.
JAXP is a Java interface that provides Parsing XML documents.
The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser.
Creating an Empty DOM Document

public static Document createDomDocument() {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.newDocument();
        return doc;
    } catch (ParserConfigurationException e) {
    }
    return null;
}
Explanation:
DocumentBuilder builder = Factory.newDocumentBuilder():- This method creates a DocumentBuilder object with the help of a DocumentBuilderFactory
Document doc = builder.newDocument():- This method obtain a new instance of a DOM Document object to build a DOM tree.

XML,XML Tutorials,XML Examples,XML Example,Java DOM Tutorial

What is DOM?

The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.

The DOM is an interface that exposes an XML document as a tree structure comprised of nodes. The DOM allows you to programmatically navigate the tree and add, change and delete any of its elements.

XML and Java Parsing XML using Java Tutorial

SAX parser is a Event Driven Parser. You provide the callback methods, and the parser invokes them as it reads the XML data. Finally, you can't "back up" to an earlier part of the document, or rearrange it, any more than you can back up a serial data stream or rearrange characters you have read from that stream. The following Packages need to be imported in your Java File to use the SAX parser.
import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;

public class BooksLibrary extends HandlerBase
{
...
}
Next Let's declare the Main method and also setup the Parser
public static void main (String argv [])
{
  SAXParserFactory factory = SAXParserFactory.newInstance();
  try {

        out = new OutputStreamWriter (System.out, "UTF8");
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse( new File(XML_FILE_NAME), new BooksLibrary() );

  } catch (Throwable err) {
        err.printStackTrace ();
  }
}
As seen above first we get a new instance of SAXParserFactory and from this one we create a new Instance of SaxParser. To the Parse Method of SaxParser, we pass two parameters, name of the XML File and the class which implements interface HandlerBase
Currently in our Code, the same JavaFile, BooksLibrary.java implements interface HandlerBase.
Note:
    The javax.xml.parsers.SAXParser class is a wrapper that defines a number of convenience methods. It wraps the org.xml.sax.Parser object. If needed, you can obtain that parser using the SAXParser's getParser() method.
The Following Methods needs to be implemented from the DocumentHandlerBase Interface, and Description above each methods explains when this Method is called. These Methods are called automatically while parsing the XML file and when the corresponding data element is reached. Please refer to the attached Java Source File  to see how these methods are implemented. When you run this Program the output will clearly show When a attribute is reached and when a Element is reached and how each of these methods are called.

Parsing / Reading XML file in Java Using org.w3c.dom parser

I have a Piece of code which can be used to Parse a XML file using java DOM Parser.

Step 1: Create a XML file as below

<?xml version="1.0"?>
<Employees>
    <Employee>
        <name>Melvyn</name>
        <grade>B</grade>
        <age>23</age>
    </Employee>
    <Employee>
        <name>Nixon</name>
        <grade>A</grade>
        <age>25</age>
    </Employee>
    <Employee>
        <name>Bruce</name>
        <grade>A</grade>
        <age>28</age>
    </Employee>
</Employees>

2.Java Code to Read the XML file

package net.viralpatel.java.xmlparser;
 
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class XMLParser {
 
    public void getAllUserNames(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            File file = new File(fileName);
            if (file.exists()) {
                Document doc = db.parse(file);
                Element docEle = doc.getDocumentElement();
 
                // Print root element of the document
                System.out.println("Root element of the document: "
                        + docEle.getNodeName());
 
                NodeList EmployeeList = docEle.getElementsByTagName("Employee");
 
                // Print total Employee elements in document
                System.out
                        .println("Total Employees: " + EmployeeList.getLength());
 
                if (EmployeeList != null && EmployeeList.getLength() > 0) {
                    for (int i = 0; i < EmployeeList.getLength(); i++) {
 
                        Node node = EmployeeList.item(i);
 
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
 
                            System.out
                                    .println("=====================");
 
                            Element e = (Element) node;
                            NodeList nodeList = e.getElementsByTagName("name");
                            System.out.println("Name: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
 
                            nodeList = e.getElementsByTagName("grade");
                            System.out.println("Grade: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
 
                            nodeList = e.getElementsByTagName("age");
                            System.out.println("Age: "
                                    + nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue());
                        }
                    }
                } else {
                    System.exit(1);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    public static void main(String[] args) {
 
        XMLParser parser = new XMLParser();
        parser.getAllUserNames("c:\\test.xml");
    }
}

Following is the output of our XML parser.
Program Output

Root element of the document: students
Total Employees: 3
==============================
Name: Melvyn
Grade: B
Age: 23
==============================
Name: Nixon
Grade: A
Age: 25
==============================
Name: Bruce
Grade: A
Age: 28

How to read XML file in Java using DOM Parser

Here’s an example to demonstrate how to read a XML file in Java with DOM parser. The DOM interface is the easiest to understand. It parses an entire XML document and load it into memory, modeling it with Object for the traversal.

Step 1:Create a XML File

<?xml version="1.0"?>
<company>
    <Employee>
        <firstname>yong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
    </Employee>
    <Employee>
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>200000</salary>
    </Employee>
</company>

2.Create a Java File to Process this XML file

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

 public static void main(String argv[]) {

 try {

    File fXmlFile = new File("c:\\file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("Employee");
    System.out.println("-----------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

       Node nNode = nList.item(temp);      
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;

          System.out.println("First Name : "  + getTagValue("firstname",eElement));
          System.out.println("Last Name : "  + getTagValue("lastname",eElement));
          System.out.println("Nick Name : "  + getTagValue("nickname",eElement));
          System.out.println("Salary : "  + getTagValue("salary",eElement));

        }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }

 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();   
 }

}

How to read XML file in Java using SAX Parser ?

SAX parser is work differently with DOM parser, it does not load any XML document into memory and create some object representation of the XML document. Instead, the SAX parser use callback function (org.xml.sax.helpers.DefaultHandler) to informs clients of the XML document structure.

Let’s start to see how to read a XML file with SAX parser.

1. Create a XML file

Create a simple XML file as following

<?xml version="1.0"?>
<company>
 <Employee>
  <firstname>yong</firstname>
  <lastname>mook kim</lastname>
  <nickname>mkyong</nickname>
  <salary>60000</salary>
 </Employee>
 <Employee>
  <firstname>low</firstname>
  <lastname>yin fong</lastname>
  <nickname>fong fong</nickname>
  <salary>30000</salary>
 </Employee>
</company>

2. Create a Java file

Use SAX parser to parse the XML file.

package com.mkyong.test;
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
public class ReadXMLFileSAX {
 
 public static void main(String argv[]) {
 
  try {
 
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser = factory.newSAXParser();
 
     DefaultHandler handler = new DefaultHandler() {
 
     boolean bfname = false;
     boolean blname = false;
     boolean bnname = false;
     boolean bsalary = false;
 
     public void startElement(String uri, String localName,
        String qName, Attributes attributes)
        throws SAXException {
 
        System.out.println("Start Element :" + qName);
 
        if (qName.equalsIgnoreCase("FIRSTNAME")) {
           bfname = true;
        }
 
        if (qName.equalsIgnoreCase("LASTNAME")) {
           blname = true;
        }
 
        if (qName.equalsIgnoreCase("NICKNAME")) {
           bnname = true;
        }
 
        if (qName.equalsIgnoreCase("SALARY")) {
           bsalary = true;
        }
 
     }
 
     public void endElement(String uri, String localName,
          String qName)
          throws SAXException {
 
          System.out.println("End Element :" + qName);
 
     }
 
     public void characters(char ch[], int start, int length)
         throws SAXException {
 
         if (bfname) {
            System.out.println("First Name : "
                + new String(ch, start, length));
            bfname = false;
          }
 
          if (blname) {
              System.out.println("Last Name : "
                  + new String(ch, start, length));
              blname = false;
           }
 
          if (bnname) {
              System.out.println("Nick Name : "
                  + new String(ch, start, length));
              bnname = false;
           }
 
          if (bsalary) {
              System.out.println("Salary : "
                  + new String(ch, start, length));
              bsalary = false;
           }
 
        }
 
      };
 
      saxParser.parse("c:\\file.xml", handler);
 
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
}

  • startDocument() and endDocument() – methods called at the start and end of an XML document.
  • startElement() and endElement() – methods called at the start and end of a document element.
  • characters() – method called with the text contents in between the start and end tags of an XML document element.

WebLogic Server and Oracle Real Application Clusters (RAC)

Oracle Real Application Clusters (RAC) is a software component you can add to a high-availabitlity solution that enables users on multiple machines to access a single database with increased performance. RAC comprises of two or more Oracle databases instances running on tow or more clustered machines and accessing a shared storage device via cluster technology. Oracle RAC offers the following features to applications on WebLogic Server:

    * Scalability: A RAC appears lika a single Oracle database and is maintained using the same tools and practices. All nodes in the cluster execute transactions against the same database. RAC coordinates access to the shared data to ensure consistency, and integrity. Nodes can be added to the cluster without partitioning data (Horizontal scaling).
    * Availability: Depending on the configuration, when a RAC node fails, in-flight transactions are redirected to another node in the cluster either by WebLogic Server or Oracle Thin driver. The fail-over is not for failed connections. Fail-over is only for transactions, which will be driven to completion, based on the time of failure.
    * Load Balancing: BEA supports load balancing capability with Oracle RAC servers, through multi-data sources
    * Failover: BEA recommends using WebLogic JDBC multi data sources to handle failover. Transparent Application Failover is not supported with WebLogic Server due to the requirement of Oracle OCI driver which is not supported by BEA.

Configuration Options
BEA supports several configuration options for using Oracle RAC with WebLogic Server:

   1. Multiple RAC instances with Global Transactions: BEA recommends the use of transaction-aware WebLogic JDBC multi data sources, which support failover and load balancing, to connect to RAC nodes.
   2. Multiple RAC instances without XA transactions: BEA recommends the use of (non-transaction-aware_ multi data sources to connect to the RAC nodes. Use the standard multi data source configuration, which supports failover and load balancing.
   3. Multiple RAC nodes when multi data sources are not an option: Use Oracle RAC with connect-time failover. Load balancing is not supported in this configuration.

Limitations:A detailed explanation of the following limitations can be found on WebLogic site

   1. Since Oracle requires that a Global Transaction must be initiated, prepared, and concluded in the same instance of the RAC cluster, and since Oracle Thin driver cannot guarantee that a transaction is initiated and concluded on the same RAC instance when when the driver is configured for load balancing, you cannot use connect-time load balancing wihen using XA with Oracle RAC.
   2. There is a potential for Inconsistent Transaction Completion
   3. Potential for Data Deadlocks in Some Failure scenarios
   4. Potential for Transactions Completed out of sequence.

WebSphere Application Server V6.1: JMS Problem Determination

This article describes problem determination information for WebSphere Application Server V6.1 JMS application users. It discusses problem diagnosis for JMS applications using the default messaging provider and the WebSphere MQ provider. The paper also includes information for WebSphere Application Server V6.1 on distributed platforms and z/OS. It also takes to diagnose a JMS related problem in a WebSphere Application Server V6.1 environment.
Table of Contents :
Chapter 1. Introduction to JMS problem determination
Chapter 2. Messaging engine problem determination
Chapter 3. Message store problem determination
Chapter 4. Message store with data store persistence
Chapter 5. File store problem determination
Chapter 6. JMS application problem determination
Chapter 7. Messaging in a multiple messaging engine environment
Chapter 8. Clustering problem determination
Chapter 9. Message-driven beans problem determination
Chapter 10. WebSphere MQ and MDBs
Chapter 11. WebSphere MQ Server problem determination
Chapter 12. WebSphere MQ configuration
Chapter 13. WebSphere MQ link problem determination
Chapter 14. JMS application with WebSphere MQ problem determination
Chapter 15. Foreign bus problem determination
Chapter 16. Mediation problem determination
Chapter 17. Default messaging provider security
Chapter 18. The next step
Article on WebSphere Application Server V6.1: JMS Problem Determination

WebSphere Application Server V6: Web Server Plug-In Problem Determination

Hi Guys,I have checked in Internet to find the best articles on  WebSphere Application Server V6: Web Server Plug-In Problem Determination.After checking each and every website i found the below article from redbooks very useful.So i am sharing the link  and the details.Hope this will be helpful for you.

This Article describes the techniques for diagnosing problems that are related to the Web server plug-in for WebSphere Application Server V6, including those resulting from configuration errors. The Web server plug-ins handle communications between a Web server and the Web container in an application server or servers. The Web server plug-in works with six different Web servers. However, this paper concentrates on the IBM HTTP Server and its plug-in. It does not address Web server problems or problems that are related to the application server Web container. 

Tutorial on WebSphere Application Server V6: Web Server Plug-In Problem Determination

How to Resolve Memory Leak Problems in a Websphere? |Memory leak detection and analysis in WebSphere Application Server

There are four common categories of memory usage problems in Java:
  • Java heap memory leaks
  • Heap fragmentation
  • Insufficient memory resources
  • Native memory leaks
The common causes for Java heap memory leaks are:
  • Insertion without deletion into collections
  • Unbounded caches
  • Un-invoked listener methods
  • Infinite loops
  • Too many session objects
  • Poorly written custom data structures.
Memory usage problems due to insufficient memory resources can be caused by:
  • Configuration issues (allocating too little memory for heap).
  • System capacity issues(too little physical memory).
Native memory leaks are memory leaks in non-Java cod, for example:
  • Type-II JDBC drivers
  • fragmentation in the non-heap segment of the Java process's address space.
WebSphere Application Server and higher provides a two-stage solution for detection and analysis of memory leaks
  • In the first stage, a lightweight memory leak detection mechanism running within the production WebSphere Application Server uses inexpensive, universally available Java heap usage statistics to monitor memory usage trends, and provides early notification of memory leaks. An automated heap dump generation facility (available in WebSphere Application Server running on IBM JDKs)generates multiple heap dumps that have been coordinated with sufficient memory leakage to facilitate comparative analysis using MDD4J.
  • The second stagethe Memory Dump Diagnostic for Java (MDD4J) is used to analyze heap dumps outside the production application server
More Information on this Arcticle

How to Open Recycle Bin With Run Command in Windows MS-DOS

You can mess around with it using various windows API's... from VB/.NET/etc

You'll also find the folders in C:\$Recycle.Bin\{}\ or C:\$RECYCLER\{

An alternative way to open Recycle Bin

    * Click on Start and go to Run.
    * Type "::{645FF040-5081-101B-9F08-00AA002F954E}" without quotes.
    * Click OK or press Enter.

Handling Oracle Large Objects with JDBC,LOBs (Large OBjects),Character Large Object (CLOB) and Binary Large Object(BLOB)

LOBs (Large OBjects) are are designed to support large unstructured data such as text, images, video etc. Oracle supports the following two types of LOBs:
  • Character Large Object (CLOB) and Binary Large Object(BLOB) are stored in the database either in-line in the table or in a separate segment or tablespace.
  • BFILEs are large binary data objects stored in operating system files outside of database tablespaces.
Oracle extension classes are provided to support these types objects in JDBC like oracle.sql.CLOB, oracle.sql.BLOB. While you can use java.sql.Blob and java.sql.Clob, oracle extensions provide added functionalities, such as adding bytes specific positions (getBytes(int pos, byte[] data) etc.


Working with LOB Data

CLOB and the BLOB objects are not created and managed in the same way as the ordinary types such as VARCHAR. To work with LOB data, you must first obtain a LOB locator. Then you can read or write LOB data and perform data manipulation. Use the ResultSet's getBlob method to obtain the LOB locator, and then you can obtain the a Stream of the blob to read/write to the Blob
Blob blob = rs.getBlob(1);
InputStream is = blob.getBinaryStream();
OutputStream os = blob.setBinaryStream(1);
The following example shows how to insert, read and write Blobs to Oracle from Java. The table here has only two columns (IMAGE_ID and IMAGE) IMAGE is a BLOB.


package data;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BlobTest {

 public void insertBlob(String imageId, String fileName) {
   Connection conn = null;
   try {
     conn = getConnection();
     if (!fileName.equals("")) {
       PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES(?, ?)");
       ps.setString(1, imageId);
       FileInputStream fis = new FileInputStream(fileName);
       ps.setBinaryStream(2, fis, fis.available());
       ps.execute();
       ps.close();
     } else {
       PreparedStatement ps = conn.prepareStatement("INSERT INTO IMAGES VALUES (?, empty_blob())");
       ps.setString(1, imageId);
       ps.execute();
       ps.close();

     }
     conn.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }

 public void readBlob(String fileName) {
   Connection conn = null;
   try {
     conn = getConnection();
     Statement st = conn.createStatement();
     ResultSet rs = st.executeQuery("SELECT IMAGE FROM IMAGES");
     while (rs.next()) {
        // The following two lines can be replaced by
        // InputStream is = rs.getBinaryStream(1);
       Blob blob = rs.getBlob(1);
       InputStream is = blob.getBinaryStream();
       FileOutputStream fos = null;

       fos = new FileOutputStream("c:/TEMP/" + fileName);
       byte[] data = new byte[1024];
       int i = 0;
       while ((i = is.read(data)) != -1) {
         fos.write(data, 0, i);
       }
     }
     conn.close();

   } catch (Exception e) {
     e.printStackTrace();
   }
 }

 public void writeBlob(String fileName) {
   Connection conn = null;
   try {
     conn = getConnection();
     Statement st = conn.createStatement();
     ResultSet rs = st.executeQuery("SELECT IMAGE FROM IMAGES FOR UPDATE");
     while (rs.next()) {
       Blob blob = rs.getBlob(1);
       System.out.println(blob);
        OutputStream os = blob.setBinaryStream(1);
       FileInputStream fis = null;
       fis = new FileInputStream("c:/TEMP/" + fileName);
       byte[] data = new byte[1];
       int i;
       while ((i = fis.read(data)) != -1) {
         os.write(data, 0, i);
       }
       os.close();
       break;
     }
     conn.close();

   } catch (Exception e) {
     e.printStackTrace();
   }
 }

 private Connection getConnection() throws ClassNotFoundException, SQLException {
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "scott", "tiger");
   return conn;
 }

 public static void main(String[] args) {
   BlobTest blobTest = new BlobTest();
   blobTest.insertBlob("img1", "");
   blobTest.writeBlob("2.gif");

 }
}