Hello Everyone!!

In this blog ,I will discuss on some cool stuff that I developed last week !!

With the power HANA on cloud and the ability to connect devices, it has become possible to access and control device from remote.

Let’s have a use case where you are in your car on the way to office and suddenly you realize that you have an important file in your personal laptop that you need access.

To solve such problems we can take use of HANA to access to resources on your local system.

I will showcase the above by an application that shut down your laptop from SAPUI5 application running in your mobile.

The application functions as explained below:

1:-    When user press on Shutdown button in SAPUI5 application, the application reads the flag from          HANA using XSODATA intreface.

If the flag for shutdown is already set, application alerts system is already shutdown.

2:-   If the shutdown flag is not set ,application set the flag for shutting down the laptop

3:-   There is a java application running in your laptop that checks for the status of the flag after                  every fix interval of time.

4:-   If the flag is set ,the java application initiates system shutdown .

5:- Along with shutdown initialization, java application unset the flag in HANA system.

So now let’s code !!

Prerequisite:-

1:- You have a HANA trial account.

2:- You have created a MDC trial schema.

3:- You have java installed in your local system.

Step 1:-

Create HANAXS application:

A:-   Create a package in  HANAXS editor.

B:- Create a .xsaccess and .xsapp files in the folder

.xsaccess

{"exposed":true}

.xsapp

{}

C:- Create  shutStorage.hdbschema file

schema_name = "ShutStorage";

D:- Create a shut.hdbdd file

namespace shuttler;
@Schema: 'ShutStorage' 
context shut {
   
   Entity flagHolder{
       key id: Integer;
       flag:Integer;
   };
};

E:- Create a accessShuttler.xsodata file

service{
"shuttler::shut.flagHolder" as "flagHolder";
}

F:- Test the ODATA service by clicking on the run button. You will get a result like below in browser

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<service xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app" xml:base="https://jdatap1942288904trial.hanatrial.ondemand.com:443/shuttler/accessShuttler.xsodata/">
<workspace>
<atom:title>Default</atom:title>
<collection href="flagHolder">
<atom:title>flagHolder</atom:title>
</collection>
</workspace>
</service>

 

After Completing the above steps our HANAXS application is ready :).

Note: Create a row inside the table with entry 1 ,0 for id and flag respectively.

Step 2:- Create SAPUi5 application

A:- Open SAP Webide and create  SAPUI5 application.

File->New->Project from template -> SAPUI5 Application

B:- Open the neo-app.json file in the newly created project and add the lines with red mark as shown below

Note: – It is required that you have created  destination for the HANAXS system in cloud cockpit as shown below

C:- Add following code in the view file inside content tag

 <Button text="Shut Down SYSTEM" id="__button1" press="onShutDownPress"/>

D:- Add the following code in your controller.js file

 

onShutDownPress: function () {
  //var oModel=this.getView().getModel("sales");
 // console.log(oModel);
 
  var oModel = new sap.ui.model.odata.ODataModel("/HANAXS/shuttler/accessShuttler.xsodata");
 oModel.setUseBatch(false);
  oModel.read("/flagHolder(1)", null, null, true, jQuery.proxy(function(data) {
  	console.log(data.flag);
 if(data.flag=="0")
 {
 	var oEntry = {};
oEntry.flag = "1";
oModel.update('/flagHolder(1)', oEntry, null, function(){
 		alert("Update successful");
 	},function(){
		alert("Update failed");});
 
 	
 	
 }
 else
 {
 	
 	alert("Your system is already shut down");
 }
  }));
		}


Test the ui5 application by clicking on the Shut down system button

Bingo!! Your UI5 application is ready

Step 3:- Create a java application in your local system

Check that java is installed in your local system.
(I am working on writing the code in pure OS command based eliminating the dependency of java.
Till then you have to bare with this .
)

A: Open any editor (notepad,notepad++ etc) and paste the following code
(Note:- Change the URL of HANAXS odata  accordingly)

