tag:blogger.com,1999:blog-55537078590498594642023-12-20T18:42:16.161-08:00Java Programs and Examples with OutputUnknownnoreply@blogger.comBlogger683125tag:blogger.com,1999:blog-5553707859049859464.post-84177778601573498452014-08-13T15:27:00.000-07:002014-08-13T15:27:27.774-07:00Java program to create a Binary Heap and Perform various operation<div dir="ltr" style="text-align: left;" trbidi="on">
A binary heap (min-heap) is a complete binary tree with elements from a
partially ordered set, such that the element at every node is less than (or
equal to) the the element at it's left and right child.<br />
<br />
This Binary Heap is a min-heap implemented with one-based array (root is
element 1; children of element n are elements 2n and 2n+1) for simplicity.<br />
<br />
<b><i>Complexity</i></b>: Space O(n), findMin O(1), insert O(logn), deleteMin O(logn),
buildHeap O(n);
<br />
<br />
<pre class="java" name="code">class BinaryHeap {
private int nodes[];
private int size;
private int capacity;
public BinaryHeap(int capacity) {
this.size = 0;
this.capacity = capacity;
this.nodes = new int[capacity + 1];
}
public int size() {
return size;
}
public int findMin() {
if (size <= 0) {
throw new RuntimeException("Empty Heap is empty.");
}
return nodes[1];
}
public void insert(int e) {
if (size >= capacity) {
throw new RuntimeException("Heap overflow.");
}
size++;
nodes[size] = e;
percolateUp();
}
public int deleteMin() {
if (size <= 0) {
throw new RuntimeException("Empty Heap is empty.");
}
int min = findMin();
nodes[1] = nodes[size];
size--;
percolateDown();
return min;
}
private void percolateDown() {
int index = 1;
while (true) {
int child = index * 2;
if (child > size)
break;
if (child + 1 <= size) {
// if there are two children -> take the smallest or
// if they are equal take the left one
child = findMin(child, child + 1);
}
if (nodes[index] <= nodes[child])
break;
swap(index, child);
index = child;
}
}
private void percolateUp() {
int index = size();
while (index > 1) {
int parent = index / 2;
if (nodes[index] >= nodes[parent])
break;
swap(index, parent);
index = parent;
}
}
private void swap(int i, int j) {
int temp = nodes[i];
nodes[i] = nodes[j];
nodes[j] = temp;
}
private int findMin(int leftChild, int rightChild) {
if (nodes[leftChild] <= nodes[rightChild]) {
return leftChild;
} else {
return rightChild;
}
}
public static void main(String[] args) {
BinaryHeap bh = new BinaryHeap(10);
bh.insert(7);
bh.insert(5);
bh.insert(9);
bh.insert(6);
bh.insert(4);
bh.insert(8);
bh.insert(10);
bh.insert(1);
bh.insert(3);
bh.insert(2);
System.out.println("Size of Binary Heap is : " + bh.size());
System.out.println("Delete min from Binary Heap : " + bh.deleteMin());
System.out.println("Size of Binary Heap is : " + bh.size());
System.out.println("Delete min from Binary Heap : " + bh.deleteMin());
System.out.println("Size of Binary Heap is : " + bh.size());
}
}
</pre>
<br />
<b>Output of this Program</b>
<br />
<pre class="" style="background-color: white !important; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; border: 0px; color: #333333; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 13px; line-height: 20px; padding: 0px !important; tab-size: 4; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;">Size of Binary Heap is : 10
Delete min from Binary Heap : 1
Size of Binary Heap is : 9
Delete min from Binary Heap : 2
Size of Binary Heap is : 8
</pre>
<div>
<br /></div>
<div style="text-align: left;">
<span style="font-size: large;">Try this by Yourself : </span><a href="http://ideone.com/FnSiPv">http://ideone.com/FnSiPv</a></div>
</div>
Happy Coderhttp://www.blogger.com/profile/10351448605389567935noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-80438019078372614502014-08-13T15:07:00.001-07:002014-08-13T15:07:58.674-07:00Create an Adjacency matrix Graph and perform Add and Remove operation<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<pre class="java" name="code">import java.util.ArrayList;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
/**
* Implementation of a directed unweighted Graph using Adjacency Matrix
*
* Complexity: addEdge, removeEdge, hasEdge O(1) / outEdges, inEdges O(n) /
* Space O(n^2)
*/
public class AdjMatrixGraph {
int size;
private boolean[][] matrix;
public static final byte WHITE = 1;
public static final byte GREY = 2;
public AdjMatrixGraph(int size) {
this.size = size;
this.matrix = new boolean[size][size];
}
public void addEdge(int nodeA, int nodeB) {
matrix[nodeA][nodeB] = true;
}
public void removeEdge(int nodeA, int nodeB) {
matrix[nodeA][nodeB] = false;
}
public boolean hasEdge(int nodeA, int nodeB) {
return matrix[nodeA][nodeB];
}
public List<Integer> outEdges(int i) {
List<Integer> edges = new ArrayList<Integer>();
for (int j = 0; j < size; j++) {
if (matrix[i][j]) {
edges.add(j);
}
}
return edges;
}
public List<Integer> inEdges(int i) {
List<Integer> edges = new ArrayList<Integer>();
for (int j = 0; j < size; j++) {
if (matrix[j][i]) {
edges.add(j);
}
}
return edges;
}
public int nVertices() {
return size;
}
public void breadthFirstSearch(int root) {
boolean[] seen = new boolean[nVertices()];
Queue<Integer> q = new LinkedList<Integer>();
q.add(root);
seen[root] = true;
while (!q.isEmpty()) {
int i = q.remove();
for (Integer j : outEdges(i)) {
if (!seen[j]) {
q.add(j);
seen[j] = true;
}
}
}
}
public void depthFirstSearch(int r) {
byte[] c = new byte[nVertices()];
Stack<Integer> s = new Stack<Integer>();
s.push(r);
while (!s.isEmpty()) {
int i = s.pop();
if (c[i] == WHITE) {
c[i] = GREY;
for (int j : outEdges(i))
s.push(j);
}
}
}
public static void main(String[] args) {
AdjMatrixGraph graph = new AdjMatrixGraph(10);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(6, 8);
graph.addEdge(3, 2);
System.out.println("Edge from 6 to 8 is : " + graph.hasEdge(6, 8));
System.out.println("Edge from 2 to 4 is : " + graph.hasEdge(2, 4));
System.out.println("Edge from 3 to 2 is : " + graph.hasEdge(3, 2));
System.out.println("Edge from 1 to 3 is : " + graph.hasEdge(1, 3));
graph.removeEdge(6, 8);
System.out.println("Edge from 6 to 8 is : " + graph.hasEdge(6, 8));
}
}
</pre>
<br />
<b>Output of this Program:</b><br />
<pre class="" style="background-color: white !important; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; border: 0px; color: #333333; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 13px; line-height: 20px; padding: 0px !important; tab-size: 4; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;">Edge from 6 to 8 is : true
Edge from 2 to 4 is : true
Edge from 3 to 2 is : true
Edge from 1 to 3 is : true
Edge from 6 to 8 is : false
</pre>
<div>
<br /></div>
<span style="font-size: large;">Try this by Yourself :</span> <a href="http://ideone.com/ZZm7rW">http://ideone.com/ZZm7rW</a></div>
Happy Coderhttp://www.blogger.com/profile/10351448605389567935noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-36523045231305440832014-08-11T16:37:00.001-07:002014-08-11T16:37:58.086-07:00To Sort an Interger Array using Shell Sort<div dir="ltr" style="text-align: left;" trbidi="on">
To Sort an Interger Array using Shell Sort<br />
<br />
<pre class="java" name="code">class ShellSort {
public static int[] shellSort(int[] array) {
int N = array.length;
// determine the initial h value
int h = 1;
while (h < N / 3)
h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
while (h >= 1) {
// h-sort the array
for (int i = h; i < array.length; i++) {
// do insertion sort for h-sized array
for (int j = i; j >= h && array[j] < array[j - h]; j -= h)
swap(array, j, j - h);
}
h = h / 3; // reverse the h-size
}
return array;
}
/*
* swaps data elements between 2 indexes of an array
*/
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String args[]){
ShellSort sSort = new ShellSort();
int[] array = { 77, 99, 44, 55, 22, 88, 11, 0, 66, 33 };
int[] sortedArray = sSort.shellSort(array);
for (int i = 0; i < array.length; i++)
System.out.println(sortedArray[i]);
}
}
</pre>
<br />
<b>Output of the Program : </b><br />
<pre class="" style="background-color: white !important; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; border: 0px; color: #333333; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 13px; line-height: 20px; padding: 0px !important; tab-size: 4; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;">0
11
22
33
44
55
66
77
88
99</pre>
<br />
Try it by yourself here :<a href="http://ideone.com/veRv5P" rel="nofollow" target="_blank"> http://ideone.com/veRv5P</a></div>
Happy Coderhttp://www.blogger.com/profile/10351448605389567935noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-38841022983410153512014-08-11T16:29:00.000-07:002014-08-11T16:29:49.803-07:00Sort an Integer array with Bucket Sort<div dir="ltr" style="text-align: left;" trbidi="on">
Here is a java program to Sort an Integer array with Bucket Sort<br />
<br />
<pre class="java" name="code">class BucketSort {
public int[] bucketSort(int[] array) {
// create an array the size of the largest value + 1
int[] bucket = new int[100];
// for every value in array, increment its corresponding bucket
for (int i = 0; i < array.length; i++)
bucket[array[i]]++;
int outPos = 0;
for (int i = 0; i < bucket.length; i++) {
if (bucket[i] > 0)
array[outPos++] = i;
}
return array;
}
public static void main(String args[]){
BucketSort bSort = new BucketSort();
int[] array = { 77, 99, 44, 55, 22, 88, 11, 0, 66, 33 };
int[] sortedArray = bSort.bucketSort(array);
for (int i = 0; i < array.length; i++)
System.out.println(sortedArray[i]);
}
}
</pre>
<br />
<b>Output of the Program :</b><br />
<pre class="" style="background-color: white !important; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; border: 0px; color: #333333; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 13px; line-height: 20px; padding: 0px !important; tab-size: 4; white-space: pre-wrap; word-break: break-all; word-wrap: break-word;">0
11
22
33
44
55
66</pre>
<br />
Try By Yourself Here :<a href="http://ideone.com/OpHXmH" rel="nofollow" target="_blank"> http://ideone.com/OpHXmH</a></div>
Happy Coderhttp://www.blogger.com/profile/10351448605389567935noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-10675663172989014722013-08-15T10:10:00.000-07:002013-08-15T10:10:25.951-07:00Merge-Sort Algorithm implementation in JAVA<div dir="ltr" style="text-align: left;" trbidi="on">
Merge-Sort Function<br />
<br />
<pre class="java" name="code">void MergeSort(int low, int high)
// a[low : high] is a global array to be sorted.
// Small(P) is true if there is only one element to
// sort. In this case the list is already sorted.
{
if (low < high) { // If there are more than one element
// Divide P into subproblems.
// Find where to split the set.
int mid = (low + high)/2;
// Solve the subproblems.
MergeSort(low, mid);
MergeSort(mid + 1, high);
// Combine the solutions.
Merge(low, mid, high);
}
}
void Merge(int low, int mid, int high)
// a[low:high] is a global array containing two sorted
// subsets in a[low:mid] and in a[mid+1:high]. The goal
// is to merge these two sets into a single set residing
// in a[low:high]. b[] is an auxiliary global array.
{
int h = low, i = low, j = mid+1, k;
while ((h <= mid) && (j <= high)) {
if (a[h] <= a[j]) { b[i] = a[h]; h++; }
else { b[i] = a[j]; j++; } i++;
}
if (h > mid) for (k=j; k<=high; k++) {
b[i] = a[k]; i++;
}
else for (k=h; k<=mid; k++) {
b[i] = a[k]; i++;
}
for (k=low; k<=high; k++) a[k] = b[k];
}
</pre>
<br/>
Merge Sort Java Code :
<br/>
<pre class="java" name="code">
import java.util.*;
public class MergeSort {
public int a[] = new int[50];
public void merge_sort(int low, int high) {
int mid;
if (low < high) {
mid = (low + high) / 2;
merge_sort(low, mid);
merge_sort(mid + 1, high);
merge(low, mid, high);
}
}
public void merge(int low, int mid, int high) {
int h, i, j, k;
int b[] = new int[50];
h = low;
i = low;
j = mid + 1;
while ((h <= mid) && (j <= high)) {
if (a[h] <= a[j]) {
b[i] = a[h];
h++;
} else {
b[i] = a[j];
j++;
}
i++;
}
if (h > mid) {
for (k = j; k <= high; k++) {
b[i] = a[k];
i++;
}
} else {
for (k = h; k <= mid; k++) {
b[i] = a[k];
i++;
}
}
for (k = low; k <= high; k++)
a[k] = b[k];
}
public MergeSort() {
int num, i;
System.out.println(" MERGE SORT PROGRAM ");
System.out.println();
System.out.println();
System.out
.println("Please Enter THE No. OF ELEMENTS you want to sort[THEN PRESS ENTER]:");
num = new Scanner(System.in).nextInt();
System.out.println();
System.out.println("Now, Please Enter the (" + num
+ ") nos. [THEN PRESS ENTER]:");
for (i = 1; i <= num; i++) {
a[i] = new Scanner(System.in).nextInt();
}
merge_sort(1, num);
System.out.println();
System.out.println("So, the sorted list (using MERGE SORT) will be :");
System.out.println();
System.out.println();
for (i = 1; i <= num; i++)
System.out.print(a[i] + " ");
}
public static void main(String[] args) {
new MergeSort();
}
}
</pre>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-73693020488710232082013-04-22T12:39:00.000-07:002013-04-22T12:40:20.332-07:00Implementation of a basic generic tree, with labels of type T - Data Structure<p></p>
<br/>
<pre class="java" name="code">
// This implements a basic generic tree, with labels of type T,
// pointer to the parent node, and a singly linked list of children nodes.
class Tree<T> {
private T label;
private Tree<T> parent;
private Tree<T> nextSibling; // next node on the list of parents's
// children
private Tree<T> firstChild; // first in the linked list of children
// Getters and setters
public T getLabel() { return label; }
public void setLabel(T v) { label = v; }
public Tree<T> getParent() { return parent;}
public Tree<T> getNextSibling() { return nextSibling;}
public Tree<T> getFirstChild() { return firstChild;}
// Add C to the front of the children of this
public void addChild(Tree<T> c) {
c.parent = this;
if (firstChild == null)
firstChild = c;
else {
c.nextSibling = firstChild;
firstChild = c;
}
}
// Check if the node is a leaf
public boolean Leaf() { return firstChild==null; }
// `Convert the tree into a string. The structure is indicated by
// square brackets. Uses a preorder listing.
public String toString() {
String S = "[ " + label.toString();
Tree<T> N = firstChild;
while (N != null) {
S = S + " " + N.toString();
N = N.nextSibling;
}
return S+" ]";
}
public void displayPreorder() {
displayPreorder1(0); }
public void displayPreorder1(int Indent) {
for (int I = 0; I < Indent; I++) System.out.print(" ");
System.out.println(label.toString());
Tree<T> N = firstChild;
while (N != null) {
N.displayPreorder1(Indent+3);
N = N.nextSibling;
}
}
public void displayPostorder() {
displayPostorder1(0); }
public void displayPostorder1(int Indent) {
Tree<T> N = firstChild;
while (N != null) {
N.displayPostorder1(Indent+3);
N = N.nextSibling;
}
for (int I = 0; I < Indent; I++) System.out.print(" ");
System.out.println(label.toString());
}
}
</pre>
<br/>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-66347860171112762922013-04-22T12:36:00.001-07:002013-04-22T12:36:52.566-07:00Stack implemented as array - Data Structure<p></p>
<br/>
<pre class="java" name="code">
// Stack implemented as array
public class ArrayStack<T> {
private T[] stack;
private int numElements = 0; // points to slot after top element
public ArrayStack(T[] s) { stack = s; }
public boolean emptyStack() {
return numElements == 0; }
public T top() {
return stack[numElements-1];
}
public void push(T x) {
stack[numElements] = x;
numElements++;
}
public T pop() {
numElements--;
return stack[numElements];
}
public static void main(String[] args) {
ArrayStack<Integer> s = new ArrayStack<Integer>(new Integer[100]);
s.push(2);
s.push(3);
s.push(5);
System.out.println(s.top());
System.out.println(s.pop());
System.out.println(s.pop());
s.push(15);
s.push(22);
System.out.println(s.pop());
}
}
</pre>
<br/>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-41623452322186623052013-04-22T12:34:00.000-07:002013-04-22T12:34:51.812-07:00Singly linked list with header - Data Structure<p></p>
<br/>
<pre class="java" name="code">
class OrderedList {
private int value;
private OrderedList next;
// Note: No setValue() method or setNext() methods are provided,
// since those could require reordering the list.
public int getValue() {
return value; }
public OrderedList getNext() {
return next; }
// If X is in the list, returns the previous node.
// If X is not in the list, returns the node for the greatest element less
// than X.
public OrderedList searchBefore(int x) { // Locate node containing X
OrderedList n = this;
while (true) {
if (n.next==null) return n;
if (n.next.value >= x) return n;
n = n.next;
}
}
// Is element x in the list. Note the use of the left to right evaluation of
// && (if the condition n.net != null is false, then the conjunction returns
// false without evaluating n.next.value=x.
public boolean inList(int x) {
OrderedList n = searchBefore(x);
return n.next != null && n.next.value == x; }
// Adds x to the ordered list, if it is not already there.
public void add(int x) {
OrderedList n = searchBefore(x);
if (n.next == null || n.next.value != x) {
OrderedList newNode = new OrderedList();
newNode.value = x;
newNode.next = n.next;
n.next = newNode;
}
}
// Deletes X from the ordered list, if it is there.
public void delete(int x) {
OrderedList n = searchBefore(x);
if (n.next != null && n.next.value == x)
n.next = n.next.next;
}
public String toString() {
OrderedList a = next;
String s = "[";
while (a != null) {
s = s + a.value + " ";
a = a.next;
}
return s+ "]";
}
public static void main(String[] args) {
OrderedList l = new OrderedList();
l.add(31);
l.add(41);
l.add(59);
l.add(26);
l.add(53);
l.add(58);
l.add(37);
l.delete(53);
System.out.println(l.toString());
}
}
</pre>
<br/>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-4547699125169989222013-04-22T12:32:00.001-07:002013-04-22T12:32:40.879-07:00Ordered array of ints with no repetition - Data Structure<p></p>
<br/>
<pre class="java" name="code">
public class OrderedArray {
private int numElements = 0;
private int[] elements;
// Constructor..Note: the caller has to provide the array of elements.
// This is because Java generics do not allow a call "elements = new T[100]".
//
public OrderedArray(int[] elts) {
elements = elts; }
public int getNumElements() { return numElements; }
public int nth(int n) { // return the Nth element
if (n < numElements) return elements[n]; else return -1; }
public int first() { return nth(0); }
public int last() { return nth(numElements-1); }
// search(X) returns the index where X is, if X is in the list.
// Otherwise, it returns the index of the smallest number greater than X
public int search(int x) {
if (numElements==0) return 0;
if (x <= first()) return 0;
if (x > last()) return numElements;
if (x == last()) return numElements-1;
return search1(x,0,numElements-1);
}
// X is strictly between L and U.
public int search1(int x,int l,int u) {
if (u==l+1) return u;
else {
int m = (l+u)/2;
if (x==elements[m]) return m;
else if (x < elements[m]) return search1(x,l,m);
else return search1(x,m,u);
}
}
public boolean inList(int x) {
return (elements[search(x)]==x); }
public void add(int x) {
int i = search(x);
if (elements[i] != x) {
for (int j = numElements; j>i; j--)
elements[j]=elements[j-1];
elements[i]=x;
numElements++;
}
}
public void delete(int x) {
int i = search(x);
if (elements[i] == x) {
for (int j=i+1; j < numElements; j++)
elements[j-1] = elements[j];
numElements--;
}
}
public String toString() {
String s = "[";
for (int i=0; i < numElements; i++)
s = s + " " + elements[i];
return s+"]";
}
public static void main(String[] args) {
OrderedArray l = new OrderedArray(new int[100]);
l.add(31);
l.add(41);
l.add(59);
l.add(26);
l.add(53);
l.add(58);
l.add(37);
l.delete(53);
System.out.println(l.toString());
System.out.println(l.search(2));
System.out.println(l.search(26));
System.out.println(l.search(53));
System.out.println(l.search(54));
System.out.println(l.search(195));
}
}
</pre>
<br/>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-73506404427895084152013-04-19T15:46:00.001-07:002013-04-19T15:46:59.701-07:00Stop Watch Program - To measure the amount of time to process each input<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<pre class="java" name="code">
public class Stopwatch {
private final long start;
public Stopwatch() {
start = System.currentTimeMillis();
}
// return time (in seconds) since this object was created
public double elapsedTime() {
long now = System.currentTimeMillis();
return (now - start) / 1000.0;
}
}
</pre>
<br /></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-89168064682439517582012-11-03T00:00:00.000-07:002012-11-03T00:00:09.982-07:00Parse XML file using DOM<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
This code snippet
explains about the parsing of the xml file using the DOM parser.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<pre class="java" name="code">
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLParser {
/**
* @param args
* @throws IOException
* @throws SAXException
*/
public void GetXMLValue(String FileName){
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(FileName);
if(file.exists()){
Document doc = null;
try {
doc = db.parse(file);
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element docelement1 = doc.getDocumentElement();
System.out.println("Root element of the document: "
+ docelement1.getNodeName());
//for commercial credit
NodeList valueList1 = docelement1.getElementsByTagName("CommercialCredit");
if (valueList1 != null && valueList1.getLength() > 0) {
for (int i = 0; i < valueList1.getLength(); i++) {
Node node = valueList1.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("DistSourceId");
System.out.println("DistSourceId: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("MMSReferenceStartTime");
System.out.println("MMSReferenceStartTime: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("MMSReferenceEndTime");
System.out.println("MMSReferenceEndTime: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
}
// for Credit result ---- added only 3 fields to test.....
NodeList valueList2 = docelement1.getElementsByTagName("CreditResult");
if (valueList2 != null && valueList2.getLength() > 0) {
for (int j = 0; j < valueList2.getLength(); j++) {
Element e2 = (Element) node;
NodeList nodeList2 = e2.getElementsByTagName("MediaAssetId");
System.out.println("MediaAssetId: "
+ nodeList2.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList2 = e2.getElementsByTagName("DetectedTime");
System.out.println("DetectedTime: "
+ nodeList2.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList2 = e2.getElementsByTagName("DetectedSourceId");
System.out.println("DetectedSourceId: "
+ nodeList2.item(0).getChildNodes().item(0)
.getNodeValue());
}
}//if ends here
}
}
else{
System.exit(1);
}
}
}
catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String[] args) throws SAXException, IOException {
// TODO Auto-generated method stub
String str = "C:\Test\Mytestfile.xml";
new XMLParser().GetXMLValue(str);
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-36096896686859574492012-11-02T21:30:00.000-07:002012-11-02T21:30:02.380-07:00Listing Files and Directory Using Java <div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
Lists Files and
directory present in the system </div>
<br />
<pre class="java" name="code">
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null)
{
// Either dir does not exist or is not a directory
}
else
{
for (int i=0; i < children.length; i++)
{
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter()
{
public boolean accept(File file)
{
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-69506335427591081932012-11-02T11:30:00.000-07:002012-11-02T11:30:03.222-07:00To Capture screen shots using Java<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<pre class="java" name="code">
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public void captureScreen(String fileName) throws Exception
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-89768934022279182752012-11-02T03:48:00.000-07:002012-11-02T03:48:00.129-07:00Extract a zip file in Java <div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
The sole purpose
of this program is how to extarct the content of a zip file in java.We
start by opening an input stream to the compressed file and an output
stream to the file where we want the content to be extracted.
</div>
<div style="margin-bottom: 0in;">
After that we get
the next entry of the zip file (and the only entry in this case) -
test so it's not null, and then start reading the contents from the
input stream and writing each chunk read to the output stream.
</div>
<div style="margin-bottom: 0in;">
As usual we should
clean up properly afterwards so we close the input and output
streams.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<pre class="java" name="code">
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ExtractingZipFile{
/**
* Extracts a zip file
*/
public void extractZipFile() {
try {
String zipFileName = "file.zip";
String extractedFileName = "extractedfile.txt";
//Create input and output streams
ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
OutputStream outStream = new FileOutputStream(extractedFileName);
ZipEntry entry;
byte[] buffer = new byte[1024];
int nrBytesRead;
//Get next zip entry and start reading data
if ((entry = inStream.getNextEntry()) != null) {
while ((nrBytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, nrBytesRead);
}
}
//Finish off by closing the streams
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new ExtractingZipFile().extractZipFile();
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-5984765467801520102012-11-02T00:00:00.000-07:002012-11-02T00:00:11.184-07:00Albers Square using JAVA<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
Albers Square
using JAVA</div>
<br />
<pre class="java" name="code">
public class AlbersSquares {
public static void main(String[] args) {
StdDraw.setCanvasSize(800, 800);
// first color
int r1 = Integer.parseInt(args[0]);
int g1 = Integer.parseInt(args[1]);
int b1 = Integer.parseInt(args[2]);
Color c1 = new Color(r1, g1, b1);
// second color
int r2 = Integer.parseInt(args[3]);
int g2 = Integer.parseInt(args[4]);
int b2 = Integer.parseInt(args[5]);
Color c2 = new Color(r2, g2, b2);
// first Albers square
StdDraw.setPenColor(c1);
StdDraw.filledSquare(.25, .5, .2);
StdDraw.setPenColor(c2);
StdDraw.filledSquare(.25, .5, .1);
// second Albers square
StdDraw.setPenColor(c2);
StdDraw.filledSquare(.75, .5, .2);
StdDraw.setPenColor(c1);
StdDraw.filledSquare(.75, .5, .1);
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-75693081611609454462012-11-01T15:30:00.000-07:002012-11-01T15:30:00.819-07:00Doubling Stack of Strings using Java<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
Doubling Stack of
Strings using Java </div>
<br />
<pre class="java" name="code">
import java.util.Iterator;
import java.util.NoSuchElementException;
public class DoublingStackOfStrings implements Iterable<String> {
private String[] a;
private int N;
public DoublingStackOfStrings() {
a = new String[2];
N = 0;
}
// is the stack empty?
public boolean isEmpty() { return (N == 0); }
// resize the underlying array holding the elements
private void resize(int capacity) {
String[] temp = new String[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
// push a new item onto the stack
public void push(String item) {
if (N == a.length) resize(2*a.length);
a[N++] = item;
}
// delete and return the item most recently added
public String pop() {
if (isEmpty()) { throw new RuntimeException("Stack underflow error"); }
String item = a[--N];
a[N] = null; // to avoid loitering
if (N > 0 && N == a.length/4) resize(a.length/2);
return item;
}
public Iterator<String> iterator() { return new ReverseArrayIterator(); }
// an iterator, doesn't implement remove() since it's optional
private class ReverseArrayIterator implements Iterator<String> {
private int i = N;
public boolean hasNext() { return i > 0; }
public void remove() { throw new UnsupportedOperationException(); }
public String next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
// test client
public static void main(String[] args) {
DoublingStackOfStrings s = new DoublingStackOfStrings();
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
if (!item.equals("-")) s.push(item);
else if (s.isEmpty()) StdOut.println("BAD INPUT");
else StdOut.print(s.pop());
}
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-8269072273082431922012-11-01T10:30:00.000-07:002012-11-01T10:30:00.988-07:00Excel Comparator xls or xlsx in java <div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
we can compare any
two excels of extension either xls or xlsx </div>
<br />
<pre class="java" name="code">
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excelcomparison {
ArrayList<String> listOfTerms =null;
ArrayList<String> al =new ArrayList<String>();
ArrayList<String> finallist = new ArrayList<String>();
public Workbook checkFileFormat(String fileName){
Workbook hwb=null;
FileInputStream checkFis=null;
try{
checkFis=new FileInputStream(fileName);
//Instantiate the Workbook using HSSFWorkbook
hwb=(Workbook)new HSSFWorkbook(checkFis);
Sheet sheet=hwb.getSheetAt(0);
Iterator<Row> rows=sheet.rowIterator();
Iterator<Cell> cells=null;
Row row=null;
Cell cell=null;
int check=0;
//Read the file as HSSFWorkbook
while(rows.hasNext()){
check++;
row=(HSSFRow)rows.next();
cells=row.cellIterator();
while(cells.hasNext()){
cell=(HSSFCell)cells.next();
}
if(check==2)
break;
}
//Return HSSFWorkbook type object if there is no exception in reading the file using HSSFWorkbook
return hwb;
}catch(ClassCastException ce){ //Instantiate the Workbook using XSSFWorkbook in case of class cast exception
Workbook xwb=null;
try{
xwb=new XSSFWorkbook(checkFis);
checkFis.close();
}catch(IOException e){
e.printStackTrace();
}
return xwb; }
catch(Exception e){ //Instantiate the Workbook using XSSFWorkbook in case of Exception while reading file through HSSFWorkbook
Workbook xwb=null;
try{
if(checkFis!=null)
checkFis.close();
checkFis=null;
checkFis=new FileInputStream(fileName);
xwb=new XSSFWorkbook(checkFis);
checkFis.close();
}catch(Exception ie){
return null;
}
return xwb;
}
}
public void readExcel()
{
try
{
Workbook workbook = checkFileFormat("EXCEL1.xlsx");
listOfTerms =new ArrayList<String>();
Sheet sheet = workbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
System.out.println("here "+rows+" "+sheet.getSheetName());
for (int r = 0; r < rows; r++)
{
Row row = sheet.getRow(r);
Cell cell =row.getCell((short)0);
String cellValue = cell.getStringCellValue().trim();
listOfTerms.add(cellValue);
}
System.out.println(listOfTerms);
Workbook workbook1 = checkFileFormat("EXCEL2.xls");
Sheet sheet1 = workbook1.getSheetAt(0);
int rows1 = sheet1.getPhysicalNumberOfRows();
System.out.println("here "+rows1+" "+sheet.getSheetName());
for (int k = 0; k < rows1; k++)
{
Row row1 = sheet.getRow(k);
Cell cell =row1.getCell((short)0);
String cellValue2 = cell.getStringCellValue();
al.add(cellValue2);
}
System.out.println(al);
for(int i=0; i<al.size(); i++)
{
if(!listOfTerms.contains(al.get(i)))
{
finallist.add(al.get(i));
}
}
for(int i=0; i<listOfTerms.size(); i++)
{
if(!al.contains(listOfTerms.get(i)))
{
finallist.add(listOfTerms.get(i));
}
}
System.out.println("Elements which are different: " +finallist);
System.out.println("");
createSheet();
}catch(Exception e)
{
e.getStackTrace();
System.out.println(e.getMessage());
}
}
private void createSheet() {
XSSFWorkbook bookout = new XSSFWorkbook();
try
{
int j=0;
XSSFSheet sheet1= bookout.createSheet();
bookout.setSheetName(0,"Document Handles");
for(int m=0;m<finallist.size();m++)
{
XSSFRow row=sheet1.createRow(j++);
row.createCell((short) 0).setCellValue(finallist.get(m));
}
FileOutputStream fout = new FileOutputStream("OutputExcel.xlsx");
bookout.write(fout);
fout.close();
System.out.println("file completed");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public static void main(String args[]){
Excelcomparison e = new Excelcomparison();
e.readExcel();
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-85550067578343667482012-11-01T03:35:00.000-07:002012-11-01T03:35:00.099-07:00Code to Remove Certain Characters from a Java Input <div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
Sometimes we can't
rename a file automatically when the Filename has "/"
inside them because of Windows limitations. This code might prove
handy in these situations.
</div>
<div style="margin-bottom: 0in;">
</div>
<br />
<pre class="java" name="code">
//Code to Remove Certain Characters from a Java Input//
try {
String Y = X;
String regx = "/";
char[] ca = regx.toCharArray();
for (char c : ca) {
Y = Y.replace("" + c, "");
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-61828094665642318812012-11-01T00:00:00.000-07:002012-11-01T00:00:05.427-07:00Code to Populate Dropdown from a DB<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
Using this Java
snippet the users can Populate Dropdown from a DB </div>
<br />
<pre class="java" name="code">
//Code to Populate Dropdown from a DB//
//In JSP//
<div id="bodydiv" align="center" >
<select name=" Name" onchange="this.form.submit();">
<option name="Router Name" value="0">--------select--------</option>
<%
GetXRouter dao = new GetXRouter();
ArrayList ReList = dao.retreiveRname();
for (int i = 0; i < ReList.size(); i++) {
%>
<option name="RName" value="<%=ReList.get(i)%>"><%=ReList.get(i)%></option>
<%
}
%>
</select>
//IN Java Class File//
public class GetList {
static Connection conn = null;
static Statement st = null;
static ResultSet rs = null;
static DBConnection db;
@SuppressWarnings({ "rawtypes", "unchecked" })
public ArrayList retreiveIname(String Rname) throws SQLException {
Connection conn;
DBConnection db = new DBConnection();
conn = db.getConnection();
Statement st;
st = conn.createStatement();
ResultSet rs = st.executeQuery("select tt.Y_nm from Z.Z_X_Y_cfg tt where tt.active = 'A' and tt.X_nm = '"+Rname+"' ");
ArrayList IList = new ArrayList();
while (rs.next()) {
IList.add(rs.getString(1));
}
for (int i = 0; i < IList.size(); i++) {
System.out.println(IList.get(i));
}
return IList;
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-81224838773214684582012-10-31T18:00:00.000-07:002012-10-31T18:00:02.354-07:00To Convert the Given String to Propercase <div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
If string is not
in proper case i.e. if a particular name's all letters are in upper
case or lower case, so this code will convert it to proper case.
</div>
<div style="margin-bottom: 0in;">
</div>
<br />
<pre class="java" name="code">
public class ConvertToProperCase {
public static String convertToProper(String strToConvert) throws java.io.IOException{
//get lower case string
java.io.StringReader str = new java.io.StringReader(strToConvert.toLowerCase());
boolean precededBySpace = true;
StringBuffer properCase = new StringBuffer();
while(true) {
//read string character by character
int i = str.read();
if (i == -1) break;
char c = (char)i;
if (c == ' ' || c == '"' || c == '(' || c == '.' || c == '/' || c == '\' || c == ',') {
properCase.append(c);
precededBySpace = true;
} else {
if (precededBySpace) {
//convert first character to proper
properCase.append(Character.toUpperCase(c));
} else {
// append rest character
properCase.append(c);
}
precededBySpace = false;
}
}
return properCase.toString();
}
//main code
public static void main(String[] args) {
try {
//call convertToProper method
System.out.println(convertToProper("1jf94osl TEST TEST test test., MIKE, BRADD, blair"));
} catch (java.io.IOException e) {
System.out.println("Exception:" + e);
}
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-6136257487678082722012-10-31T13:30:00.000-07:002012-10-31T13:30:00.544-07:00Excel report generator based on the Input provided through an xml file<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
This tool can
generate one or more xls report based on the input provided inside a
xml file.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<pre class="java" name="code">
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* This java class will read the xml file and generate the excel sheet based on the input parameter
* provided to it.
*
*
*/
public class ReadXmlFile {
public static void main(String argv[]) {
Connection con = null;
try {
String __runId = argv[0];
String __runIdArr[] = __runId.split(",");
if (__runIdArr.length > 0) {
for (int i = 0; i < __runIdArr.length; i++) {
String __filePath = "C:\excel\test1.xml";
File fXmlFile = new File(__filePath);
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("data");
System.out.println("-----------------------");
File f = new File("C:\excel\data_import_"+__runIdArr[i]+".xls");
if (f.createNewFile()) {
System.out
.println("File has been created successfully");
}
FileOutputStream fileOut = new FileOutputStream(f);
HSSFWorkbook hwb = new HSSFWorkbook();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String __sheetName = getTagValue("sheetname",
eElement);
String __columns = getTagValue("column", eElement);
String __query = getTagValue("query", eElement);
// String __runId = getTagValue("runid", eElement);
con = DBConnection.getConnection();
if (createSheet(hwb, __sheetName, con, __query,
__columns, __runIdArr[i])) {
System.out
.println(__sheetName
+ " sheet has been created successfully.");
}
}
}
hwb.write(fileOut);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("File has been generated successfully.");
System.exit(1);
}
/**
* @depricated.
* @param sTag String Object.
* @param eElement Element object
* @return returns string object.
*/
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();
}
/**
* This method will create the excel sheet based on queries has been written inside the xml file.
* @param hwb Inatance of HSSFWorkbook
* @param sheetName Instance of
* @param con String
* @return returns boolean values.
* @throws Exception
*/
private static boolean createSheet(HSSFWorkbook hwb, String sheetName,
Connection con, String query, String columns, String runId)
throws Exception {
boolean __sheetstatus = false;
HSSFSheet sheet = hwb.createSheet(sheetName);
HSSFRow rowhead = sheet.createRow((int) 1);
int count = 0;
HSSFFont font = hwb.createFont();
font.setFontHeightInPoints((short) 10);
font.setFontName(HSSFFont.FONT_ARIAL);
HSSFCellStyle headerCell = setHeaderCell(hwb, font);
String columnsArr[] = columns.split(";");
for (int i = 0; i < columnsArr.length; i++) {
setHeadColumnValue(sheet, rowhead, headerCell, columnsArr[i],
count, 75);
count++;
}
PreparedStatement psEventCount = null;
ResultSet rsEventType = null;
try {
psEventCount = con.prepareStatement(query.replaceAll("#", runId));
rsEventType = psEventCount.executeQuery();
int rowCount = 2;
HSSFCellStyle setStringCell = setStringCell(hwb);
while (rsEventType.next()) {
int __count = 0;
HSSFRow currentRowhead = sheet.createRow((short) rowCount);
for (int i = 0; i < columnsArr.length; i++) {
String __equipmentselNumber = rsEventType
.getString(columnsArr[i]);
setHeadColumnValue(sheet, currentRowhead, setStringCell,
__equipmentselNumber, __count, 75);
__count++;
}
rowCount++;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
rsEventType.close();
psEventCount.close();
}
__sheetstatus = true;
return __sheetstatus;
}
/**
* @This method will organize the xls cell values and style of that.
* @param wb Instance of HSSFWorkbook
* @param font Inatance of HSSFFont
* @return Instance of String.
*/
private static HSSFCellStyle setHeaderCell(HSSFWorkbook wb, HSSFFont font) {
HSSFCellStyle headerCell = wb.createCellStyle();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// headerCell.setAlignment(HSSFCellStyle.ALIGN_LEFT);
headerCell.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
headerCell.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headerCell.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);
headerCell.setFont(font);
headerCell.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerCell.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headerCell.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerCell.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerCell.setWrapText(true);
return headerCell;
}
/**
* @This method will organize the xls cell values and style of that.
* @param wb Instance of HSSFWorkbook
* @return returns String instance.
*/
private static HSSFCellStyle setStringCell(HSSFWorkbook wb) {
HSSFCellStyle stringCell = wb.createCellStyle();
stringCell.setAlignment(HSSFCellStyle.ALIGN_LEFT);// "#,##0"
stringCell.setBorderBottom(HSSFCellStyle.BORDER_THIN);
stringCell.setBorderLeft(HSSFCellStyle.BORDER_THIN);
stringCell.setBorderTop(HSSFCellStyle.BORDER_THIN);
stringCell.setBorderRight(HSSFCellStyle.BORDER_THIN);
stringCell.setLocked(false);
stringCell.setWrapText(true);
return stringCell;
}
/**
* This method will set the head columns values.
* @param sheet Instance of HSSFSheet
* @param row Instance of HSSFRow
* @param style Instance of HSSFCellStyle
* @param value Instance of String
* @param colNo Instance of int.
* @param width Instance of of int.
*/
public static void setHeadColumnValue(HSSFSheet sheet, HSSFRow row,
HSSFCellStyle style, String value, int colNo, int width) {
HSSFCell cellt = row.createCell((short) colNo);
sheet.addMergedRegion(new Region(0, (short) colNo, 0,
(short) (colNo + 2)));
cellt.setCellStyle(style);
cellt.setCellValue(value);
sheet.setColumnWidth((short) colNo, (short) (100 * width));
}
}
import java.sql.*;
public class DBConnection {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
//QA
//String url = "jdbc:oracle:thin:@etpcamq1.energy.ge.com:1521:etpcamq1";
//con = DriverManager.getConnection(url,"TBCAM","cam34etpq1");
String url =""
con = DriverManager.getConnection(url,"","");
}catch(Exception e){
e.printStackTrace();
}
return con;
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-63791270288040098712012-10-31T10:30:00.000-07:002012-10-31T10:30:00.848-07:00Recursivey listing files and folders in java<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
This code snippet
lists all the files and folders including the files in subdirectories
present in the given path at any level recursively and displays in a
tree structure
</div>
<div style="margin-bottom: 0in;">
</div>
<br />
<pre class="java" name="code">
import java.io.File;
public class FileStructure {
int tabCounter = 0;
// obtain the list of files and folders in particular location
public void listFilesAndFolders(String folder) {
File file = new File(folder);
if (!file.exists() || !file.isDirectory()) {
System.out.println("Parameter is not a directory");
System.exit(1);
}
File[] fileArray = file.listFiles();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
System.out.println(getTabs() + "- " + fileArray[i].getName());
tabCounter++;
listFilesAndFolders(fileArray[i].getAbsolutePath());
}
else {
System.out.println(getTabs() + fileArray[i].getName());
}
}
tabCounter--;
}
// provide a tab space to represent tree structure
private String getTabs() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < tabCounter; i++)
buffer.append("\t");
return buffer.toString();
}
public static void main(String[] args) {
FileStructure fileStructure = new FileStructure();
fileStructure.listFilesAndFolders("C:\\temp");
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-1646370283625407322012-10-31T03:09:00.000-07:002012-10-31T03:09:00.337-07:00calculate the free disk space<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
To calculate
available disk space using Java </div>
<br />
<pre class="java" name="code">
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
public class DiskSpace {
public static void main(String[] args) {
try {
//calculate free disk space
double freeDiskSpace = FileSystemUtils.freeSpaceKb("C:");
//convert the number into gigabyte
double freeDiskSpaceGB = freeDiskSpace / 1024 / 1024;
System.out.println("Free Disk Space (GB):" + freeDiskSpaceGB);
} catch (IOException e) {
e.printStackTrace();
}
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-70447027253172188162012-10-30T15:30:00.000-07:002012-10-30T15:30:01.774-07:00Dictionary Program to obtain meaning of words using java<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<div style="margin-bottom: 0in;">
It is a program to
obtain meaning of words which are redirected to google as parameters.
The results are fetched and printed using json object in java. </div>
<br />
<pre class="java" name="code">
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import javax.swing.JOptionPane;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Dictonary
{
public static void main(String args[]) throws Exception
{
String str = null;
System.out.println("running");;
str = JOptionPane.showInputDialog("Enter the string");
System.setProperty("http.proxyHost", "192.168.0.17");
System.setProperty("http.proxyPort", "8080");
JSONObject json = readJsonFromUrl("http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q="+str+"&sl=en&tl=en&restrict=pr%2Cde&client=te");
JSONArray json1 = json.getJSONArray("webDefinitions");
JSONArray json2 = ((JSONObject)json1.get(0)).getJSONArray("entries");
System.out.println("MEANINGS OF "+str);
for(int i=0;i<json2.length();i++)
{
JSONArray jobarray =((JSONObject)json2.get(i)).getJSONArray("terms");
for(int j=0;j<jobarray.length();j++)
{
JSONObject job = jobarray.getJSONObject(j);
String stri = (String)job.get("type");
if(stri.equals("text"))
{
System.out.println(job.get("text"));
}
}
System.out.println("");
}
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
// System.out.println("char 1 "+jsonText.trim());
jsonText= jsonText.substring(jsonText.indexOf('(')+1,jsonText.lastIndexOf(')'));
// System.out.println("char 2 "+jsonText.trim());
JSONObject json = new JSONObject(jsonText.trim());
return json;
} finally {
is.close();
}
}
private static String readAll(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0tag:blogger.com,1999:blog-5553707859049859464.post-71646648327128947192012-10-30T14:30:00.000-07:002012-10-30T14:30:02.034-07:00Efficient retrieval of Keys using given Values in the Map<div dir="ltr" style="text-align: left;" trbidi="on">
This asset provides a reusable code which can be used to retrieve the Keys when Values are given in Java maps. <br />
<br />
<pre class="java" name="code">
BidiMap bidimap = new DualHashBidiMap();
bidimap.putAll(theMap);
String myKey= bidimap.inverseBidiMap().get("Mumbai").toString();
System.out.println("The Key is :" + myKey) ;
</pre>
<br /></div>
Raju Guptahttp://www.blogger.com/profile/13350804494797609989noreply@blogger.com0