Friday, 15 September 2017

Convert json string to map

Below program converts json string to a map. This program runs only for primitive types. If json string has complex types like array, nested json objects, it will not work.

Test.java
import java.util.LinkedHashMap;
import java.util.Map;

public class Test {

 public static Map<String, String> getMapFromString(String s) {
  if (s == null || s.isEmpty()) {
   return new LinkedHashMap<>();
  }

  Map<String, String> map = new LinkedHashMap<>();

  String[] tokens = s.split(",");

  for (int i = 0; i < tokens.length; i++) {
   tokens[i] = tokens[i].replace("\"", "");
   tokens[i] = tokens[i].replace("{", "");
   tokens[i] = tokens[i].replace("}", "");
   String[] subparts = tokens[i].split(":");

   if (subparts.length == 2) {
    map.put(subparts[0], subparts[1]);
   } else {
    map.put(subparts[0], "");

   }

  }

  return map;
 }

 public static void main(String args[]) {

  String json = "{\"id\":\"123456\",\"changeToken\":\"token-1234\",\"headerText\":\"\"}";

  Map<String, String> map = getMapFromString(json);

  for (String key : map.keySet()) {
   System.out.println(key + " : " + map.get(key));
  }
 }
}

Output
id : 123456
changeToken : token-1234
headerText :

If you would like to convert complex json string to map, I would suggest you to use libraries like gson, Jackson, genson etc.,



You may like




ABAP: Defining variables using colon notation

In my previous post, I explained how to define variables. By using colon notation, you can define multiple variable in one shot.

Example
DATA: first_name TYPE STRING,
      last_name TYPE STRING,
      age TYPE I.

Z_HELLO_WORLD
*&---------------------------------------------------------------------*
*& Report Z_HELLO_WORLD
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT Z_HELLO_WORLD.

* Defining Variables
DATA: first_name TYPE STRING,
      last_name TYPE STRING,
      age TYPE I.

first_name = 'Hari Krishna'.
last_name = 'Gurram'.
age = 28.

Write first_name.
Write / last_name.
Write / age.



Previous                                                 Next                                                 Home

Monday, 11 September 2017

ABAP: Variables

Variable is a named memory location used to store a value. Every variable in ABAP must have a type.

How to define a variable?
DATA variable_name TYPE type_name VALUE value_of_the_variable.

                 (OR)
                
DATA variable_name TYPE type_name.
variable_name = value.

Z_HELLO_WORLD
*&---------------------------------------------------------------------*
*& Report Z_HELLO_WORLD
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT Z_HELLO_WORLD.

* Defining Variables
DATA char_var1 TYPE C.
char_var1 = 'a'.

DATA char_var2 TYPE C VALUE 'b'.

Write char_var1.
Write / char_var2.


Note

The name of the variable can be up to 30 characters long

Previous                                                 Next                                                 Home

Implement LRU cache using LinkedHashMap

By default LinkedHashMap stores elements in the order they inserted. LinkedHaspMap provides one special constructor, that is used to get the elements of LinkedHashMap in their access order, that is from least-recently accessed to most-recently access-order.

public LinkedHashMap(int initialCapacity, float loadFactor,boolean accessOrder)
Above constructor is used to define a access-order linked hash map. If the argument 'accessOrder' is true, then it constructs linked hash map using access order of the keys, else insertion order of the keys.

Example
Map<Integer, String> map = new LinkedHashMap<>(10, 0.75f, true);

By overridding the method ‘removeEldestEntry’ of LinkedHashMap class, you can use LinkedHashMap as LRU cache.

private static final int MAX_ENTRIES = 5;

@Override
protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
         return size() > MAX_ENTRIES;
}

Above override allow the map to grow up to 5 entries and then delete the eldest entry each time a new entry is added, maintaining a steady state of 100 entries. If the map is an access-ordered map, eldest entry is the least recently accessed entry. If map is not an access-ordered map, eldest entry is the least recently inserted entry.

Find the complete working application.

Test.java
import java.util.LinkedHashMap;
import java.util.Map;

public class Test {

 private static Map<Integer, String> getLRUMap() {
  return new LinkedHashMap<Integer, String>(2, (float) 0.75, true) {
   private static final long serialVersionUID = 1L;
   private static final int MAX_ENTRIES = 5;

   @Override
   protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) {
    return size() > MAX_ENTRIES;
   }
  };
 }

 private static void printMap(Map<Integer, String> map) {

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

 }

 public static void main(String args[]) {
  Map<Integer, String> map = getLRUMap();

  map.put(1, "Krishna");
  map.put(2, "Hari");
  map.put(3, "Ram");
  map.put(4, "Joel");
  map.put(5, "Kiran");

  printMap(map);

  System.out.println("Accessing the keys 1, 2, 5");

  map.get(1);
  map.get(5);
  map.get(2);

  System.out.println("Inserting the key 6");

  map.put(6, "Naveen");
  printMap(map);

 }
}

Output
***************************************
1 : Krishna
2 : Hari
3 : Ram
4 : Joel
5 : Kiran
***************************************
Accessing the keys 1, 2, 5
Inserting the key 6

***************************************
4 : Joel
1 : Krishna
5 : Kiran
2 : Hari
6 : Naveen
***************************************

As you observe above output, initially map has 1, 2, 3, 4, 5 keys.  After that I accessed 1, 2, 5 keys. When I tried to insert the key 6, it removes the key 3 (Since 3 is the least recently used key) and add the key 6.

You may like



Friday, 8 September 2017

Get elements of LinkedHashMap by access order?

