Thursday, 10 December 2015

Using SQL developer for connecting to DB2 database

Background


To execute queries on IBM DB2 we can use IBM data studio . But if you are already user of SQL developer (using oracle DB) then you can use the same for connecting and executing to DB2 queries. In this post we will see how can we do that.


Using SQL developer for connecting to DB2 database


1. Download the JDBC driver for DB2 (click here). It will be something like db2cc4-4.18.60.jar.

2. Next go to your SQL developer. Go to Tools -> Preferences -> Databases -> Third party JDBC drivers and click on "Add Entry". Next select the driver jar you downloaded in step 1.



3. Next go to New (Ctrl + N) and select database connection. Provide details about your connection. Don't forget to select database type as DB2 rather than oracle (see screenshot) and provide your db details.





4. You can test your connection and save or connect to it. After this you should be good to execute queries on your DB2 database from SQL developer.

NOTE :  Your database connection are stored by SQL developer in location - C:\Users\athakur\AppData\Roaming\SQL Developer\system3.0.04.34\o.jdeveloper.db.connection.11.1.1.4.37.59.31\connections.xml
Instead of athakur on the path it will be your username.

Saturday, 5 December 2015

Declare variables in PL/SQL

Background

In this post we will see how to declare and initialize variables in PL/SQL block.

Syntax

General syntax to declare variable in PL/SQL is
var_nm datatype [NOT NULL := var_value ];
  • var_nn is the name of the variable.
  • datatype is a valid PL/SQL datatype.
  • NOT NULL is an optional specification on the variable which this variable cannot be assigned null value.
  • var_value or DEFAULT value is also an optional specification, where you can initialize a variable with some specific value.
  • Each variable declaration is a separate statement and must be terminated by a semicolon.
We can assign value to variables in one of the following two ways -
  1. direct assignment (Eg. var_nm:= var_value;)
  2. Using select from (Eg. SELECT col_nm INTO var_nm FROM tbl_nm [WHERE clause];)

 Usage Examples

keeping above syntax in mind you can define variables as follows -


DECLARE 
 id number; 
BEGIN
 SELECT 1000 into id from dual;
 dbms_output.put_line('id : '|| id ); 
END; 
/
OR
DECLARE 
 id number := 1000; 
BEGIN
 dbms_output.put_line('id : '|| id ); 
END; 
/

Sunday, 15 November 2015

Create your own chrome plugin example demo

Background

In this post we will see how to create chrome plugins. We will see a simple demo plugin example in which when we click on the plugin icon we will will see the URL of current active TAB.


Getting Started

Create a directory where you will create files needed for your plugin. Lets call it "chrome_plugin" directory. 
  • First and foremost what you need is a file called manifest.json. This file essentially tell chrome browser details about your plugin like it's name, it's version, what permission it needs and the actual code files.

For our demo this file looks something like below -

{

  "manifest_version": 2,
  "name": "Open Source For Geeks Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },

  "permissions": [
   "activeTab"
   ]

} 


Contents of manifest.json file are basically json with plugin details. As you must have notices by now it references two essential resources -
  1. icon.png
  2. popup.html
  • Go ahead and put icon.png and create a file called popup.html is the same directory - "chrome_plugin".




 If you do not have the icon you can use the one above. It's 20*20 pixels icon.

  • Next edit popup.html with following contents - 

<!doctype html>

<html>
  <head>
    <title>OSFG Chrome Demo Plugin</title>
    <script src="popup.js"></script>
  </head>
  <body>

    <h1>Current Site URL : </h1>
    <br/>
    <div id="currentTabUrl"></div>
  </body>
</html>


Again a simple HTML file but note it asks to load a popup.js javascript file.

  •  Go ahead create a file called popup.js and add following contents to it -

function getCurrentActiveTabUrl(callback) {

  var tabQueryInfo = {
    active: true,
    currentWindow: true
  };

  chrome.tabs.query(tabQueryInfo, function(tabs) {
    var currentTab = tabs[0];
    var url = currentTab.url;]
    console.log(url);
    console.assert(typeof url == 'string', 'currentTab.url should be a string');
    callback(url);
  });

}
  

function renderOutput(outputText) {
  document.getElementById('currentTabUrl').innerHTML = "<a href='" + outputText + "'>" + outputText + "</a>";
}

document.addEventListener('DOMContentLoaded', function() {
  getCurrentActiveTabUrl(function(url) {
        renderOutput(url);
  });
});



Take some time to see the javascript code above. It essentially reads the current active TAB url and shows it in the popup in an anchor tag. And there you go your first chrome plugin is all set to be deployed.

NOTE : Most of the chrome APIs are asynchronous. So you cannot do something like -

var currTabUrl;
chrome.tabs.query(queryInfo, function(tabs) {
  currTabUrl= tabs[0].url;
});
alert(currTabUrl); // Will show "undefined" as chrome.tabs.query is async.


Deploying your chrome plugin

Deploying your plugin is again quite simple
  • Go to chrome://extensions/ URL is your chrome browser. Here you should see list of existing chrome extensions you are using.
  • Make sure "Developer Mode" check box is selected.

  • Now click on "Load Unpacked Extension" and select the folder you have plugin in - "chrome_plugin" directory is this case.

  • Now open any tab. You should see the plugin with icon you had put in the directory just besides Omnibox. Go to any URL and then click on the plugin icon.  



 You can download this sample chrome plugin code from here.

