Sunday, 3 September 2017

Read URL Contents using HttpURLConnection

Follow below steps to read the contents from an url.

Step 1: Create a connection to the url.
                 URL url = new URL(urlToConnect);
                 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
                
Step 2: Create input stream from the url connection.

                 int responseCode = httpUrlConnection.getResponseCode();
                 InputStream inputStream = null;

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

Step 3: Read the content from input stream and print them 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.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 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 url = "https://self-learning-java-tutorial.blogspot.com/2016/05/java-home-page.html";
  HttpURLConnection httpUrlConnection = getURLConnection(url);
  InputStream inputStream = getContent(httpUrlConnection);
  printInputStream(inputStream);

 }

}



Previous                                                 Next                                                 Home

Working with HttpURLConnection class

HttpURLConnection class is used to establish a connection to http end points. By using HttpURLConnection class, you can open a connection to given http end point, read the content, write content, read and write headers, read response status codes etc., In this tutorial series, you will get hands on of all these things.

·       Read URL Contents using HttpURLConnection
·       Get headers from url using HttpURLConnection
·       Adding headers using HttpURLConnection
·       Post data to url using HttpURLConnection



Previous                                                 Next                                                 Home

Saturday, 2 September 2017

ABAP: Comments

Comments are used to document the ABAP application. There are two kinds of comments.

a.   Full line comments
b.   Partial line comments

Full line comments
Full line comments are start with *.

Example
* I used to document the code.

ZHELLO_WORLD
*---------------------------------------------------------------------
* Report zhello_world
*---------------------------------------------------------------------
*
*---------------------------------------------------------------------

REPORT zhello_world.

Write: 'Hello World'.

Partial line comments
Partial line comments starts with " (Double quote).


ZHELLO_WORLD
*---------------------------------------------------------------------
* Report zhello_world
*---------------------------------------------------------------------
*
*---------------------------------------------------------------------

REPORT zhello_world.

Write: 'Hello World'. "I am partial line comment




Previous                                                 Next                                                 Home

Friday, 1 September 2017

ABAP: Statements

Every statement in ABAP starts with ABAP keyword and ends with a '.'.

If your program is an executable, then the first non-comment line should be 'REPORT REPORT_NAME'. If your program is not executable, then the first non-comment line should be 'PROGRAM PROGRAM_NAME'.

ZHELLO_WORLD
*&---------------------------------------------------------------------*
*& Report zhello_world
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zhello_world.

Write 'Hello World'.

Colon Notation
If the statements are identical, then consecutive statements can be chained using : notation.

Write 'Hello'.
Write 'Good'.
Write 'Morning'.

Above statements can be chained like below.

Write: 'Hello', 'Good', 'Morning'.


ZHELLO_WORLD
*&---------------------------------------------------------------------*
*& Report zhello_world
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zhello_world.

Write: 'Hello', 'Good', 'Morning'.



Previous                                                 Next                                                 Home

ABAP Editor : Hello World Program

ABAP Editor is used to create, edit and run the programs.

How to open ABAP Editor?
By navigating through the Folder structure on SAP Easy Access Pane (or) by entering the transaction ‘SE38’ in command field.

Navigating through folder structure.
Tools -> ABAP Workbench -> Development -> ABAP Editor

By using transaction technical name
You can open ABAP Editor by entering the transaction technical name ‘SE38’ in the command field.
Since we are going to use ABAP editor throughout the tutorial, add this as favorite. I already explained in my previous post ‘How to add a Favorite?’.

On you entered the transaction ‘SE38’ in command window, it opens the window like below.

Below image summarizes the important sections of ABAP Editor

Create Hello World Program
Enter the name of the program as ‘Z_HELLO_WORLD’ and press Create button.
All the custom programs must start with the letter ‘Z’ (or) ‘Y’.
Once you press ‘Create’ button, it opens below window.  Give some meaningful title to the application and select the type as ‘Executable Program’ and press Save button.

Once you press the Save button, it opens below window.
Click the ‘Local Object’. It opens the Editor.

As you see, by default program is in Inactive state. Update the program like below.

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

Write 'Hello World'.

Save the program by using CTRL + S. Activate the program and run the program.
First check the program for any syntax errors. If there are no syntax error, you will get ‘No Syntax Errors found’ message at the bottom of the window.
Now activate the program by clicking Activate button.
Now you can run the program. Once you run the program, you can able to see below window.
As you observe the title we had given is displayed in the title bar of the window and the content of Write statement is displayed in body of the window.

