Powered By Blogger

Friday, September 20, 2013

Sort A linked List with N numbers. Range of Numbers in ( 0, 1, 2 )

Sort a Linked List with N numbers. Range of Numbers in this Linked List in ( 0, 1, 2 )

For exmaple:
A Linked List with numbers : { 0, 0, 1, 2, 2, 1, 1, 0, 0, 1, 2 } OR { 2,0, 0, 1, 2, 2, 1, 1, 0, 0, 1, 2 }, etc

Below is the Program to sort this:

public class SortALinkedList {

    public Link sort(Link head) {
     
        if (head == null)
            return head;
        if (head.next == null)
            return head;

        Link k = head;
        Link _0 = null;
        Link _1 = null;

        if (head.value() == 0)
            _0 = k;
        else if (head.value() == 1)
            _1 = k;

        Link iter = head.next;
        Link iter_before = head;

        while (iter != null) {

            if (iter.value() == 2) {
                iter_before = iter;
                iter = iter.next;
                continue;
            }

            Link p = iter;
            iter = iter.next;
            iter_before.next = iter;

            if (p.value() == 1) {

                if (_1 == null) {
                    _1 = p;

                    if (_0 != null) {
                        p.next = _0.next;
                        _0.next = p;
                    } else {
                        p.next = head;
                    }
                } else {
                    p.next = _1.next;
                    _1.next = p;
                }

            } else if (p.value() == 0) {

                if (_0 == null) {
                    _0 = p;
                    p.next = (_1 == null ? head : _1);
                } else {
                    p.next = k;
                }
                k = p;
            }

        }

        return k;
    }

    public static void main(String[] args) {

        int[] arr0 = new int[] { 0, 0, 1, 2, 2, 1, 1, 0, 0, 1, 2 };
       
        int[] arr1 = new int[] {  1,0, 2, 2, 1, 1, 0, 0, 1, 2 };
       
        int[] arr2 = new int[] { 2,1, 0, 1, 2, 2, 1, 1, 0, 0, 1, 2 };
       
        int[] arr3 = new int[] { 2,0, 0, 1, 2, 2, 1, 1, 0, 0, 1, 2 };
       
        int[] arr4 = new int[] { 2,2,0, 0, 1, 2, 2, 1, 1, 0, 0, 1, 2 };
       
        int[] arr5 = new int[] {  1, 1, 0, 2, 2, 1, 1, 0, 0, 1, 2 };
       
        Link head = Link.build(arr0);

        SortALinkedList srt = new SortALinkedList();
        Link k = srt.sort(head);

        k.print(k);
   
    }

}

Tuesday, September 10, 2013

Eclipse Remote Debugging:

Failed to connect to remote VM. Connection timed out

 

The above error is the most frequently encountered by Developers working with different eclipse version.
It is almost too irritating all to get this error and spend a substantial portion of the day debugging it.

Some things to try to get past this error:

1. First check the network connection settings ( Assuming you can ping to the remote machine successfully )

Go to Window -> Preferences -> General -> Network Connections, and check if there is any proxy set here, change the 'Active Provider' to be 'Direct' and try again

For more see the below link:
http://stackoverflow.com/questions/9034147/getting-launch-error-failed-to-connect-to-remote-vm-connection-timed-out-whic

2. Increase the Debug timeout paramters:
http://stackoverflow.com/questions/5990438/eclipse-remote-debug-timeout-problem

3. Check the remote server Debug settings:
My Java debug options configured on the remote server:

set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8788,server=y,suspend=n"

where 8788 is the port to connect to for remote debugging.

This port, 8788 must be provided in the ecliipse settings

See this link for how to add the remote server name and remote server debug port:
http://java.dzone.com/articles/how-debug-remote-java-applicat

4. For more general information, see link:
http://javarevisited.blogspot.in/2011/02/how-to-setup-remote-debugging-in.html

 

Friday, September 6, 2013

QuickSort on an Array

Implement a QuickSort on an Array


public class QuickSort {
   
