Saturday, 26 December 2015

Spring redirect using mvc:redirect-view-controller tag

Background

This is an extension of my previous post on 
So if you have directly landed here I would highly recommend to read it first for setup.  In this post we will essentially see how can we redirect one URL to other using mvc:redirect-view-controller tag configuration.


Spring redirect using mvc:redirect-view-controller tag

Basic setup remains the same as that of previous post

NOTE : For this Spring 4.1+ is required! So change your ivy dependency accordingly.

        <dependency org="org.springframework" name="spring-webmvc"
            rev="4.1.4.RELEASE">
            <exclude org="javax.servlet" name="javax.servlet-api" />
            <exclude org="javax.servlet.jsp" name="jsp-api" />
            <exclude org="javax.el" name="javax.el-api" />
        </dependency>

Now only change that you need to do in your spring configuration is as follows - 

    <mvc:redirect-view-controller redirect-url="/TestWebProject/newtest" path="/oldtest" status-code="308" keep-query-params="true"/>
    <mvc:view-controller path="/newtest" view-name="test"/>

All it says is if you get a URL "/oldtest" redirect it to new URL "/newtest" and the 2nd line states if you get url "/newtest" then render view with logical name test which will again render the same JSP test.jsp as per the InternalResourceViewResolver.






Notice the redirect with 308 response status.


Alternate way to redirect is using

<mvc:view-controller path="/oldtest" view-name="redirect:newtest"/>
 <mvc:view-controller path="/newtest" view-name="test"/>



Again notices the 302 response code.


NOTE : It is not desirable to use version in xsd declaration. Spring will use highest version in the project's dependencies if version not given.

How to install Maven on Windows

Prerequisites

  • We are going to install  Maven 3.3.9. So make sure you have JDK 7 installed. 
  • Set JAVA_HOME env variable to above JDK. For me it is C:\Program Files\Java\jdk1.7.0_79
  • Also I am using Windows 7.

How to install Maven on Windows

  • Download Maven zip file from their official site. We are going to install Maven 3.3.9. So go ahead download the corresponding zip file - apache-maven-3.3.9-bin.zip
  • Unzip it to some folder.  I have extracted it in folder - C:\Users\athakur\Softwares\apache-maven-3.3.9
  • Now add M2_HOME and MAVEN_HOME environment variable and point them to your extracted folder.
  • Append your %PATH% variable to add %M2_HOME%\bin
  • Make sure your JAVA_HOME is set to JDK 7 as per note below.
  • Finally you can execute mvn -version to see if maven is successful installed.







NOTE : Maven 3.3 requires JDK 1.7 or above to execute. Maven 3.2 requires JDK 1.6 or above, while Maven 3.0/3.1 requires JDK 1.5 or above

Related Links

Serving static resources with Spring MVC 3.0 in Java

Background

Many time we use custom CSS and java script file to add functionality and style to our web pages. We usually refer them in our JSP pages. In this post we will see how we can refer such static resources with Spring 3.0+. We will use Tomcat as our container/server.


Setup

If you are new to Spring then try out a sample Spring program -
Above post is somewhat old but should give you good idea as to get started. Anyhow I will provide the setup xmls here.

Your web.xml file should look as follows -

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Spring Web MVC Demo Application</display-name>
   
   
  <servlet>
      <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
     <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
  </servlet-mapping>
  
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   

</web-app>



 Important file here is mvc-dispatcher-servlet.xml which forms a part of web application context. Have given a dummy file root-context.xml for root application context but you may not add it in your web.xml file. If you are not familiar with context loading part I suggest read

As I said create file mvc-dispatcher-servlet.xml with following content -

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

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
    <!-- Scan for components under this package -->
    <context:component-scan base-package="com.osfg.test" />



    <mvc:annotation-driven/>
    
</beans>


As you can see the web application context will scan package com.osfg.test to find Spring resources like handler/interceptor. GO ahead create this package and create a controller in it. Lets call it TestController.java. Add following content to it.

package com.osfg.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author athakur
 */
@Controller
public class TestController {
    
    @RequestMapping(value="/test", method=RequestMethod.GET)
    public String welcome() {
        return "test";
    }

}