Appending custom methods to chrome right click Menu

Lets see how we can add custom functions to right click menu. Here is what we are going to do -  we will add a new option on right click which enables to search selected text in google maps.


The new manifest.json file looks like the following - 

{
  "manifest_version": 2,

  "name": "Chrome Test Plugin",
  "description": "This extension will just show current active Tab URL",
  "version": "1.0",
  
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "activeTab",
   "contextMenus"
   ]
}

Notice couple of differences here
  1. There is a new permission added called contextMenus. This basically lets you operator om chrome context menus.
  2. There is a new key added called background that basically tells chrome about background processes. You can specify scripts or page here.
 Next in background.js add following code

function searchgooglemaps(info)
{
 var searchstring = info.selectionText;
 chrome.tabs.create({url: "http://maps.google.com/maps?q=" + searchstring})
}

chrome.contextMenus.create({title: "Search Google Maps", contexts:["selection"], onclick: searchgooglemaps});


 And you are done. Reload the extension.



When you click on "Search Google Maps" you should see a new Tab opening with google maps and a search location of your desired selected String.


Related Links

Thursday, 12 November 2015

Understanding p-namespace and c-namespace in Spring


Background

 In one of the previous post on Spring Dependency Injection we saw how beans are created. We also saw c namespace and how to use it.

  1. For values as dependency (like simple String) you can do <property name="brand" value="MRF"/> or <property name="bat" ref="myBat"/>
  2. Instead of using property tag you can also use p namespace - <bean id="cricket" class="Cricket" p:brand="MRF" p:bat-ref="myBat" />  (don't forget to add the namespace)
  3. Also note p namespace does not have any schema reference. 

Entire Spring configuration bean looks like -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cricket" class="com.osfg.Cricket" p:brand="MRF" p:bat-ref="myBat" />

</beans>


In this post we will see what c name space is and how to use it.

Spring 3.1 Constructor Namespace  

As you already know by now you can do dependency injection by setters or by constructor - setter injection and constructor injection.

Let's see a simple  example of constructor based dependency injection.

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cricket" class="com.osfg.Cricket">
    <constructor-arg value="MRF"/>
    <constructor-arg ref="myBat"/>
  </bean>

</beans>

NOTE : The <constructor-arg> tag could take type and index to reduce ambiguity, but not name.

You can simplify above xml using c namespace

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:c="http://www.springframework.org/schema/c"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="cricket" class="com.osfg.Cricket"
    c:brand="MRF"
    c:ref-bat="myBat"/>

</beans>

NOTE : Both the “p” ad “c” namespaces do not have a schema reference in the XML header.

Related Links

Wednesday, 11 November 2015

Using Handlers for async communication in Android

Background

In one of the previous posts we say how Android OS shows ANR(App not responding) if UI threads is blocked for more than 5 seconds. And to overcome this we used Async Tasks.

 In this post we will see how to use handlers which is another mechanism for asynchronous communication.

NOTE : Both handlers and async task internally use threads. So you can achieve the same functionality by pure java threading.

Using Handlers for async communication in Android

Here is what we are going to do. We are going to simulate a 6 seconds task. After that is completed we will send a message to the handler registered on the main thread and it will show a toast message showing task is completed.


To start with we have a simple layout with a button at the center that says "Start Process"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context=".MainActivity">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Process"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Next lets get our handler ready.

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by athakur on 11/11/2015.
 */
public class MainActivityHandler extends Handler {

    public static int SHOW_PROCESS_FINISH_TOAST = 29;

    private Activity activity;
    private static final String TAG = MainActivityHandler.class.getSimpleName();

    public MainActivityHandler(Activity handlerActivity) {
        this.activity = handlerActivity;
    }

    @Override
    public void handleMessage(Message msg) {
        Log.d(TAG, "Received message : " + (msg == null ? null : msg.what));
        switch(msg.what) {
            case 29:
                Toast.makeText(activity,"Finished Processing Task",Toast.LENGTH_LONG).show();
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

This is just a class that extends handler and overrides handleMessage method. It then checks whether the message received is of type process completed show toast type. If so them simply show a toast message saying  "Finished Processing Task".

Now lets see this in action. Write your MainActivity as follows - 

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button myButton = (Button) findViewById(R.id.myButton);
        final Handler mainActivityHandler = new MainActivityHandler(this);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "Starting process");
                        try {
                            //simulate process for 6 seconds
                            Thread.sleep(6000);
                        } catch (InterruptedException e) {
                            Log.e(TAG,"Thread sleep interrupted",e);
                        }
                        Log.d(TAG, "Ending process. Sending Notification");
                        mainActivityHandler.sendEmptyMessage(MainActivityHandler.SHOW_PROCESS_FINISH_TOAST);
                    }
                }).start();
            }
        });
    }
}


 In the MainActivitys oncreate method we are getting reference of the button and on its onclick we are starting a new thread that does the processing for 6 seconds and then sends a message to the handler that it is done. We are also creating a new handler here.

NOTE1 : Handler is created on main thread or UI thread so it will have messages corresponding to UI threads message queue.

NOTE2 : You cal also post a runnable to be run on the thread to which handler belongs to.

Simply install the app on your phone or emulator and click on "Start Process" button. You should see the process completed toast after 6 seconds without any ANR.



So in a nutshell -

Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue



Realated Links

t> UA-39527780-1 back to top