    int partition( int[] in ) {
        if ( in.length == 1) return 0;
   
        if ( in.length == 2 ) {
            if ( in[0] > in[1]) {
                swap(in , 0 ,1);
                return 1;
            }else if( in[0] == in[1])
                return 1;
            else return 0;
               
        }
       
        int pivot = in[0];
        int down = 1;
        int up = in.length - 1;
        int ele = -1;
       
        while ( up > down ) {
            // move down pointer
            while( in[down] <= pivot && down < in.length -1)
                ++down;
                   
            while( in[up] > pivot && up > 0)
                --up;
               
            if ( up > down) {
                swap(in, down, up);
                ele = down;
               
                ++down;
                --up;
            }
        }

        if ( in[up] > pivot) {
            swap(in, 0, ele);
        }else{
            swap(in, 0, up);
            ele = up;
        }

        return ele;
    }
   
    private void swap( int[] in, int lb, int ub ) {
        int tmp = in[lb];
        in[lb] = in[ub];
        in[ub] = tmp;
    }
   
    void print(int[] in) {
        for( int i: in )
            System.out.println(i);
    }
   
    public static void main( String[] args ) {
       
        int[] in = new int[] {57,25, 36, 69, 22, 99, 48, 98, 88, 79, 62 };
       
        int[] in1 = new int[] {25, 22, 21, 23, 24 };
       
        int[] in2 = new int[] { 21, 24, 26, 28, 49 };
       
        int[] in3 = new int[] { 25, 57, 48, 37, 12, 92, 86, 33};
       
        int[] in4 = new int[]{2,1,3,-2,0};
       
        int[] in5 = new int[]{2,1,0,6,-7};
       
        int[] in6 = new int[]{25,35,49,50,21,22,25};
       
        int[] in7 = new int[]  {2,1,2};
       
        int[] in8 = new int[]  {2,2};
       
        QuickSort sort = new QuickSort();
   
        System.out.println("--------------------");
       
        System.out.println(sort.partition(in));
        sort.print(in);
       
        System.out.println("-------------------------------");
        System.out.println(sort.partition(in1));
        sort.print(in1);
   
        System.out.println("-------------------------");
        System.out.println(sort.partition(in2));
        sort.print(in2);
       
        System.out.println("-------------------------------");
        System.out.println(sort.partition(in3));
        sort.print(in3);
       
        System.out.println("-------------------------------");
        System.out.println(sort.partition(in4));
        sort.print(in4);
       
        System.out.println("----------------------");
        System.out.println(sort.partition(in5));
        sort.print(in5);
       
        System.out.println("-------------------------");
        System.out.println(sort.partition(in6));
        sort.print(in6);
       
        System.out.println("---------------------------");
        System.out.println(sort.partition(in7));
        sort.print(in7);
       
        System.out.println("---------------------------");
        System.out.println(sort.partition(in8));
        sort.print(in8);
       
       
    }

}


Thursday, September 5, 2013

implement a Queue from Two Stacks

Implement a Queue from Two Stacks


Below is a java program to Implement a Queue from two Stacks

public class QueueFromStack {
   
    Stack pushStack = new Stack();
    Stack otherStack = new Stack();
    int front = -1;
    int rear = -1;
   
    void queue(int val ) {
        pushStack.push(val);
    }
   
    boolean isEmpty() {
        return pushStack.isEmpty();
    }
   
    int dequeue() {
        int dequeuedVal = 0;
        boolean found = false;
        while( !pushStack.isEmpty()) {
            int val = pushStack.pop();
            otherStack.push(val);
        }
        if ( !otherStack.isEmpty() ) {
            found = true;
            dequeuedVal = otherStack.pop();
        }
        while ( !otherStack.isEmpty() ) {
            int val = otherStack.pop();
            pushStack.push( val );
        }
        if ( !found )
            throw new RuntimeException("Empty Queue");
       
        return dequeuedVal;           
    }
   
    void print() {
        int bottom = pushStack.getBottom();
        int top = pushStack.top();
        while( bottom <= top )
        System.out.println( pushStack.get(bottom++) );
    }
   