That's it. We have our controller all setup. This controller returns a logical view name called test. Now if you notice our spring configuration we have already defined InternalResourceViewResolver which provides a JSTL view. So go ahead and create a JSP file at /pages/test.jsp under webapp or webcontent.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>OSFG Test Page</title>
<link href="CSS/test.css" rel="stylesheet">
</head>
<body>

<h1>Hello World from OSFG!</h1>

</body>
</html>


As you can see our JSP references a CSS file called test.css. Create a folder called CSS and then create a file called test.cs  in it. Add following contents to it.
H1 {
color: white; background: teal; FONT-FAMILY: arial; FONT-SIZE: 18pt; FONT-STYLE: normal; FONT-VARIANT: normal
}



Ok we are all set to test now.

Note the Directory structure below -

 


Testing 1.0

Go ahead start up your tomcat server and load following URL
  • http://localhost:8080/TestWebProject/test 



 Oops! what happened? It is not able to find the CSS file.Well lets come to the point. Spring does not directly allow you to access static resources and the very goal of this post is to show you how. So lets see that now.

Add following to your Spring configuration -
<mvc:default-servlet-handler />


This basically allows you to render static resources from root folder (under webapp or webcontent).
It essentially configures a handler for serving static resources by forwarding to the Servlet container's default Servlet (DefaultServletHttpRequestHandler is used).
 Lets test with our new configuration -

Testing 2.0

After restarting the server hit the URL again -



All good? Yup :) There is also alternate way to do this. You can define resource mapping instead of specifying default-servlet-handler.

<mvc:resources mapping="/resources/**" location="/CSS/" />

Then you also need to make change in JSP as follows

<link href="resources/test.css" rel="stylesheet">

So when you reference resources it will go and pick up from CSS. You can use classpath references in location as well. Here ResourceHttpRequestHandler is used to serve request based on location provided.


Related Links





Saturday, 19 December 2015

Variables Inheritance in Java

Background

In one of the previous posts we saw method overriding. 
In case of variables it is slightly different. It is shadowing that overriding.

Variables Inheritance in Java

Following code will help you understand better

class A {
    int number = 10;
}

class B extends A {
    int number = 4;

    public void test() {
        System.out.println(this.number);
        System.out.println(super.number);
        System.out.println(((A)this).number); //same behavior as super.number
    }
}

public class HelloWorld {
    
    public static void main(String args[]) {
        B b = new B();
        b.test();
    }

}

And this will output : 
4
10
10

Note : Access to static/instance fields and static methods depend on class of the polymorphic reference variable and not the actual object to which reference point to. Also variables are never overridden. They are shadowed.

So if you have

public class A {
    public static String test = "testA";
    public static void test() {
        System.out.println(test);
    }
}


and

public class B extends A {
    public static String test = "testB";
    public static void test() {
        System.out.println(test);
    }
}


and you run

public class Test {
    public static void main(String args[]) {
        A a  = new B();
        a.test();
    }
}


it will print testA

Note : In method overridden return type can be same or subclass of the super class method. Same goes for Exception thrown. Exception thrown by the overridden method can be same or subclass of Exception thrown by method in the super class. However the access modifies for the overridden method should be more strict.

Related Links

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

Saturday, 7 November 2015

Showing notification from you Android App

Background

Many time you must have seen apps send out notifications that you see in the title bar of your screen. For eg. when you receive a SMS or when your battery is low. Android provides mechanism for your app to send out such notifications. In this post we will see how to do it programmatically.


Showing notification from you Android App

Here is what we are going to do. We will simply create a button that when on click will show a notification and close the App. On click of that notification we will restart our App.

Before we write our Activity code create a simple layout with button at the center. To see more details on centering your layout refer -

PATH : NotificationDemo\app\src\main\res\layout\activity_main.xml

<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="Show Notification"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Next lets write our Activity class - 

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button myButton = (Button) findViewById(R.id.myButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, (int) System.currentTimeMillis(), intent, 0);

                Notification notification  = new Notification.Builder(MainActivity.this)
                        .setContentTitle("Test Notification")
                        .setContentText("You have received a notification from OSFG")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(pIntent)
                        .setAutoCancel(true)
                        .addAction(R.mipmap.ic_launcher, "Action1", pIntent)
                        .addAction(R.mipmap.ic_launcher, "Action2", pIntent).build();


                NotificationManager notificationManager =
                        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                notificationManager.notify(0, notification);
                finish();
            }
        });
    }
}

