Static Blocks in Java with Example

Static block in a class are the block of code portion which  executed only once,

1.Before creation of any object of the class.

2.Before any static member of the class in been accessed.

Example: Before creation of any object of the class

package com.devil.java.concept;

public class StaticBlockForConstructor {

static {
System.out.println("I am in first static block");
}

public StaticBlockForConstructor() {
System.out.println("I am in the constructor");
}

public static void main(String args[]) {
StaticBlockForConstructor constr1 = new StaticBlockForConstructor();
StaticBlockForConstructor constr2 = new StaticBlockForConstructor();
}
}

 
Important point to note that static block is been exceuted only once when we create first object constr1
and not when second object constr2 is been created .Output of the above programme is :

I am in first static block
I am in the constructor
I am in the constructor

We can use multiple static blocks as well, they will be executed in the order they are defined in the class, like:

package com.devil.java.concept;

public class StaticBlockForConstructor {

static {
System.out.println("I am in First static block");
}

static {
System.out.println("I am in Second static block");
}

static {
System.out.println("I am in Third static block");
}

public StaticBlockForConstructor() {
System.out.println("I am in the constructor");
}

public static void main(String args[]) {
StaticBlockForConstructor constr1 = new StaticBlockForConstructor();
StaticBlockForConstructor constr2 = new StaticBlockForConstructor();
}
}

Output of the above programme will be :

I am in First static block
I am in Second static block
I am in Third static block
I am in the constructor
I am in the constructor

Example: Before any static member of the class in been accessed.

package com.devil.java.concept;

public class StaticBlock {
static int i;

static {
i = 10;
System.out.println("static block called here");
}

public static void main(String args[]) {

System.out.println(StaticBlock.i);
}
}

Output of the above programme will be:

static block called here
80

If we use multiple variables , in that case also static block will be executed only once like:

package com.devil.java.concept;

public class StaticBlock {
static int i;
static int j;
static int k;

static {
i = 80;
j = 90;
k = 150;
System.out.println("static block called here");
}

public static void main(String args[]) {

System.out.println(StaticBlock.i);
System.out.println(StaticBlock.j);
System.out.println(StaticBlock.k);
}
}

Output of the above programme will be:

static block called here
80
90
150

So that is it about the static block in Java. Hope it will be helpful.

Generics in Java with examples

Generics has been introduced in java 1.5.Generics provide many advantage like code re-usability and detect compile time error related to type safety.

Idea is to pass object as an parameter to the class, function and interface(like passing object Integer,Double or any other user defined object).
Primitive types like int, double etc are not allowed to pass as an parameter.

Generic Class Illustration:

package com.devil.java.generics;

public class GenericClass<T> {
T genericObject;

public GenericClass(T obj) {
this.genericObject = obj;
}

public T getGenericObject() {
return genericObject;
}

}

For creating object for the above class:

When String is passed as an parameter:

GenericClass<String> stringObject = new GenericClass<String>(
"Merry Christmas");

When Integer is passed as an parameter:

GenericClass<Integer> intObject = new GenericClass<Integer>(10);

When Double is passed as an parameter:

GenericClass<Integer> intObject = new GenericClass<Integer>(80.89);

Now if we try to pass primitive type as an parameter,it will give compile error.Like below code will give compile error.

GenericClass<int> doubleObject = new GenericClass<int>(80);

Example illustrating above object (not primitive type)passing is:

package com.devil.java.generics;

public class GenericClassMain {

public static void main(String args[]) {
GenericClass<String> stringObject = new GenericClass<String>(
"Merry Christmas");
String str = stringObject.getGenericObject();
System.out.println("String name from Generic is: " + str);

GenericClass<Integer> intObject = new GenericClass<Integer>(10);

Integer intNumber = intObject.getGenericObject();
System.out.println("IntNumber from generic is :" + intNumber);

GenericClass<Double> doubleObject = new GenericClass<Double>(80.89);

Double doubleNumber = doubleObject.getGenericObject();
System.out.println("Double Number from generic is :" + doubleNumber);
}
}

