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

Adding headers using HttpURLConnection

HttpURLConnection class provides 'setRequestProperty' method to set the headers.

Below step-by-step procedure explains how to set headers.

Step 1: Get HttpURLConnection object
                 URL url = new URL(urlToConnect);
                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();

Step 2: Add headers to the HttpURLConnection using setRequestProperty method.
                 Map<String, String> headers = new HashMap<>();

                 headers.put("X-CSRF-Token", "fetch");
                 headers.put("content-type", "application/json");
                
                 for (String headerKey : headers.keySet()) {
                          httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
                 }
                
Find below working application.

Test.java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

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 void setHeaders(HttpURLConnection httpUrlConnection, Map<String, String> headers) {
  for (String headerKey : headers.keySet()) {
   httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
  }
 }

 public static void main(String[] args) throws IOException {
  String url = "urlToConnect";
  HttpURLConnection httpUrlConnection = getURLConnection(url);

  Map<String, String> headers = new HashMap<>();

  headers.put("X-CSRF-Token", "fetch");
  headers.put("content-type", "application/json");

  setHeaders(httpUrlConnection, headers);
  httpUrlConnection.getContent();

 }

}



Previous                                                 Next                                                 Home

Get headers from url using HttpURLConnection

Below step by step procedure explains, how to get all headers from http url.

Step 1: Get HttpURLConnection instance from url.
                 URL url = new URL(urlToConnect);
                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
                 return httpUrlConnection;
                
Step 2: Use 'getHeaderFields' method of HttpURLConnection instance to get all the headers.
                 Map<String, List<String>> headers = httpURLConnection.getHeaderFields();

                 for (String headerName : headers.keySet()) {
                          System.out.println(headerName + " : " + headers.get(headerName));
                 }
                
Find below working application.

Test.java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

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 void printHeaders(HttpURLConnection httpURLConnection) {
  Map<String, List<String>> headers = httpURLConnection.getHeaderFields();

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

 public static void main(String[] args) throws IOException {
  String url = "https://self-learning-java-tutorial.blogspot.com/2016/05/java-home-page.html";
  HttpURLConnection httpUrlConnection = getURLConnection(url);
  printHeaders(httpUrlConnection);

 }

}


Output
Transfer-Encoding : [chunked]
null : [HTTP/1.1 200 OK]
Alt-Svc : [quic=":443"; ma=2592000; v="39,38,37,35"]
Server : [GSE]
X-Content-Type-Options : [nosniff]
Last-Modified : [Thu, 31 Aug 2017 17:49:01 GMT]
Date : [Fri, 01 Sep 2017 09:50:33 GMT]
Accept-Ranges : [none]
Cache-Control : [private, max-age=0]
Vary : [Accept-Encoding]
Expires : [Fri, 01 Sep 2017 09:50:33 GMT]
X-XSS-Protection : [1; mode=block]
Content-Type : [text/html; charset=UTF-8]



Previous                                                 Next                                                 Home