Now lets test out our code. Install the App on your Android phone or VM and launch it. You should see following screen -



Now click on Show notification button. You should receive a notification in the title bar and your App should get close.




Now look at the code again and relate the subject title and actions we had set. Also notice that we are calling finish() on showing notification that will effectively terminate our main activity. Now click on the notification (or the actions in it). Our App should get launched again. You should see activity with show notification button again.

NOTE : You can call the cancel() for a specific notification ID from the NotificationManager. You can also do cancelAll() method that will essentially removes all of the notifications you had previously issued.

NOTE : You can also use NotificationCompat to get builder. You can use things like NotificationCompat.Builder#setLargeIcon(Bitmap) to allow you to take full advantage of Android 3.0+ with things like the large icon, while maintaining compatibility on versions of Android prior to 3.0 that do not support such thing.

What is this pending intent?

If you are still wondering what is this intent and how is it different than a normal intent then you are on right track. PendingIntent is executed by remote component (Like NotificationManager,alarm manager or other 3rd party applications) with the same permissions as that of the component that hands it over (The one that creates the notification).

 NOTE :  To perform a broadcast via a pending intent you can get a PendingIntent via the getBroadcast() method of the PendingIntent class and to perform an activity via a pending intent, you can get the activity via PendingIntent.getActivity() method.

Disabling notifications

Some apps provide settings in their App itself to turn off notifications. If setting is not provided you can also disable it from App info screen. For more details refer one of the earlier posts - 


Related Links

How To Add Google+ Follower Widget in your website or WordPress/Blogger blogs

Background

It been almost two and a half years since I am blogging on bloggers and I though it's time I see what wordpress has to offer. To surprise the UI is kind of complex and have limited widget support. Also it does not allow you to add plugins. After a few customizations I decided to add a Google+ followers widget but there unfortunately isn't one. Hence this post. It's a simple html/javascript. So you can plug it into any website. Bloggers as you know already has a widget for this.


How To Add Google+ Follower Widget in your blog/website

  • First create a simple text/html widget
  • Next add following javascript code to it
<div class="g-plus" data-action="followers" data-height="300" data-href="https://plus.google.com/102342595285863325267" data-source="blogger:blog:followers" data-width="320">
</div>
<script type="text/javascript">
      (function() {
        window.___gcfg = {'lang': 'en'};
        var po = document.createElement('script');
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
      })();
    </script>


  • Next Save and Publish. You should now be able to see the widget on your wordpress site.
NOTE : Make sure you use your own G+ page URL as the value of data-href attribute in div tag.

You should see it get rendered as follows -


Sunday, 1 November 2015

Spring dependency injection using annotation based Autowiring

Background



In last post you would have seen what dependency injection is and how is it generally achieved in Spring. It is done using beans that you define in you xml file using tags bean , constructor-arg and property.

But as your project size grows it becomes difficult to keep adding bean in your XML files with its dependencies as the size of xml file continues to grow. So Spring has provided a feature called autowiring where bean dependencies are automatically injected based on various criteria like name, type etc (you can find all types in the previous post). Going a step forward Spring also provides annotations based injection in which case you don't event have to define beans. Spring will scan annotations and inject dependencies on it's own Ofcourse there are rules by which this is governed. We will see this autowiring feature in this post with and without annotations.

Lets continue with the Cricket example we saw in Last post.

Models

Lets rewrite our model classes - 

Bat.java

package models;



public class Bat {    

    private String name;

    public Bat() {}

    

    public Bat(String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    
    public void play() {
        System.out.println("Bat is swung");
    }

}


Ball.java

package models;

public class Ball {
    

    private String name;


    public Ball() {} 
    

    public Ball(String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    

    public void play() {
        System.out.println("Ball is bowled");
    }

}

And finally Cricket.java

package models;



public class Cricket {

    private Bat bat;
    private Ball ball;

    public Bat getBat() {
        return bat;
    }

    public void setBat(Bat bat) {
        this.bat = bat;
    }

    public Ball getBall() {
        return ball;]
    }

    public void setBall(Ball ball) {
        this.ball = ball;
    }

    