Output of the above Programme will be:
String name from Generic is: Merry Christmas
IntNumber from generic is :10
Double Number from generic is :80.89

We can pass multiple type parameters as well like:

class name<T1, T2, …, Tn> { /* … */ }

Like in this example , we are passing three parameter.

package com.devil.java.generics;

public class GenericClassMultipleParameter<T, S, U> {
public T obj1;
public S obj2;
public U obj3;

public GenericClassMultipleParameter(T ob1, S ob2, U ob3) {
this.obj1 = ob1;
this.obj2 = ob2;
this.obj3 = ob3;
}

public void printParameter() {
System.out.println("First Parameter is: " + obj1);
System.out.println("Second Parameter is: " + obj2);
System.out.println("Third Parameter is: " + obj3);

}
}

Programme to use above class is :

package com.devil.java.generics;

public class GenericClassMultipleParameterMain {
public static void main(String args[]) {
GenericClassMultipleParameter<String, Integer, Double> genericObject =
new GenericClassMultipleParameter<String, Integer, Double>(
"Merry Christmas", 100, 900.67);
genericObject.printParameter();
}
}

Output of the above programme will be:

First Parameter is: Merry Christmas
Second Parameter is: 100
Third Parameter is: 900.67

Generic Function Illustration:

In the generic function we will use parameters between access modifier and return type like this:

For one parameter:

public <T> void printDetail(T object){/*....*/ }

For multiple parameters:

public <T,U,V> void printDetail(T object1,U object2,V object3){/*....*/}

Example illustrating using of one parameter:


package com.devil.java.generics;

public class GenericFuncton {

public <T> void printDetail(T object) {
System.out.println("Passed object is :" + object.getClass().getName()
+ " and value is :" + object);
}

public <T> T getObjectDetail(T object) {
return object;
}

public static void main(String args[]) {
GenericFuncton function = new GenericFuncton();
function.printDetail("Merry Christmas");
function.printDetail(800);
function.printDetail(456.90);

String str = function.getObjectDetail("Merry Christmas-2016");
System.out.println("Value of returned String object is: " + str);
/**similarly we can get do for other parameter */

}
}

Output of the above programme will be :

Passed object is :java.lang.String and value is :Merry Christmas
Passed object is :java.lang.Integer and value is :800
Passed object is :java.lang.Double and value is :456.9
Value of returned String object is: Merry Christmas-2016

Example illustrating using of multiple parameters:

package com.devil.java.generics;

package com.devil.java.generics;

public class GenericFunctonMultipleParameter {
public <T, U, V> void printDetail(T object1, T object2, T object3) {
System.out.println("First Passed object is :"
+ object1.getClass().getName() + " and value is :" + object1);

System.out.println("Second Passed object is :"
+ object2.getClass().getName() + " and value is :" + object2);

System.out.println("Third Passed object is :"
+ object1.getClass().getName() + " and value is :" + object3);
}

public static void main(String args[]) {
GenericFunctonMultipleParameter function =
new GenericFunctonMultipleParameter();
function.printDetail("Merry Christmas",800,456.90);

}
}

Output of the above programme will be :

First Passed object is :java.lang.String and value is :Merry Christmas
Second Passed object is :java.lang.Integer and value is :800
Third Passed object is :java.lang.String and value is :456.9

Advantage of using Java Generics:

1.Code re-usabilty:We can write a generic method/class/interface once and use for any type we want.

2.Using of generics will detect errors at compile rather than throwing error/exception at run time.like if we do not use generic collection (say ArrayList) in our example.It will allow insertion of 10 (Integer type) at compile time but will throw exception at run time.

package com.devil.java.generics;

import java.util.ArrayList;