    public static void main( String[] args ) {
        QueueFromStack qfs  = new QueueFromStack();
        qfs.queue(2);
        qfs.queue(3);
        qfs.queue(5);
       
        qfs.print();
       
        System.out.println("-------------------------");
        qfs.dequeue();
        qfs.dequeue();
               
        System.out.println("-------------------------");
        qfs.print();
    }

}

------------------------------------ Stack class --------------------------------------------------------
public class Stack {

    public int max_size = 20;
    private int[] stack = new int[max_size];
   
    int top = -1;
   
    void push( int val ) {
        if ( top == max_size )
            throw new RuntimeException("Stack_Overflow");
        stack[++top] = val;
    }
   
    int top() {
        return top;
    }
   
    int pop() {
        if ( top == -1)
            throw new RuntimeException( "stack_underflow" );
        return stack[top--];
    }
   
    boolean isEmpty() {
        return top == -1;
    }
   
    int peek() {
        return stack[top];
    }
   
    void clear() {
        top = -1;
    }
   
    int getBottom() {
        return 0;
    }
   
    int get( int i ) {
        return stack[i];
       
        }
}

Implement a Stack from Two Queues

Implement a Stack from Two Queues

Below is a java program to Implement a Stack from Two Queues

public class StackFromQueue {
   
    Queue pushQ = new Queue();
    Queue popQ = new Queue();
   
    void push( int val ) {
        pushQ.enqueue(val);
    }
   
    int pop() {
       
        if ( pushQ.isEmpty() )
            throw new RuntimeException("empty_queue");
       
        int front = pushQ.front();
        int rear = pushQ.rear();
       
        while ( front++ < rear ) {
            int val = pushQ.dequeue();
            popQ.enqueue(val);
        }
       
        int ret = pushQ.dequeue();
       
        Queue a = pushQ;
        pushQ = popQ;
        popQ = a;
       
        return ret;
    }
   
    void print() {
        if ( !pushQ.isEmpty() ) {
            int front = pushQ.front();
            int rear = pushQ.rear();
           
            while ( front <= rear ) {
                System.out.println( pushQ.get(front++));
            }
        }
    }
    public static void main( String[] args ) {
        StackFromQueue sfq = new StackFromQueue();
        sfq.push( 2 );
        sfq.push( 3);
        sfq.push(4);
       
        sfq.print();
       
        System.out.println("--------------------------");
       
        System.out.println(sfq.pop() );
        System.out.println(sfq.pop() );
       
        System.out.println("---------------------------");
       
        sfq.print();
       
    }

}
-------------------------------------- Queue class ------------------------------
public class Queue {
   
    final int max_size = 20;
    int[] queue = new int[ max_size];
   
    int front;
    int rear;
   
    public Queue() {
        init();
    }
   
    private void init() {
        front = 0;
        rear = -1;
    }
   
    void enqueue( int val ) {
        if ( rear == max_size - 1)
            throw new RuntimeException("overflow");
        queue[++rear] = val;
    }
   
    int dequeue() {
        if ( isEmpty() )
            throw new RuntimeException("underflow");
        int retVal =  queue[front++];
        if ( front > rear ) {
            init();
        }
        return retVal;
    }
   
    int front() {
     return front;
    }
   
    int rear() {
        return rear;
    }
   
    int get( int i ) {
        if ( i >= front && i <= rear ) {
            return queue[i];
        }
        throw new RuntimeException( "index_out_of_bounds" );
    }
   
    boolean isEmpty() {
        return rear == -1 && front == 0;
    }
   
    void print() {
        if ( !isEmpty() ) {
            int front = front();
            int rear = rear();
           
            while ( front <= rear ) {
                System.out.println( get(front++));
            }
        }
    }
   
    public static void main( String[] args ) {
        Queue q = new Queue();
        q.enqueue(2);
        q.enqueue(3);
       
        q.print();
       
        System.out.println("------------------");
       
        System.out.println(q.dequeue() );
        System.out.println(q.dequeue());
       
        System.out.println("-------------------");
       
        q.print();
       
    }

}

Monday, September 2, 2013

Merge Two Sorted Link Lists into a Third Sorted List

Merge two Sorted Linked List into a Third Linked List


