Monday, 23 October 2017

Merge generic arrays

In this post, I am going to show you how to merge generic arrays.

First, we need to define a generic array, that takes variable number of generic arrays as arguments and return a generic array. Method signature looks like below.
public static <T> T[] mergeArrays(T[]... arr)


Next, we need to identify the size of the resulting (after merging all the elements of input arrays) array.


Below snippet is used to calculate the length of output array.
  int finalArraySize = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;
   finalArraySize += array.length;
  }

Define generic array with length ‘finalArraySize’. By using reflection, we can define gneric array.
T[] result = (T[]) Array.newInstance(arr[0].getClass().getComponentType(), finalArraySize);

Now, you can copy all the input array elements to result array. I am using System.arraycopy method to copy elements of array.
  int offset = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;

   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }


Find the below working application.


Test.java
import java.lang.reflect.Array;

public class Test {
 @SuppressWarnings("unchecked")
 public static <T> T[] mergeArrays(T[]... arr) {
  if (arr == null) {
   return null;
  }
  int finalArraySize = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;
   finalArraySize += array.length;
  }

  /* Define array with given size */
  T[] result = (T[]) Array.newInstance(arr[0].getClass().getComponentType(), finalArraySize);
  int offset = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;

   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }

  return result;
 }

 private static void printArray(Object[] arr) {
  for (Object data : arr) {
   System.out.print(data + " ");
  }
 }

 public static void main(String args[]) {
  Integer[] arr1 = { 2, 3, 5, 7 };
  Integer[] arr2 = { 1, 3, 5, 7, 11 };
  Integer[] arr3 = null;
  Integer[] arr4 = { 2, 4, 6, 8, 10 };

  Integer[] result = mergeArrays(arr1, arr2, arr3, arr4);
  printArray(result);

 }
}




Sunday, 22 October 2017

Convert epoch to human readable format

In this post, I am going to explain how to convert epoch time to human readable format.

SimpleDateFormat class provides format method to convert given date into human readable format.

Step 1: Get Date instance from seconds.
Date date = new Date(seconds);

Step 2: Create instance of SimpleDateFormat class.
DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

Step 3: Use the format method to convert given date into human readable form.
formatter.format(date);

Find the below working application.

Test.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
 public static String getDateFromSeconds(long seconds) {
  Date date = new Date(seconds);
  DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
  return formatter.format(date);
 }

 public static void main(String args[]) {
  long timeInSeconds = 1508683954000l;

  String date = getDateFromSeconds(timeInSeconds);
  System.out.println(date);
 }
}

Output
2017.10.22 20:22:34

Below are some of the examples to format given date.

"K:mm a, z"
"EEE, d MMM yyyy HH:mm:ss Z"
"yyMMddHHmmssZ"
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
"yyyyy.MMMMM.dd GGG hh:mm aaa"
"hh 'o''clock' a, zzzz"
"yyyy.MM.dd G 'at' HH:mm:ss z"
"EEE, MMM d, ''yy"
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
"YYYY-'W'ww-u"
"h:mm a"

You may like
Interview Questions

Wednesday, 18 October 2017

Convert query string to name value pair (map)

Query string is part of the URL, used to pass the extra information to the request.

Ex
http://example.com/employee?name=devi&city=Ongole

In the above example ‘name=devi&city=Ongole’ is the query string.

Below snippet converts the query string to a map.
 private static Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException {
  if (queryString == null || queryString.isEmpty()) {
   return Collections.EMPTY_MAP;
  }

  String[] queryParams = queryString.split("&");
  Map<String, String> map = new HashMap<>();

  for (String queryParam : queryParams) {
   int index = queryParam.indexOf('=');
   String key = queryParam.substring(0, index);
   key = URLDecoder.decode(key, "UTF-8");

   String value = null;

   if (index > 0) {
    value = queryParam.substring(index + 1);
    value = URLDecoder.decode(value, "UTF-8");
   }

   map.put(key, value);
  }

  return map;
 }

Find the below working application.


