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

Thursday, 12 October 2017

Basic authentication using HttpURLConnection

Below statements are used to perform basic authentication.

HttpURLConnection httpUrlConnection = getURLConnection(url);
Encoder encoder = Base64.getEncoder();
String encoded = encoder.encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8));
httpUrlConnection.setRequestProperty("Authorization", "Basic " + encoded);

Find the below working application.

Test.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Base64.Encoder;

public class Test {

 private static HttpURLConnection getURLConnection(String urlToConnect) throws IOException {
  URL url = new URL(urlToConnect);
  HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
  return httpUrlConnection;
 }

 private static InputStream getContent(HttpURLConnection httpUrlConnection) throws IOException {
  int responseCode = httpUrlConnection.getResponseCode();
  InputStream inputStream = null;

  if (responseCode >= 200 && responseCode < 400) {
   inputStream = httpUrlConnection.getInputStream();
  } else {
   inputStream = httpUrlConnection.getErrorStream();
  }

  return inputStream;
 }

 private static void printInputStream(InputStream inputStream) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

  String line = null;

  while ((line = br.readLine()) != null) {
   System.out.println(line);
  }
 }

 public static void main(String[] args) throws IOException {
  String userName = "";
  String password = "";

  String url = "";

  HttpURLConnection httpUrlConnection = getURLConnection(url);
  Encoder encoder = Base64.getEncoder();
  String encoded = encoder.encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8));
  httpUrlConnection.setRequestProperty("Authorization", "Basic " + encoded);

  InputStream inputStream = getContent(httpUrlConnection);
  printInputStream(inputStream);

 }

}


Previous                                                 Next                                                 Home

Wednesday, 11 October 2017

ABAP: Class Builder

Classes are the enhanced version of function modules. ABAP classes support object oriented principles.

ABAP GUI provides 'Class Builder' user interface to build the classes. Use the transaction code 'SE24' to open the 'Class Builder' user interface.

Below step-by-step procedure explains how to define class.

Step 1: Use the transaction ‘SE24’ to open class builder.


Step 2: Give the class name as ZCL_EMPLOYEE. ‘CL’ stands for class, it is just a naming convention.
Click on ‘Create’ button.

It opens below window.

Give the description as ‘Model class to represent employee information’.
Click on ‘Save’ button.

It opens below window.
Click on the button ‘Local Object’.

It opens below window.
Activate the class ZCL_EMPLOYEE.

It opens below window.
Select all the object and activate them.

Step 3: Define constructor to the class ZCL_EMPLOYEE.

Click on the tab ‘Methods’, give the Mehtod name as ‘CONSTRUCTOR’ and press Enter. Change the access from private to public.
Next click on the tab ‘parameters’.

Define the parameters ID, FIRST_NAME, and LAST_NAME.
Save the changes.

Now click on the tab ‘METHODS’. Double click on the method CONSTRUCTOR.
After double click, it opens below window.
Update the constructor definition like below.

  method CONSTRUCTOR.
    _id = ID.
    _first_name = FIRST_NAME.
    _last_name = LAST_NAME.
  endmethod.
Save the source code.

Go back and click on ‘Attributes’ tab.
Define the attributes _id, _first_name and _last_name.

Set the Level as ‘Instance Attribute’, Visibility to Private and Type to STRING.
Save the program and activate the application.

It opens below window, select all the press Ok button.
Click on the button ‘Source Code-Based’
You can able to see the source code of ZCL_EMPLOYEE.
Below one is the source code.

Z_CL_EMPLOYEE
class ZCL_EMPLOYEE definition
  public
  final
  create public .

public section.

  methods CONSTRUCTOR
    importing
      !ID type STRING
      !FIRST_NAME type STRING
      !LAST_NAME type STRING .
protected section.
private section.

  data _ID type STRING .
  data _FIRST_NAME type STRING .
  data _LAST_NAME type STRING .
ENDCLASS.



CLASS ZCL_EMPLOYEE IMPLEMENTATION.


* <SIGNATURE>---------------------------------------------------------------------------------------+
* | Instance Public Method ZCL_EMPLOYEE->CONSTRUCTOR
* +-------------------------------------------------------------------------------------------------+
* | [--->] ID                             TYPE        STRING
* | [--->] FIRST_NAME                     TYPE        STRING
* | [--->] LAST_NAME                      TYPE        STRING
* +--------------------------------------------------------------------------------------</SIGNATURE>
  method CONSTRUCTOR.
    _id = ID.
    _first_name = FIRST_NAME.
    _last_name = LAST_NAME.
  endmethod.
ENDCLASS.



Previous                                                 Next                                                 Home

Initialize list in one line

In this post, I am going to show you, how to define a list in one line.

In general, we create an instance of ArrayList class and call the add method to add new elements to the array list.
  List<String> countries = new ArrayList<>();

  countries.add("India");
  countries.add("Germany");
  countries.add("Canada");
  countries.add("Singapore");

There are other ways to define array list in one line.
         a. By using Arrays.asList method
         b. By using List.of method
         c. By using Double Brace Initialization
         d. By using streams
         e. By using Collections.singletonList


By using Arrays.asList method
List<String> countries = Arrays.asList("India", "Germany", "Canada", "Singapore");
                                  (or)
String arr[] = {"India", "Germany", "Canada", "Singapore"};
List<String> countries = Arrays.asList(arr);


By using List.of method
From Java9 onwards List interface provides 'of' method to define list.
List<String> strings = List.of("India", "Germany", "Canada", "Singapore");

By using Double Brace Initialization
  List<String> countries = new ArrayList<String>() {
   {
    add("India");
    add("Germany");
    add("Canada");
    add("Singapore");
   }
  };

By using streams
Streams are available from Java8.
List<String> places = Stream.of("India", "Germany", "Canada", "Singapore").collect(Collectors.toList());


By using Collections.singletonList
If your list has only one element, then you can use singletonList.
List<String> country = Collections.singletonList("India");