Java program to Merge two sorted lists into a third list. Below program has, both a recursive and iterative version methods


public class MergeLinkList {

    private Link mergeRecursive( Link l1, Link l2 ) {
        if ( l1 == null) return l2;
        if ( l2 == null ) return l1;
       
        Link mergedhead = null;
       
        if ( l1.value() < l2.value() ) {
            mergedhead = l1;
            mergedhead.next = mergeRecursive(l1.next, l2);
        }else {
            mergedhead = l2;
            mergedhead.next = mergeRecursive(l1, l2.next);
        }
        return mergedhead;
    }
   
    private Link mergeInterative( Link  l1, Link l2 ) {
        if ( l1 == null) return l1;
        if ( l2 == null ) return l2;
       
        Link p1 = l1;
        Link p2 = l2;
       
        Link mergedHead= null;
        Link last = mergedHead;
       
        while ( p1!= null && p2 != null ) {
        if ( p1.value() < p2.value() ) {
          if ( last == null ) {
              last = new Link(p1.value());
              mergedHead = last;
          }else {
              last.next = new Link( p1.value());
              last = last.next;
          }
         p1 = p1.next;
        }else {
             if ( last == null ) {
                  last = new Link(p2.value());
                  mergedHead = last;
              }else {
                  last.next = new Link( p2.value());
                  last = last.next;
              }
             p2 = p2.next;
        }               
        }
        if ( p1 != null ) {
            insertAll( p1, last );
        }else
            insertAll( p2, last );
       
        return mergedHead;
    }
   
    private void insertAll( Link p1, Link last ) {
        do {
            last.next = new Link(p1.value());
            p1 = p1.next;
        }while ( p1 != null );
    }
   
public static void main( String[] args ) {
       
        /*
          * .................n..........n.............n.........n.............n.......................n............n..........        ---> Number line for Array1, has 8 numbers in ascend
         * .....n...n...........n......... n...n..........n.........n.................................................................... 
             * */
       
            int[] ar1 = new int[] { 45, 56, 77, 89, 150, 187, 198};
            int len1 = 7;
           
            int[] ar2 = new int[] { 23, 29, 47, 59, 67, 80, 106 };
            int len2 = 7;
           
            Link l1 = Link.build( ar1 );
            Link l2 = Link.build(ar2);
           
            MergeLinkList merge = new MergeLinkList();
            Link mergedIter = merge.mergeInterative(l1, l2);
            mergedIter.print(mergedIter);
           
            System.out.println("Prining recursively");
           
            Link mergedRecursive = merge.mergeRecursive(l1, l2);
            mergedRecursive.print(mergedRecursive);
           
           
    }
}

Sort a given List using Insertion Sort

Sort a Linked List using Insertion Sort

C++ Code to sort a given list
 
void Sort(ListNode** pHead) {
if(pHead == NULL || *pHead == NULL)
return;
ListNode* pToBeSorted = pLastSorted->m_pNext;
while(pToBeSorted != NULL) {
if(pToBeSorted->m_nValue < (*pHead)->m_nValue) {
pLastSorted->m_pNext = pToBeSorted->m_pNext;
pToBeSorted->m_pNext = *pHead;
*pHead = pToBeSorted;
}
else {
ListNode* pNode = *pHead;
while(pNode != pLastSorted
&& pNode->m_pNext->m_nValue < pToBeSorted->m_nValue) {
pNode = pNode->m_pNext;
}
if(pNode != pLastSorted) {
pLastSorted->m_pNext = pToBeSorted->m_pNext;
pToBeSorted->m_pNext = pNode->m_pNext;
pNode->m_pNext = pToBeSorted;
}
else
pLastSorted = pLastSorted->m_pNext;
}
pToBeSorted = pLastSorted->m_pNext;
}
}

Merge Two Sorted Arrays

Merge Two Sorted Arrays into one of the Arrays

Given two sorted arrays, denoted as array1 and array2, 
Merge them into array1 and keep the merged array sorted.
** Assumption: Array1 has enough space to accomodate the elements of Array2
Java Program to Merge Two sorted arrays