By default LinkedHashMap stores elements in the order they inserted. LinkedHaspMap provides a constructor, that is used to get the elements of LinkedHashMap in their access order, that is from least-recently accessed to most-recently (access-order).

public LinkedHashMap(int initialCapacity, float loadFactor,boolean accessOrder)
Above constructor is used to define a access-order linked hash map. If the argument 'accessOrder' is true, then it constructs linked hash map using access order of the keys, else insertion order of the keys.

Example
Map<Integer, String> map = new LinkedHashMap<>(10, 0.75f, true);

Test.java
import java.util.LinkedHashMap;
import java.util.Map;

public class Test {

 private static void printMap(Map<Integer, String> map) {

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

 }

 public static void main(String args[]) {
  Map<Integer, String> map = new LinkedHashMap<>(10, 0.75f, true);

  map.put(1, "Krishna");
  map.put(2, "Hari");
  map.put(3, "Ram");
  map.put(4, "Joel");

  printMap(map);

  System.out.println("\nAccessing the key 1");
  map.get(1);

  printMap(map);

  System.out.println("\nAccessing the key 3");
  map.get(3);
  printMap(map);

 }
}


Output
***************************************
1 : Krishna
2 : Hari
3 : Ram
4 : Joel
***************************************

Accessing the key 1

***************************************
2 : Hari
3 : Ram
4 : Joel
1 : Krishna
***************************************

Accessing the key 3

***************************************
2 : Hari
4 : Joel
1 : Krishna
3 : Ram
***************************************

After inserting the elements, those are maintained in same order.

1 : Krishna
2 : Hari
3 : Ram
4 : Joel

After accessing the key '1' from linked hashmap.
2 : Hari
3 : Ram
4 : Joel
1 : Krishna

After accessing the key '3'.

2 : Hari
4 : Joel
1 : Krishna

3 : Ram

You may like



Wednesday, 6 September 2017

ABAP: Data Types

Data type is used to specify the type of data that a variable can hold. ABAP offers both fixed and variable length data types.

Below table summarizes the basic data types in ABAP.

Keyword
Description
Default Length
Default Value
C
Character
1 character
''
N
Numeric text field
1 character
0
D
Character like Date
8 characters
00000000
T
Character like Time
6 characters
000000
X
Hexa Decimal
1 byte
X'0'
I
Integer
4 bytes
0
P
Packed
8 bytes
0
F
Float
8 bytes
0
STRING
Alpha numeric string
Variable length

XSTRING
Represents byte string
Variable length


Z_HELLO_WORLD
*&---------------------------------------------------------------------*
*& Report Z_HELLO_WORLD
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT Z_HELLO_WORLD.

* Defining Variables
DATA char_var TYPE C.
char_var = 'a'.

DATA numeric_var TYPE N.
numeric_var = 5.

DATA date_var TYPE D.
date_var = SY-DATUM.

DATA hexa_var TYPE x.
hexa_var = '5'.

DATA int_var TYPE I.
int_var = 12345.

DATA packed_var TYPE P.
packed_var = 12345.

DATA float_var TYPE F.
float_var = 1200.

DATA string_var TYPE STRING.
string_var = 'Hello World'.

DATA xstring_var TYPE XSTRING.
xstring_var = 'Hello World'.

Write char_var.
Write / numeric_var.
Write / date_var.
Write / hexa_var.
Write / int_var.
Write / packed_var.
Write / float_var.
Write / string_var.
Write / xstring_var.


Output

Write / numeric_var.
/ is used to print the output in next line.

Previous                                                 Next                                                 Home

Sunday, 3 September 2017

Post data to url using HttpURLConnection

By writing to HttpURLConnection output stream, you can send post data to http url.

Below step-by-step procedure explains how to post the data.

Step 1: Get HttpURLConnection instance.
                 URL url = new URL(urlToConnect);
                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
                
Step 2: Set the request method (POST, PUT etc.,) and other request headers.
                 httpUrlConnection.setRequestMethod(method);
                 httpUrlConnection.setDoOutput(true);
                 httpUrlConnection.setRequestProperty("Content-Type", requestContentType);

Step 3: Write the data to HttpUrlConnection output stream. After writing the data flush and close the stream.
                 OutputStreamWriter writer = new OutputStreamWriter(httpUrlConnection.getOutputStream());
                 writer.append(content);
                 writer.flush();
                 writer.close();
                
Step 4: Get the content stream.
                 int responseCode = httpUrlConnection.getResponseCode();
                 InputStream inputStream = null;

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

Step 5: Print the stream to console.
                 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

                 String line = null;

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

Find below working application.


Test.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

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 HttpURLConnection writeContentTo(String urlToWrite, String content, String requestContentType,
   String method) throws IOException {
  HttpURLConnection httpUrlConnection = getURLConnection(urlToWrite);

  httpUrlConnection.setRequestMethod(method);
  httpUrlConnection.setDoOutput(true);
  httpUrlConnection.setRequestProperty("Content-Type", requestContentType);
  OutputStreamWriter writer = new OutputStreamWriter(httpUrlConnection.getOutputStream());
  writer.append(content);
  writer.flush();
  writer.close();

  return httpUrlConnection;
 }

 private static InputStream getContentStream(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 url = "urlToWrite";
  String method = "POST";
  String content = "{\"id\" : \"krishna\", \"logonId\" : \"hari\"}"; //you can write any content
  String requestContentType = "application/json";

  HttpURLConnection httpUrlConnection = writeContentTo(url, content, requestContentType, method);
  InputStream inputStream = getContentStream(httpUrlConnection);
  
  printInputStream(inputStream);
  
 }

}


Previous                                                 Next                                                 Home