That’s it. You are done with the first steps of ABAP Programming. It is time to explore more about ABAP syntax.
Previous                                                 Next                                                 Home

Thursday, 31 August 2017

ABAP Workbench Development Tools

ABAP Workbench tools are primarily categorized into two.
a.   Development Tools
b.   Analysis Tools

In this tutorial series, our main focus is on developing ABAP programs using ABAP development tools.

There are many Development tools provided by ABAP workbench, but most of the times, you do not require all of them. Below list summarizes most frequent and important tools used by the developers while working with ABAP Applications.

a.   ABAP Editor: Used to create, edit and run the programs
b.   Screen Painter: Used to develop the screens
c.   Web Dynpro Explorer: To build Web Applications
d.    ABAP Dictionary: To manage databases
e.   Function Builder: To build function modules
f.    Class Builder: To maintain classes
g.   Gate way Service Builder: To publish web services
h.   Enhancement Framework: To enhance SAP modules.



Previous                                                 Next                                                 Home

Wednesday, 30 August 2017

JAX-RS: getClasses vs getSingletons

In my previous post, I explained, how to configure your rest resources by extending ‘javax.ws.rs.core.Application’ class.

‘javax.ws.rs.core.Application’ class provides getClasses and getSingletons methods.

If you define any resource in getClasses method, it creates a new instance for each new request. Whereas if you define any resource in getSingletons method, it creates single instance of the resource and reuse the resource for all the requests.

Let’s see it by an example.

Step 1: Create new dynamic web project ‘app’ in eclipse.

Right click on ‘Project Explorer’ -> New -> Dynamic Web Project

Give the project name as ‘app’ and press Next.

In Java window, press Next.

In Web Module window, select the check box ‘Generate web.xml deployment descriptor’, press Finish.

Step 2: Mavenize the project.

Right click on the project ‘app’ -> Configure -> Convert To Maven Project.
It opens ‘Maven POM’ window, use the defaults and press the button Finish.

I am using below maven dependencies.
       <dependencies>
  <dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.25.1</version>
  </dependency>

  <dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-server</artifactId>
   <version>2.25.1</version>
  </dependency>

  <dependency>
   <groupId>org.glassfish.jersey.media</groupId>
   <artifactId>jersey-media-moxy</artifactId>
   <version>2.25.1</version>
  </dependency>
 </dependencies>

Step 3: Create a package ‘com.sample.resources’ and define HelloWorldSingletonResource, HelloWorldResource classes like below.


HelloWorldSingletonResource.java
package com.sample.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("HelloWorldSingletonResource")
public class HelloWorldSingletonResource {

 private static int count = 0;

 public HelloWorldSingletonResource() {
  count++;
 }

 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String hello() {
  return "Hello called " + count + " times";
 }

}

HelloWorldResource.java
package com.sample.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("HelloWorldResource")
public class HelloWorldResource {
 private static int count = 0;

 public HelloWorldResource() {
  count++;
 }

 @GET
 @Produces(MediaType.TEXT_PLAIN)
 public String hello() {
  return "HelloWorldResource called " + count + " times";
 }

}

Step 4: Create a package 'com.sample.rest' and define RestApplication like below.

RestApplication.java
package com.sample.rest;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import com.sample.resources.HelloWorldResource;
import com.sample.resources.HelloWorldSingletonResource;

public class RestApplication extends Application {

 @Override
 public Set<Class<?>> getClasses() {
  Set<Class<?>> s = new HashSet<Class<?>>();
  s.add(HelloWorldResource.class);
  return s;
 }

 public Set<Object> getSingletons() {
  Set<Object> set = new HashSet<>();
  HelloWorldSingletonResource resource = new HelloWorldSingletonResource();
  set.add(resource);
  return set;
 }
}


Step 5: Define web.xml like below.


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>jersey_tutorial</display-name>

 <servlet>
  <servlet-name>Jersey REST Service</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

  <init-param>
   <param-name>javax.ws.rs.Application</param-name>
   <param-value>com.sample.rest.RestApplication</param-value>
  </init-param>

  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>Jersey REST Service</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>


Complete project structure looks like below.

Run the application on server. Right click on the project ‘app’ -> Run As -> Run on Server.

If you do not know, hot to configure server in eclipse, you can go through my below post.

Once the application run on server, hit below url.


Re hit the same url.
You can see that the counter is getting increased, whenever you hit the url.

Now hit the url, http://localhost:8080/app/HelloWorldSingletonResource, try to hit the url as many times you want, the counter will not increase.






Previous                                                 Next                                                 Home