public class MergeSortedArrays {
/**
 *                                                                                           |
 *                                                                                           index1
 * .................n..........n.............n.........n.............n.......................n............n...n............        ---> Number line for Array1, has 8 numbers in ascend
 * .....n...n...........n........ n...n..........n.........n....................................................................       ----> Number line for Array2
 *                                              index2
 *                                               |
 * In the above number line 'n' stands for a number in the number line for natural numbers for the given array
 *
 *
 */
   
    public int[] merge( int[] array1, int[] array2, int length1, int length2 ) {
        if ( array1 == null )
            throw new IllegalArgumentException("Invalid array to merge" );
       
        if ( array2 == null || array2.length == 0 )
            return array1;
       
        int index1 = length1- 1;
        int  index2 = length2 -1;
        int mergedBoundary = length1 + length2 - 1;
   
        while( index1 >= 0 && index2 >= 0) {
            if ( array1[index1] > array2[index2] ) {
                array1[mergedBoundary--] = array1[index1--];
            }else {
                array1[mergedBoundary--] = array2[ index2-- ];
            }
        }
        while ( index2 >= 0 ) {
            array1[ mergedBoundary--] = array2[index2--];
        }
       
        return array1;   
       
    }
   
    public static void print( int[] ar, int len ) {
        int i = 0;
        while ( len-- > 0)
            System.out.println( ar[i++ ]);
    }
   
    public static void main( String[] args ) {
        /*
      * .................n..........n.............n.........n.............n.......................n............n..........        ---> Number line for Array1, has 8 numbers in ascend
     * .....n...n...........n......... n...n..........n.........n.................................................................... 
         * */
   
        int[] ar1 = new int[] { 45, 56, 77, 89, 150, 187, 198, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        int len1 = 7;
       
        int[] ar2 = new int[] { 23, 29, 47, 59, 67, 80, 106 };
        int len2 = 7;
        MergeSortedArrays merge = new MergeSortedArrays();
        int[] ar3 = merge.merge( ar1, ar2,  len1, len2 );
        print( ar3, len1+len2 );
    }
}


Sunday, September 1, 2013

An array of Numbers with Multiple Duplicates

How to Find Duplicates in an Array of N numbers ranging from 0 to N-1.

An array contains n numbers ranging from 0 to n-1. There are some numbers duplicated in the
array. It is not clear how many numbers are duplicated or how many times a number gets duplicated. How to find a duplicated number in such an array? For example, if an array of length 7 contains the numbers {2, 3, 1, 0, 2, 5,
3}, the implemented function (or method) should return either 2 or 3.

Java Code:

int duplicate(int numbers[]) {
int length = numbers.length;
for(int i = 0; i < length; ++i) {
if(numbers[i] < 0 || numbers[i] > length - 1)
throw new IllegalArgumentException("Invalid numbers.");
}
for(int i = 0; i < length; ++i) {
while(numbers[i] != i) {
if(numbers[i] == numbers[numbers[i]]) {
return numbers[i];
}
// swap numbers[i] and numbers[numbers[i]]
int temp = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = temp;
}
}
throw new IllegalArgumentException("No duplications.");
}



Thursday, August 29, 2013

Reverse a Link List

 

 Program to Reverse a Link List


public class ReverseLinkList {

     public static Link reverse( Link head ) {
        Link last = null;
        Link p0 = head;
        Link p1 = p0 != null ? p0.next: null;
        Link p2 = p1 != null ? p1.next : null;
       
        return reverse( p0, p1, p2, last );
    }
   
    private static Link reverse( Link p0, Link p1, Link p2, Link last ) {
        if ( p0 == null ) return p0;
        if ( p1 == null ) {
            p0.next = last;
            return p0;
        }
        if ( p2 == null ) {
            p1.next = p0;
            p0.next = last;
            return p1;
        }
       
        // reverse middle, p2 can be null at this point
        p1.next = p0;
        p0.next = last;
       
        // reset pointers
        last = p1;
        p0 = p2;
        p1 = p0.next;
        p2 = p1 != null ? p1.next: null;
       
        return reverse( p0, p1, p2, last );   
       
    }

