Pages

Wednesday, July 9, 2014

7z Compression of files using Apache Commons Compress API

Here is a demo program to demonstrate archiving of files to 7z format using Apache Commons Compress API

List of Jars required:
  • xz-1.4.jar
  • commons-compress-1.8.jar

    package demo.sevenzcompression.examples;
    
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    
    import org.apache.commons.compress.archivers.sevenz.*;
    
    public class SevenZCompressionDemo {
    
    	public static void main(String args[]) {
    
    		// set the files to be archived
    		File file1 = new File("Demo1.csv");
    		File file2 = new File("Demo2.csv");
    		File file3 = new File("Demo3.csv");
    		File file4 = new File("Demo4.csv");
    
    		// add files to an array list
    		ArrayList<File> filesToArchive = new ArrayList<File>();
    		filesToArchive.add(file1);
    		filesToArchive.add(file2);
    		filesToArchive.add(file3);
    		filesToArchive.add(file4);
    
    		// get formatted file name with system date (ex: Archive_20140709.7z)
    		String sevenZarchiveFileName = getFormattedFileName();
    		File sevenZFile = new File(sevenZarchiveFileName);
    		SevenZOutputFile sevenZOutput = null;
    
    		System.out.println("Attempting to create " + sevenZarchiveFileName
    				+ ".......");
    
    		try {
    			sevenZOutput = new SevenZOutputFile(sevenZFile);
    		} catch (IOException e1) {
    
    			System.out.println(e1.getMessage());
    			System.exit(0);
    		}
    		for (int i = 0; i < filesToArchive.size(); i++) {
    			try {
    
    				SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(
    						filesToArchive.get(i), filesToArchive.get(i).getName());
    				sevenZOutput.putArchiveEntry(entry);
    				FileInputStream in = new FileInputStream(filesToArchive.get(i));
    				byte[] b = new byte[1024];
    				int count = 0;
    				while ((count = in.read(b)) > 0) {
    					sevenZOutput.write(b, 0, count);
    				}
    				sevenZOutput.closeArchiveEntry();
    				in.close();
    
    			} catch (IOException e) {
    
    				System.out.println(e.getMessage());
    				System.exit(0);
    			}
    		}
    		try {
    			sevenZOutput.close();
    			System.out.println("Archive " + sevenZarchiveFileName
    					+ " created successfully.......");
    
    		} catch (IOException e) {
    
    			System.out.println(e.getMessage());
    
    		}
    
    	}
    
    	private static String getFormattedFileName() {
    
    		long millis = System.currentTimeMillis();
    		Date date = new Date(millis);
    		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
    		String filename = "Archive_" + df.format(date) + ".7z";
    		return filename;
    	}
    
    }
    


Thursday, June 5, 2014

XML over HTTP POST using Apache HTTPClient 4.x

Here is an Example on how to send XML data over HTTP POST using Apache HTTPClient 4.x

JARs required:
httpclient-4.3.3.jar
httpcore-4.3.2.jar
commons-logging-1.1.3.jar
commons-io-2.4.jar


package demo.pckg.httpclient;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

public class HTTPClientDemo {

 public static void main(String[] args) {

  String inputXML = "<data> <name>XYZ</name> <message>Hello XYZ...!!!</message> </data>";
  InputStream in ;
  StringEntity entity = new StringEntity(inputXML, ContentType.create(
    "text/xml", Consts.UTF_8));
  entity.setChunked(true);
  HttpPost httppost = new HttpPost(
    "http://localhost:8080/MyRestService/rest/UserService");

  httppost.setEntity(entity);

  HttpClient client = HttpClients.createDefault();

  try {
   HttpResponse response = client.execute(httppost);
   System.out.println(response.toString());
   in=response.getEntity().getContent();
   String body = IOUtils.toString(in);
   System.out.println(body);
  } catch (ClientProtocolException e) {
   System.out.println(e);
  } catch (IOException e) {
   System.out.println(e);
  }

 }
}


Thursday, March 6, 2014

Build and Send a SOAP message to a webservice

Below is an example on how to build and send a SOAP message to a web service.

MyWebservice accepts Name (String) as input and returns a hello message (String) as output.

Here is a piece of code which builds and sends the SOAP message to a MyWebservice



package demo.ws;

import javax.xml.soap.*;

import java.util.*;
import java.net.URL;

public class MySOAPRequestBuilder {
 public static void main(String[] args) {
  try {
   SOAPConnectionFactory scFactory = SOAPConnectionFactory
     .newInstance();
   SOAPConnection con = scFactory.createConnection();

   MessageFactory factory = MessageFactory.newInstance();
   SOAPMessage message = factory.createMessage();

   SOAPPart soapPart = message.getSOAPPart();
   
   //Getting SOAP Envelope
   SOAPEnvelope envelope = soapPart.getEnvelope();
   
   //Getting SOAP Header
   SOAPHeader header = envelope.getHeader();
   
   //Getting SOAP Body
   SOAPBody body = envelope.getBody();
   header.detachNode();

   Name bodyName = envelope.createName("sayHello", "m",
     "http://ws.demo");
   SOAPBodyElement gltp = body.addBodyElement(bodyName);

   Name name = envelope.createName("name");
   SOAPElement symbol = gltp.addChildElement(name);
   symbol.addTextNode("Foo");

   URL endpoint = new URL(
     "http://localhost:8080/MyWS/services/MyWebService/sayHello");
     
   //Sending SOAP message to Endpoint and collecting response object
   SOAPMessage response = con.call(message, endpoint);

   con.close();

   //Reading response object
   SOAPPart sp = response.getSOAPPart();
   SOAPEnvelope se = sp.getEnvelope();
   SOAPBody sb = se.getBody();

   //Iterating through SOAP Body Elements
   Iterator it = sb.getChildElements();
   SOAPBodyElement sbe = (SOAPBodyElement) it.next();
   
   //Iterating through SOAP elements
   Iterator it1 = sbe.getChildElements();
   SOAPElement se1 = (SOAPElement) it1.next(); 
   
   //Printing response to console
   System.out.print("Response is ");
   System.out.print(se1.getValue());
   

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



Output of the code: 

Response is Hello Foo !!!!



Example SOAP Request:

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.demo" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
 <q0:sayHello>
  <q0:name>Foo</q0:name>
  </q0:sayHello>
  </soapenv:Body>
  </soapenv:Envelope>


Example SOAP Response:

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
 <soapenv:Body>
 <ns:sayHelloResponse xmlns:ns="http://ws.demo">
  <ns:return>Hello Foo !!!!</ns:return>
  </ns:sayHelloResponse>
  </soapenv:Body>
  </soapenv:Envelope>