    public void play() {
        ball.play();
        bat.play();
    }

    

}

now lets configure Spring for these models. 

Spring configuration

Under src folder create a file called beans.xml and add following beans to it

beans.xml

<?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-3.0.xsd">

    

   <bean id="bat" class="models.Bat" />
   <bean id="ball" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" autowire="byType"/>

</beans>

Note :  Notice the attribute autowire of tag bean which is set to byType. This means Cricket has dependency on Bat instance so find a bean of type Bat and inject into cricket. You can also set it as byName in which case it will match bean name and inject dependency, However be careful in using this - if spring finds two beans of type Bat it will throw exception.

Now lets run this setup

Main.java

import models.Cricket;



import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {

    
    public static void main(String args[]) {
       
        ApplicationContext context =  new ClassPathXmlApplicationContext("beans.xml");
        Cricket cricket = (Cricket) context.getBean("cricket");
        cricket.play();
    }
    
}
Output :
Ball is bowled
Bat is swung
Now lets see the same thing with annotations.

Note : Note that spring first created beans that are dependencies and then injects in into objects that need them. Also all beans by default are singleton.

Spring dependency injection using annotation based Autowiring

Changes needed
  1. In your beans.xml file remove autowire="byType" from the cricket tag.
  2. In your Cricket class use @Autowired annotation over your Bat and Ball instance variables.
 beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>
    
   <bean id="bat" class="models.Bat" />
   <bean id="ball" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" />

</beans>


Cricket.java

public class Cricket {
    
    @Autowired
    private Bat bat;
    @Autowired
    private Ball ball;
    //more code 
} 



Now run the same program as above and you should again get the same output. Few point to note -
  1.  Using @Autowired annotation is same as saying find the bean by type.If Spring finds no bean of injected type for auto-wiring, then it will throw NoSuchBeanDef Exception. If you think that this dependency is not a must than you can use @Autowired(required=false).
  2. As mentioned before @Autowired annotation is similar to autowiting by type. If there are two beans of same type you land in trouble. In such cases you can use resolve by name. For this you can use @Qualifier(value="beanName")
  3. Combination of using @Autowired(required=false) with @Qualifier(value="beanName") is very flexible as you can use this to specify you dependency is not a mandate and you can also specify bean name to resolve with.

To use Qualifier annotation Change your beans.xml as follows

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>

    
   <bean id="myBat" class="models.Bat" />
   <bean id="myBall" class="models.Ball" /> 
   <bean id="cricket" class="models.Cricket" />

</beans>


and your cricket class as follows

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Cricket {

    
    @Autowired(required=false)
    @Qualifier(value="myBat") 
    private Bat bat

    @Autowired(required=false)
    @Qualifier(value="myBall") 
    private Ball ball;

     //more code 

}


and run the Main class again you should see same result.


Note : If you want to resolve by name then you can use @Resource annotation. Sample usage would be @Resource(name="myBat") . But note here that you loose the flexibility of marking it as non mandatory as you did with @Autowired annotation. All dependencies become mandatory.


Change the Cricket class as

public class Cricket {
    

    @Resource(name="myBat") 
    private Bat bat;

    @Resource(name="myBall") 
    private Ball ball;
   
    //More code
} 



and rerun Main methods. You should see same output.


Related Links

Saturday, 31 October 2015

Spring Dependency Injection

Background



Before we proceed with how dependency injection works in Spring lets see what dependency injection actually is and why is it so important.

Consider a simple example. Lets say we are designing a Cricket game. How will it's class look like?

You will have a Cricket class that will probably have Bat class and Ball class.

public class Cricket {
    private Bat bat;
    private Ball ball;
    
    public Cricket()
   {
        bat = new Bat("MyBat1") ;
        ball= new Ball("MyBall1") ;
   }


   public void play()
   {
         bat.play();
         ball.play(); 
   }
     
}


How would you play cricket? Probably something like

public class Main {
    
    public static void main(String args[]) {
        Cricket cricket1 = new Cricket();

         cricket1.play();       
    }
    
}


What do you think about above code -
  • It is tightly coupled. If you device to change your Bat or Ball you have to write a new Cricket instance. 
  • It will also be very difficult to test. There can be any type of Bat or Ball and each test your need new Cricket instance.

This is where dependency injection comes into picture. Now consider your cricket class as follows.

public class Cricket {
    private Bat bat;
    private Ball ball;
    