  public static Link build( int count) {
       
        if ( count == 0 ) return null;
        Link head = new Link( 1 );
        Link last = head;
        int a = 1;
        while ( count-- > 1 ) {
        Link link  = new Link( ++a );
        last.next = link;
        last = link;
        }
        return head;
    }
   
    public static void print( Link head ) {
        if ( head == null ) return;
        int count = 1;
    Link k = head;
        do {
            System.out.println( count++ + "::"+ k.name());
            k = k.next;
        }while( k != null );
    }

public static void main( String[] args ) {
        Link head = build(10);
        print( head );
        Link reverseHead = reverse( head );
        System.out.println("Reversing");
        print( reverseHead );
    }


}

class Link {
    private String name;
    Link next;
   
    Link( int name, Link next ) {
        this.name = name + "";
        this.next = next;
    }
   
    Link ( int name ) {
        this( name, null );
    }
   
    String name() {
        return this.name;
    }
   
}

Friday, June 28, 2013

Find Second largest Element in an Array

Find Second largest Element in an Array in Minimum Time Complexity


1. State different ways and the Complexities involved with them

  • Keep two pointers, largest, second_largest. Let the first element is largest and second element as second_largest. Compare. After comparison, largest, second_largest will point to right array indices. Move from the third index till the end of array. At each entry to loop, again compare and reset the pointers: largest and second_largest. This solution is of order n, o(n) as there are almost 2n comparisons

A general variation of this problem will be to find out the kth largest in an array of N numbers

  • Kth largest logically means that in a set of K elements , find the smallest element. This smallest in the set of K elements is the Kth largest for the set of K. So steps include

Using Min-heap

    • Get the first K elements. Construct a min-heap of it. Order of Complexity of constructing this heap = kLog(k)
    • Root of this min-heap, which is the smallest of this heap, is the currently the kth largest on this set of k
    • a: Iterate over the array from k+1 index. Get the k+1 element of array. If it is less, ignore it
    • b: If k+1 th element is greater then root, then insert this element in the min-heap. Order of Complexity for this Log(k)
    • c: Remove the smallest , which is the new root. order of Complexity for this is again Log(k)
    • d: Now the min-heap again contains K elements, the new root is now the K th largest.
    • Do the steps a, b, c, d, for the rest of the elements of array
Order of Complexity in this case:
Order of Complexity to construct the min-heap of K elements = kLog(k)- one time
order of Complexity to insert a new element = kLog(k) - ( n-k) times
order of Complexity to remove the root = kLog(k) - ( n-k) times

Total complexity, order :
kLog(k) + 2*(n-k)*Log(k)

Serialize a Binary Search tree


Monday, February 18, 2013

Jersey Mutipart - Resource that Produces MULTIPART Response and Client code to process it



Handling 'MULTIPART/MIXED'  using Jersery Apis.

Jars required:

a. ) jersey-bundle-1.13.jar
b. ) jersey-multipart-1.13.jar

Jersey Client to GET a Multipart Http Request

______________________________________--

Lets build a client equired to GET a Multipart Response. This Response that has two BodyParts.

1. An xml Input : This is the first body part. It is an Xml representation for a JAXB object  ,MyEntity E
2. Byte[] array : This array of bytes is the second body part. This byte array is the content of the file produced by a REST resource

So the aim is to create a jersery client and GET a MULTIPART request.


                  final long resourceId = 1026l;
final String exportUrl =  "get Export Resource URL"
final String path = "/" + resourceId ;

Client c = Client.create();
WebResource service = c.resource(exportUrl );

MultiPart multipart = service.path(path).type(MediaType.APPLICATION_XML).header( headerKey, headerValue).get(MultiPart.class);

List bodyParts = multipart.getBodyParts();
String xmlResponse = bodyParts.get(0).getEntityAs(String.class);
byte[] exportedContent = bodyParts.get(1).getEntityAs(byte[].class);
System.out.println("XML  = " + xmlResponse);
System.out.println("\n\n");
System.out.println("ExportedContent : \n");
System.out.println(new String(exportedContent ));