Test.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Test {

 private static Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException {
  if (queryString == null || queryString.isEmpty()) {
   return Collections.emptyMap();
  }

  String[] queryParams = queryString.split("&");
  Map<String, String> map = new HashMap<>();

  for (String queryParam : queryParams) {
   int index = queryParam.indexOf('=');
   String key = queryParam.substring(0, index);
   key = URLDecoder.decode(key, "UTF-8");

   String value = null;

   if (index > 0) {
    value = queryParam.substring(index + 1);
    value = URLDecoder.decode(value, "UTF-8");
   }

   map.put(key, value);
  }

  return map;
 }

 private static void printMap(Map<String, String> map) {
  Set<Map.Entry<String, String>> entrySet = map.entrySet();

  for (Map.Entry<String, String> entry : entrySet) {
   System.out.println(entry.getKey() + " : " + entry.getValue());
  }
 }

 private static void parseAndPrintQueryString(String queryString) throws UnsupportedEncodingException {
  Map<String, String> map = parseQueryString(queryString);
  System.out.println("\nFor the query String : " + queryString);
  printMap(map);
 }

 public static void main(String args[]) throws IOException, ClassNotFoundException {

  String queryString1 = "name=devi&city=Ongole";
  String queryString2 = "name=&city=Ongole";
  String queryString3 = "name=devi&city=";
  String queryString4 = "name=&city=";

  parseAndPrintQueryString(queryString1);
  parseAndPrintQueryString(queryString2);
  parseAndPrintQueryString(queryString3);
  parseAndPrintQueryString(queryString4);
 }
}

Output
For the query String : name=devi&city=Ongole
city : Ongole
name : devi

For the query String : name=&city=Ongole
city : Ongole
name : 

For the query String : name=devi&city=
city : 
name : devi

For the query String : name=&city=
city : 
name :


Tuesday, 17 October 2017

Deserialize byte array to java object

In my previous post, I explained how to serialize an object to byte array. Below snippet is used to deserialize the byte array to java object.
        /* De serialize the byte array to object */
  private static Object getObject(byte[] byteArr) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
    ObjectInput in = new ObjectInputStream(bis);
    return in.readObject();
  }


Find the below working application.


Employee.java
package com.sample.model;

import java.io.Serializable;

public class Employee implements Serializable {

  private static final long serialVersionUID = 1L;
  private int id;
  private String name;
  private String country;

  public Employee(int id, String name, String country) {
    super();
    this.id = id;
    this.name = name;
    this.country = country;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  @Override
  public String toString() {
    return "Employee [id=" + id + ", name=" + name + ", country=" + country + "]";
  }

}


Test.java
package com.sample.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.sample.model.Employee;

public class Test {

  /* Serialize the object to byte array */
  private static byte[] getByteArray(Object obj) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
      os.writeObject(obj);
    }
    return bos.toByteArray();
  }

  /* De serialize the byte array to object */
  private static Object getObject(byte[] byteArr) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
    ObjectInput in = new ObjectInputStream(bis);
    return in.readObject();
  }

  public static void main(String args[]) throws IOException, ClassNotFoundException {
    Employee emp = new Employee(1, "Chamu", "India");

    byte[] serializedData = getByteArray(emp);

    Employee deserializedEmp = (Employee) getObject(serializedData);

    System.out.println("Deserialized Employee : " + deserializedEmp);
  }
}


Serialize the object to byte array

If java class implement Serializable interface, then you can use below snippet to get the byte array form of the object.

 private static byte[] getByteArray(Object obj) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
   os.writeObject(obj);
  }
  return bos.toByteArray();
 }

Employee.java
package com.sample.model;

import java.io.Serializable;

public class Employee implements Serializable {

 private static final long serialVersionUID = 1L;
 private int id;
 private String name;
 private String country;

 public Employee(int id, String name, String country) {
  super();
  this.id = id;
  this.name = name;
  this.country = country;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + ", country=" + country + "]";
 }

}

Test.java
package com.sample.serialize;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.sample.model.Employee;

public class Test {

 private static byte[] getByteArray(Object obj) throws IOException {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try (ObjectOutputStream os = new ObjectOutputStream(bos)) {
   os.writeObject(obj);
  }
  return bos.toByteArray();
 }

 public static void main(String args[]) throws IOException {
  Employee emp = new Employee(1, "Chamu", "India");

  byte[] serializedData = getByteArray(emp);

  for (byte b : serializedData) {
   System.out.print(b + ",");
  }
 }
}


Output