import org.apache.commons.codec.binary.Base64;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class ShutProcessor {
	private final String USER_AGENT = "Mozilla/5.0";
	public static void main(String[] args)  {
		try{
	
		
		
			
			 Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
		try{
        ShutProcessor sP=new ShutProcessor();
        	sP.sendGet();
		}catch(Exception e){}
	}

}, 0, 50000);
		
	
		//System.out.println("Using proxy: " + host + ":" + port);
		//String shutdownCmd = "shutdown -s";
		//	Process child = Runtime.getRuntime().exec(shutdownCmd);
		}
		catch(Exception e)
		{
			System.out.println("error"+e.getLocalizedMessage());
			e.printStackTrace();
		}
		
		
	}
	private void sendPut(URL obj) throws Exception
	{
		String url = "https://jdatap1942288904trial.hanatrial.ondemand.com/shuttler/accessShuttler.xsodata/flagHolder(1)";
		System.out.println("\nSending 'PUT' request to URL : " + url);
		URL obj1 = new URL(url);
		String req="<a:entry xmlns:a="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"><a:author><a:name/></a:author><a:content type="application/xml"><m:properties><d:flag>0</d:flag></m:properties></a:content></a:entry>";
		HttpURLConnection con = setUsernamePassword(obj1);
		
		con.setRequestProperty("Content-Type", "application/atom+xml");
		con.setRequestProperty("Content-Length", Integer.toString(req.getBytes().length));
		con.setRequestProperty("Accept", "application/atom+xml,application/atomsvc+xml,application/xml");
		con.setRequestProperty("Content-Type", "application/atom+xml");
		con.setDoOutput(true);
		con.setRequestMethod("PUT");
		OutputStreamWriter out = new OutputStreamWriter(
    con.getOutputStream());
out.write(req);
out.close();
BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
System.out.println(response.toString());
	}
	private void sendGet() throws Exception {
 
		String url = "https://jdatap1942288904trial.hanatrial.ondemand.com//shuttler/accessShuttler.xsodata/flagHolder(1)/flag?$format=json";
	
		URL obj = new URL(url);
		HttpURLConnection con = setUsernamePassword(obj);;
		
		
		// optional default is GET
		con.setRequestMethod("GET");
		
		//add request header
		con.setRequestProperty("User-Agent", USER_AGENT);
		
		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		

		JSONArray jsonArray = new JSONArray("["+response.toString()+"]");
System.out.println(jsonArray);
		JSONObject rec = new JSONObject(response.toString());
String flg = rec.getJSONObject("d").getString("flag");

if(flg.equalsIgnoreCase("1"))
	 {       this.sendPut(obj);       
		    String shutdownCmd = "shutdown -s";
			Process child = Runtime.getRuntime().exec(shutdownCmd);
	 }	 
    
	

	}
	 private HttpURLConnection setUsernamePassword(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        String authString = "<HANA_Instance_username>" + ":" + "<HANA_Instance_password>";
        String authStringEnc = new String(Base64.encodeBase64(authString.getBytes()));
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        return urlConnection;
    }
}

B:- Compile the program using the javac command.

C:- Run the program using java command.

D:- Create a shutProcess.bat file and include the java commands in the file.

E:- Include the bat file in the startup programs so that it runs as soon as the system starts

for help to run bat file at startup click here

Note: The java program make use of following jar files .You need to download them and add to your class path for the application to work properly.

commons-codec-1.10.jar

java-json.jar

Bingo!! Your application is ready. Now just press the shutdown system  button from your application and your laptop will shutdown !!

If you have any suggestions to improve or add to the application do suggest 🙂

 

To report this post you need to login first.

4 Comments

You must be Logged on to comment or reply to a post.

  1. Krunal Patel

    Hey mate ,

    nice blog .
    hv a small query. You mentioned that for local system a Java program needs to be implemented and compile through Javac command. So is there any java version dependency ? Or we can use any of the  Java version i.e 6 ,7 or 8 ?

    thank u 🙂

    (1) 
    1. Jatin Dharani Post author

      Hi Krunal,

      Greetings!!

      I have developed and tested the application on java 1.8 version.

      However the application should run smoothly  on java version 1.5 and higher.

      (0) 
  2. Jelena Perfiljeva

    So “you realize that you have an important file in your personal laptop that you need access” and then you decide… to shutdown the laptop? Doesn’t make sense IMHO. And if you had files you’d need to access on multiple devices why not just store them on Dropbox or something?

    Interesting idea, maybe just not the best choice of a use case. Anyways, thanks for sharing!

    (1) 
    1. Jatin Dharani Post author

      Hello Jelena,

      Thanks for your feedback !!

      The use case I have mentioned is a kind of “Getting started”  use case on the idea on connecting your on premise stuff with cloud and controlling them from mobile.

      If for the above use case we replace personal laptop with an on premise server and the file with error log files , we get a very useful “remote server administration” use case.Of course when dealing with server we have to add extra security.

      On the same idea , I am in development  phase of another use case and will be blogging soon on that 🙂

      (0) 

Leave a Reply