/////////////// The FileExport Resource that would Produce this Multipart Request ///////////////////////

       @GET
@Path("{id}")
@Produces("multipart/mixed")
public Response read(@PathParam("id") String resourceId , @Context HttpHeaders headers,
@Context UriInfo uriInfo) // add other @Context arguments if required
{
          // process Request and fetch Xml Response Strinrg
           String responseStr = getResponseStrForResourceId( reesource Id );
         
           // build Multipart Web Response
           MultiPart multipart = buildMultipartResponse(responseStr);
 
            Response response = Response.status(status).header( headerKey, headerValue ) .entity(multipart).type(MultiPartMediaTypes.MULTIPART_MIXED).build();

return response;

       }

  // build Multipart Data
   MultiPart buildMultipartResponse(String xmlResponseStr)
{
MultiPart multiPart = new MultiPart();
multiPart.bodyPart(new BodyPart(xmlResponseStr, MediaType.APPLICATION_XML_TYPE)).bodyPart(
new BodyPart(getAttachmentBytes(), MediaType.APPLICATION_OCTET_STREAM_TYPE));

return multiPart;
}

Jersey Mutipart - Resource that Consumes MULTIPART and Client that POSTs such a request


Handling 'MULTIPART/MIXED'  using Jersery Apis.

Jars required:

a. ) jersey-bundle-1.13.jar
b. ) jersey-multipart-1.13.jar

Jersey Client to POST Multipart Http Request

______________________________________--

Lets build a client that requires to POST to a REST resource a multipart request that has two body parts

1. An xml Input : This is the first body part. Let the JAXB object created for this be Represented by MyEntity E
2. Byte[] array : This array of bytes is the second body part. This byte array is the content of the file that needs to imported , along with the above xml input

So the aim is to create a jersery client and post a multipart request.

        String fileImporUrl = "URl to the resource that would handle this request"

   Client c = Client.create();
   WebResource service = c.resource(fileImporUrl );

   // Construct a MultiPart with two body parts

    // Construct the JAXB object for the Input Xml 
   MyEntity E = new MyEntity ();
          // E.setname( "anbc" );
          //E.setId(123 );
          .............
         ..... Build the Entity
 
            // read the file and get bytes to import
   byte[] bytesToImport = getBytesToImport();
 
               // Construct Multipart Request. Content-type of the first part is 'application/xml '
              // and second part is 'appication/octet-stream'
   MultiPart multiPart = new MultiPart().
    bodyPart(new BodyPart(E, MediaType.APPLICATION_XML_TYPE)).
     bodyPart(new BodyPart(bytesToImport, MediaType.APPLICATION_OCTET_STREAM_TYPE));

   // POST the request
   ClientResponse response = service.path("/import").
     type("multipart/mixed").header( headerKey, headerValue).post(ClientResponse.class, multiPart);

   System.out.println( "Import Response status = " + response.getStatus() );


/////////////// A FileImport Resource that would consume this Multipart Request ///////////////////////

    @POST
@Consumes("multipart/mixed")
@Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_XML })
public Response importFile(MultiPart multipart, @Context HttpHeaders headers, @Context UriInfo uriInfo) // add other context if required
{

final int INDEX_XML = 0; final int INDEX_FILE_CONTENT = 1; MultipartBodyEntityContent bodyEntityContent = new MultipartBodyEntityContent(); MyEntity E = null; BodyPartEntity fileContentAsBodyPart = null; try { E = multipart.getBodyParts().get(INDEX_XML).getEntityAs(MyEntity.class); fileContentAsBodyPart = (BodyPartEntity) multipart.getBodyParts().get(INDEX_FILE_CONTENT).getEntity(); byte[] byteContent = getByteArrayFromInputStream( fileContentAsBodyPart .getInputStream() );

// Process the MyEntity E and byteContent and return Response }

}

// get byte[] from Input Stream byte[] getByteArrayFromInputStream(InputStream in) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[4096]; while ((nRead = in.read(data, 0, data.length)) != -1) buffer.write(data, 0, nRead); buffer.flush(); buffer.close(); return buffer.toByteArray(); }