-84,-19,0,5,115,114,0,25,99,111,109,46,115,97,109,112,108,101,46,109,111,100,101,108,46,69,109,112,108,111,121,101,101,0,0,0,0,0,0,0,1,2,0,3,73,0,2,105,100,76,0,7,99,111,117,110,116,114,121,116,0,18,76,106,97,118,97,47,108,97,110,103,47,83,116,114,105,110,103,59,76,0,4,110,97,109,101,113,0,126,0,1,120,112,0,0,0,1,116,0,5,73,110,100,105,97,116,0,5,67,104,97,109,117,



Monday, 16 October 2017

Office URI Scheme

URI stands for Uniform Resource Identifier, used to uniquely identify a resource.

What is URI Scheme?
URI scheme tells how to interpret given URI.

MSOffice provides, office uri scheme, by using uri scheme commands, we can invoke office applications.

URI Scheme syntax
<scheme-name>:<command-name>"|"<command-argument-descriptor> "|"<command-argument>

Ex:
a. Below uri scheme opens the document presented in local file system.
Open run prompt and enter below url, if ms office is installed in your machine, it opens the document.
ms-word:ofv|u|file:///C:\Users\krishna\Documents\testDoc.docx

b. Below uri scheme opens the document presented in internet.
ms-word:ofv|u|http://sample.com/testDoc.docx

You can write a html file like below to open the file using office uri schema.

uriHandle.html
<!DOCTYPE html>
<html>
 <head>
  <title>Open Office URI</title>
  
  <script>
   function openURI() {
    var urlToLaunch = 'ms-word:ofv|u|file:///C:/Users/Krishna/Documents/testDoc.docx';
    if (navigator.msLaunchUri) {
     navigator.msLaunchUri(urlToLaunch);
    } else {
     var win = (window.parent) ? window.parent : window;
     win.location.assign(urlToLaunch);
    }
   }
  </script>

 </head>

 <body onLoad='openURI()'>
  <a href='ms-word:ofv|u|file:///C:\Users\Krishna\Documents\testDoc.docx'>ClickMe</a>
 </body>

</html>


Open above html file in browser. For example, I opened above file in chrome browser. Chrome browser prompts you with below kind of window, whether you want to open the file or not.

Click on the button ‘Open Word 2016’, it open the word document located in your machine.

Analyze the syntax of office uri scheme
<scheme-name>:<command-name>"|"<command-argument-descriptor> "|"<command-argument>

Token
Description
<scheme-name>
Scheme name specifies the office application to be invoked.

Ex:
         ms-word : Specifies office word application
         ms-powerpoint : Specifies the ppt application
:
Separate the uri scheme and commands
<command-name>
Specifies the action to be performed by the application.

Ex:
       ofe (Open for Edit): Open the document in edit mode
       ofv (Open for View): Open the document in view mode
       nft (New from template) : Create a file from given template
|
Separator
<command-argument-descriptor>
Add extra information about what the command argument is about.
|
Separator
<command-argument>
It vary depends on the command. For example, we can provide the uri (location of the document)

For ex: for the below uri scheme
ms-word:ofv|u|file:///C:/Users/krishna/Documents/testDoc.docx

<scheme-name> : ms-word
<command-name> : ofv
<command-argument-descriptor> : u

Compact form of Office Scheme
You can also use the compact form of office uri scheme.
<scheme-name>:<command-argument>

Ex
ms-word:file:///C:\Users\krishna\Documents\testDoc.docx

Above uri scheme open the document.

What are the uri schemes implemented as part of Microsoft Office applications?
When you install Microsoft Office, below uri schemes will be installed in your machine.

Below table summarizes the uri schemes comes as part of office installation.

URI Scheme
Description
ms-word
Office documents like .doc, .docx
ms-powerpoint
Power point (ppt) files
ms-excel
Excel sheet (xls, xlsx)
ms-visio
Visio files (.vsdx)
ms-access
Microsoft access files
ms-project
Microsoft project files
ms-publisher
Microsoft publisher application files (.pub)
ms-spd
Microsoft Sharepoint Designer files
ms-infopath
Info path forms

Is there any limitations in using uri scheme?
Yes, you should consider below limitations while using office uri scheme.

a.   File names must not contain following characters \ / : ? < > | " or *.
b.   The maximum command argument (path length) length is 256 characters, for xls files it is 216 characters.

Reference


You may like