    public Cricket(Bat bat, Ball ball) {
        this.bat = bat;
        this.ball = ball;
    }
    
    public void play() {
        bat.play();
        ball.play();
    }
    
}

and you play like

    public static void main(String args[]) {
       
        Bat bat1 =  new Bat("MyBat");
        Ball ball1 =  new Ball("MyBall");
        Cricket cricket1 = new Cricket(bat1, ball1);
        cricket1.play();
       
        Bat bat2 =  new Bat("MyNewBat");
        Ball ball2 =  new Ball("MyNewBall");
        Cricket cricket2 = new Cricket(bat2, ball2);
        cricket2.play();

    }

If you notice you can create and use any type of bat and ball and play cricket with it. All of it is done at runtime. So essentially you are injecting Bat and Ball dependencies into your Cricket object.

Also notice the problems we faced with earlier code are vanished
  • Code is now decoupled. You can use any Bat and Ball to play cricket.
  • Testing has also becomes very easy as you can now mock your Bat and Ball objects and test your cricket.

There are two types of dependency injection
  1. Constructor based dependency injection
  2. Setters based dependency injection
What you saw in code above is constructor based dependency injection. Setter based dependency injection is when you use setters instead of constructor to inject dependency. See following example -


public class Cricket {
    private Bat bat;
    private Ball ball;
    
    public Bat getBat() {
        return bat;
    }

    public void setBat(Bat bat) {
        this.bat = bat;
    }

    public Ball getBall() {
        return ball;
    }

    public void setBall(Ball ball) {
        this.ball = ball;
    }
    
    public void play() {
        bat.play();
        ball.play();
    }
    
}


and you play like

     public static void main(String args[]) {
        
        Bat bat1 =  new Bat("MyBat");
        Ball ball1 =  new Ball("MyBall");
        Cricket cricket1 = new Cricket();
        cricket1.setBat(bat1);
        cricket1.setBall(ball1);
        cricket1.play();
        
        Bat bat2 =  new Bat("MyNewBat");
        Ball ball2 =  new Ball("MyNewBall");
        Cricket cricket2 = new Cricket();
        cricket2.setBat(bat2);
        cricket2.setBall(ball2);
        cricket2.play();

    }


Simply putting

"Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out."

That's the dependency injection in general. Now lets come to Spring dependency injection.

Spring Dependency Injection 

In Spring dependency injection Spring container instantiates and injects dependencies in your instance (also called beans) based on the dependency type or name (more on this later) rather that you instantiating and injecting it yourself.


Lets see how spring DI works in case of our above code.

  • Setter DI

<?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-3.0.xsd">

    <bean id="myBat" class="Bat">
    
    <bean id="myBall" class="Ball">
    
   <bean id="cricket" class="Cricket">
      <property name="bat" ref="myBat"/>
      <property name="ball" ref="myBall"/>
   </bean>

</beans>

Above bean definition uses setter DI. Spring container scans beans and automatically injects dependencies in it. You can also use 
  • Constructor based DI
<?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-3.0.xsd">

    <bean id="myBat" class="Bat">
    
    <bean id="myBall" class="Ball">
    
   <bean id="cricket" class="Cricket">
      <constructor-arg ref="myBat"/> <!--  constructor argument order should be same-->
      <constructor-arg ref="myBall"/>
   </bean>

</beans>

Notes : 
  1. For values as dependency (like simple String) you can do <property name="brand" ref="MRF"/>
  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.

Aurowiring

Instead of explicitly providing dependencies to be injected you can autowire them. One simple example is autowiring by type. In this case Spring container will look for bean of dependency type among all beans and inject it. However note if more than one type of such bean exist this will fail.

  • autowire is an attribute in bean tag with following possible values.





Another interesting aspect is spring DI using annotations and component scan. Instead of specifying beans you can directly use annotations and ask spring framework to scan those and autowire. You can see the same in next post -


NOTE : Dependency injection and IoC (Inversion of control) are words used interchangeably. Both mean dependencies are injected rather that created itself by the object which needs the dependencies.

Related Links


t> UA-39527780-1 back to top