public class NoTypeSafety {
public static void main(String[] args)
{
ArrayList al = new ArrayList();

al.add("Banglore");
al.add("Kolkata");
al.add(10); // Compiler allows this

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);

// throws Runtime Exception
String s3 = (String)al.get(2);
}
}

Output will be :

Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.devil.java.generics.NoTypeSafety.main(NoTypeSafety.java:18)

Using of generics will solve this problem and will detect error at compile time, like this:

package com.devil.java.generics;

import java.util.ArrayList;

public class TypeSafety {
public static void main(String[] args)
{
ArrayList <String> al = new ArrayList<String> ();

al.add("Banglore");
al.add("Kolkata");

//  Compiler doesn't allow this
al.add(10);

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}

Compiler error will be :
The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)

 

 

So this is all about using of generics  in Java.Let me now if there is any questions.

Upload/POST XML data or XML data object to an URL (i.e Web Service URL) through HTTP POST Request in Java

This is about how we can post XML data or data object to an URL( webservice URL or any other URL which can accept these POST request.)

Common Scenario: Lets say we are having data in some tables and we want to post /send these data in the form of xml request to some external URL( which can be a web service URL). We will convert each of these row data in to xml data object and will send this xml data object with the help  marshalling/de-marshalling functionality and will do a POST request to the external URL.

Below is the XML data object used for carrying XML data .

TransactionXMLData Class:

package com.abc.xyz.xml.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Transaction")
public class TransactionXMLData {

@XmlElement(name = "TransactionId")
private long transactionId;
@XmlElement(name = "DCCode")
private String dcCode;
@XmlElement(name = "TransactionType")
private String transactionType;
@XmlElement(name = "TransactionDate")
private Date transactionDate;
@XmlElement(name = "SourceLicensePlateNo")
private String sourceLicensePlateNo;
@XmlElement(name = "DestLicensePlateNo")
private String destLicensePlateNo;
@XmlElement(name = "ProductId")
private String productId;
@XmlElement(name = "PerformedBy")
private String performedBy;
@XmlElement(name = "OrderId")
private String orderId;
@XmlElement(name = "OrderType")
private String orderType;
@XmlElement(name = "OrderLineNo")
private String orderLineNo;

public long getTransactionIdValue() {
return transactionId;
}
public void setTransactionId(long transactionId) {
this.transactionId = transactionId;
}
public String getDcCodeValue() {
return dcCode;
}
public void setDcCode(String dcCode) {
this.dcCode = dcCode;
}
public String getTransactionTypeValue() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public Date getTransactionDateValue() {
return transactionDate;
}
public void setTransactionDate(Date transactionDate) {
this.transactionDate = transactionDate;
}
public String getSourceLicensePlateNoValue() {
return sourceLicensePlateNo;
}
public void setSourceLicensePlateNo(String sourceLicensePlateNo) {
this.sourceLicensePlateNo = sourceLicensePlateNo;
}
public String getDestLicensePlateNoValue() {
return destLicensePlateNo;
}
public void setDestLicensePlateNo(String destLicensePlateNo) {
this.destLicensePlateNo = destLicensePlateNo;
}
public String getProductIdValue() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getPerformedByValue() {
return performedBy;
}
public void setPerformedBy(String performedBy) {
this.performedBy = performedBy;
}
public String getOrderIdValue() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderTypeValue() {
return orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public String getOrderLineNoValue() {
return orderLineNo;
}
public void setOrderLineNo(String orderLineNo) {
this.orderLineNo = orderLineNo;
}
}

WebServiceUploadConfig Class:

package com.abc.xyz;
public class WebServiceUploadConfig {
private String url;
private String username;
private String password;

public WebServiceUploadConfig(String url) {
super();
this.url = url;
}
public WebServiceUploadConfig(String url, String username, String password) {
super();
this.url = url;
this.username = username;
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

 

WebServiceUploadException Class:


package com.abc.xyz.exception;

public class WebServiceUploadException extends Exception {

private static final long serialVersionUID = 1L;

public WebServiceUploadException(String msg) {
super(msg);
}

public WebServiceUploadException(Throwable t) {
super(t);
}

public WebServiceUploadException(String msg, Throwable t) {
super(msg, t);
}
}

WebServiceUploadAudit Class:


package com.abc.xyz.model.dataobjects;
import java.util.Date;

public class WebServiceUploadAudit {
private long id;
private long transactionId;
private String transactionType;
private String remoteHost;
private String requestURL;
private String requestBody;
private Date sendDate;
private String responseHeader;
private String responseBody;
private String host;
private String userId;
private boolean success;
private String errorMessage;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getRemoteHost() {
return remoteHost;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public String getRequestURL() {
return requestURL;
}
public void setRequestURL(String requestURL) {
this.requestURL = requestURL;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getResponseHeader() {
return responseHeader;
}
public void setResponseHeader(String responseHeader) {
this.responseHeader = responseHeader;
}
public String getResponseBody() {
return responseBody;
}
public void setResponseBody(String responseBody) {
this.responseBody = responseBody;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public boolean getSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public long getTransactionId() {
return transactionId;
}
public void setTransactionId(long transactionId) {
this.transactionId = transactionId;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}

}

XMLConverter Class:


package com.abc.xyz;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class XMLConverter {
Logger logger = Logger.getLogger(XMLConverter.class);
private Marshaller marshaller;
private Unmarshaller unmarshaller;

public Marshaller getMarshaller() {
return marshaller;
}
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}

public void convertFromObjectToOutPutStream(Object object,OutputStream os)
throws IOException {
if (logger.isInfoEnabled()) {
logger.info("converting object to xml");
}
try {
getMarshaller().marshal(object, new StreamResult(os));
} finally {
if (os != null) {
os.close();
}
}
}

public Object convertFromXMLToObject(String xmlfile) throws IOException {
if (logger.isInfoEnabled()) {
logger.info("converting xml to object");
}

FileInputStream is = null;
try {
is = new FileInputStream(xmlfile);
return getUnmarshaller().unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}

}

WebServiceUploadAuditDAO Class:

package com.abc.xyz.dao;

import com.abc.xyz.model.dataobjects.WebServiceUploadAudit;

public interface WebServiceUploadAuditDAO {

public void save(WebServiceUploadAudit audit);

}

WebServiceUploadAuditDAOImpl Class:

package com.abc.xyz.dao;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;

import com..abc.xyz.model.dataobjects.WebServiceUploadAudit;

public class WebServiceUploadAuditDAOImpl implements WebServiceUploadAuditDAO {
Logger logger = Logger.getLogger(WebServiceUploadAuditDAOImpl.class);
private JdbcTemplate jdbcTemplate;

public void save(WebServiceUploadAudit audit) {
if (logger.isInfoEnabled()) {
logger.info("Inserting Data in WEBSERVICE_UPLOAD_LOG table");
}

String insertQuery = "INSERT INTO      WEBSERVICE_UPLOAD_LOG(ID,REMOTE_HOST,REQUEST_URL,SEND_DATE,HOST,USER_ID,SUCCESS_IND,ERROR_MESSAGE,TRANSACTION_ID,TRANSACTION_TYPE,REQUEST_BODY,RESPONSE_HEADER,RESPONSE_BODY)values(WEBSERVICE_UPLOAD_LOG_SEQ.nextval,?,?,?,?,?,?,?,?,?,?,?,?)";
jdbcTemplate.update(
insertQuery,
new Object[] { audit.getRemoteHost(), audit.getRequestURL(),
audit.getSendDate(), audit.getHost(),
audit.getUserId(), audit.getSuccess(),
audit.getErrorMessage(), audit.getTransactionId(),
audit.getTransactionType(), audit.getRequestBody(),
audit.getResponseHeader(), audit.getResponseBody() });
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}

 

XMLUploadBusinessProcessImpl Class: This is the class used for POST request of xml data to an URL.

 


package com.abc.xyz.businessprocess;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.abc.xyz.WebServiceUploadConfig;
import com.abc.xyz.XMLConverter;
import com.abc.xyz.dao.WebServiceUploadAuditDAO;
import com.abc.xyz.exception.WebServiceUploadException;
import com.abc.xyz.model.dataobjects.WebServiceUploadAudit;
import com.abc.xyz.xml.model.TransactionXMLData;

public class XMLUploadBusinessProcessImpl implements XMLUploadBusinessProcess {
private XMLConverter xmlConverter;

private WebServiceUploadAuditDAO webServiceUploadAuditDAO;
Logger logger = Logger.getLogger(XMLUploadBusinessProcessImpl.class);

public void processTransactionXMLObjectForUpload(
WebServiceUploadConfig webServiceUploadConfig,
TransactionXMLData transactionXMLData)
throws WebServiceUploadException {
if (webServiceUploadConfig == null)
throw new IllegalArgumentException("WebServiceUploadConfig is null");

WebServiceUploadAudit audit = new WebServiceUploadAudit();
HttpClient client = HttpClientBuilder.create().build();
try {

ByteArrayOutputStream baos = new ByteArrayOutputStream();
xmlConverter.convertFromObjectToOutPutStream(transactionXMLData,
baos);

HttpPost post = new HttpPost(webServiceUploadConfig.getUrl());

if (!StringUtils.isEmpty(webServiceUploadConfig.getUsername())) {

post.addHeader(new BasicScheme().authenticate(
new UsernamePasswordCredentials(webServiceUploadConfig
.getUsername(), webServiceUploadConfig
.getPassword()), null, null));
}
InputStreamEntity reqEntity = new InputStreamEntity(
new ByteArrayInputStream(baos.toByteArray()), -1);

post.addHeader("Content-Type", "application/xml");
post.setEntity(reqEntity);
String host = "hostname";
audit.setHost(host);
audit.setSuccess(true);
audit.setRequestURL(webServiceUploadConfig.getUrl());
audit.setUserId(webServiceUploadConfig.getUsername());

audit.setRequestBody(baos.toString());

audit.setSendDate(new Date());
audit.setTransactionId(transactionXMLData.getTransactionIdValue());
audit.setTransactionType(transactionXMLData
.getTransactionTypeValue());

HttpResponse response = client.execute(post);

// convert header to string
StringBuilder sb = new StringBuilder();

sb.append("HTTP Response Status: ");
sb.append(response.getStatusLine().toString());
// attach new line
sb.append("\n");

Header[] headers = response.getAllHeaders();

for (int i = 0; i < headers.length; i++) {
sb.append(headers[i].getName());
sb.append(":");
sb.append(headers[i].getValue());

// attach new line
sb.append("\n");
}

audit.setResponseHeader(sb.toString());

ByteArrayOutputStream responseBaos = new ByteArrayOutputStream();
response.getEntity().writeTo(responseBaos);

audit.setResponseBody(responseBaos.toString());

if (logger.isInfoEnabled()) {
logger.info("response" + response.getEntity().getContent()
+ "-" + response.getStatusLine());
}

if (response.getStatusLine().getStatusCode() != 200) {
audit.setSuccess(false);
audit.setErrorMessage("Status code is not success: "
+ response.getStatusLine());
throw new WebServiceUploadException(response.getStatusLine()
.toString());
}

} catch (Throwable t) {
logger.warn("Error response", t);
audit.setSuccess(false);
audit.setErrorMessage(t.getMessage());
throw new WebServiceUploadException(t);
} finally {
webServiceUploadAuditDAO.save(audit);
}

}

&nbsp;

 

So with the above approach, we can send XML data to an external URL (i.e Web service URL)

throgh http POST request.