Thursday, March 12, 2015

WebLogic patching

cd /appserver/Oracle/Middleware-10.3.6/utils/bsu/cache_dir
unzip /tmp/
./ -prod_dir=/appserver/Oracle/Middleware-10.3.6/wlserver_10.3  -patchlist=H6RZ -verbose -install
./ -report -patch_id_mask=H6RZ

Sunday, January 25, 2015

Kirana best price delivery application

Problem to solve: People have to go to multiple shops for checking best price. Then, they buy stuff they needed and wait for an auto/rikshaw to bring those goods home. They often need to go to multiple shops for different items

  1. Buyer builds an order list and places the order from a mobile device
  2. XYZ receives the order and finds optimal prices/shops to buy those items
  3. XYZ sends "order picking boys" to gather items by pooling items from different orders
  4. "order picking boys" bring items to XYZ warehouse where they pack each order
  5. "order delivery boys" deliver orders, bring cash
  6. XYZ gets feed from local big shops and distributors containing item prices for that day
  7. XYZ and distributors settle finances later by reconciling transactions 

Small business order and inventory management system

Problem to solve: Automate the ordering of items in a small grocery/kirana merchant.
  1. A kirana merchant owner orders items from wholesale distributor 
  2. #1 can be a onetime or recurrent order
  3. Kirana merchant can select items, adds them to the order and specifies quantity
  4. kirana merchant adds address and phone number for delivery
  5. Wholesale distributor is notified whenever there is a new order
  6. Wholesale distributor has ability to cancel/fulfill/deliver/getPaymentConfirmation order

Thursday, January 15, 2015

Simple Android Application using Activities and Maps

This is a simple Android app that uses two activities. This app uses Google Maps API.

  1. Download Android studio and install
  2. Create a new blank activity - this is the launcher activity
  3. Login to google and enable Maps API by providing SHA-1 value of your client
    1. C:\Users\xyz>keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
    2. Register ssh-1 key in google API console along with application package name
    3. Get the key and save it in android manifest
  4. Launcher activity creates a new private class that extends AsyncTask
  5. This class is responsible to call the API to retrieve JSON rest call
  6. JSON output is parsed and we only retrieve few values we needed from the json hierarchy
  7. There is a second button that invokes a MapsActivity when clicked by passing latitude and longitude via intent
  8. This app uses free weather API
Important file contents

    <string name="google_maps_key_instructions" templateMergeStrategy="replace">
    <string name="google_maps_key" templateMergeStrategy="preserve">GoogleAPIKeyHere</string>

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import org.json.JSONObject;


public class MainActivity3 extends ActionBarActivity  implements View.OnClickListener {

    public static final String RESTAPI_URL = "";

    public static final String UNITS = "&units=metric";

    EditText result;
    EditText cityCountry;
    ProgressBar pb;
    Button button;

    String longitude;
    String latitude;

    protected void onCreate(Bundle savedInstanceState) {

        pb = (ProgressBar) findViewById(;

        button = (Button) findViewById(;

        Button mapButton = (Button) findViewById(;

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == {
            return true;

        return super.onOptionsItemSelected(item);

    public void onClick(View v) {

        if( v.getId() == ) {
            Intent intent = new Intent(this, MapsActivity.class);
            intent.putExtra("lat", Double.parseDouble(latitude));
            intent.putExtra("long", Double.parseDouble(longitude));

            result = (EditText)findViewById(;
            cityCountry = (EditText)findViewById(;
            pb = (ProgressBar) findViewById(;

            //call web service
            AsyncTaskService service = new AsyncTaskService();


    private class AsyncTaskService extends AsyncTask<String, Integer, String> {

        String jSonContent;
        String resultToDisplay;

        protected String doInBackground(String... params) {
            return null;

        protected void onPostExecute(String serviceResult){

        protected void onProgressUpdate(Integer... progress){

        public void postData(String valueIWantToSend) {
            // HTTP Get
            BufferedReader reader = null;
            try {
                URL url = new URL(RESTAPI_URL+valueIWantToSend+UNITS);

                StringBuilder sb = new StringBuilder();
                String line = null;

                reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
                // Read Server Response
                while((line = reader.readLine()) != null)
                    // Append server response in string
                    sb.append(line + "");
                    System.out.println("Response:"+ line);

                // Append Server Response To Content String
                jSonContent = sb.toString();


            } catch (Exception e ) {

        private void parseJson(String rawJson) {
            JSONObject jsonResponse;

            StringBuffer sb = new StringBuffer();
            try {
                jsonResponse = new JSONObject(rawJson);

                JSONObject coord = jsonResponse.getJSONObject("coord");
                longitude = coord.getString("lon");
                latitude = coord.getString("lat");

                sb.append("Latitude:" + latitude);
                sb.append("\nLongitude:" + longitude);

                JSONObject sys = jsonResponse.getJSONObject("sys");
                String countryCode = sys.getString("country");
                sb.append("\nCountry Code:" + countryCode);

                JSONObject main = jsonResponse.getJSONObject("main");
                String minTemp = main.getString("temp_min");
                String maxTemp = main.getString("temp_max");

                sb.append("\nMin Temp:" + minTemp);
                sb.append("\nMax Temp:" + maxTemp);

                String cityName = jsonResponse.getString("name");
                sb.append("\nCity Name:" + cityName);

                resultToDisplay = sb.toString();

            } catch (Exception e ) {




public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    double latitude;
    double longitude;

    protected void onCreate(Bundle savedInstanceState) {

        Intent intent = getIntent();
        latitude = intent.getDoubleExtra("lat", 0);
        longitude = intent.getDoubleExtra("long", 0);



    protected void onResume() {

     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
            // Check if we were successful in obtaining the map.
            if (mMap != null) {

     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
    private void setUpMap() {
        //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

        LatLng position = new LatLng(latitude, longitude);
        // create marker
        MarkerOptions marker = new MarkerOptions().position(position).title("Hello Maps ");

        // adding marker

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 4));

WLST script to create JMS resources

This script creates JMS servers, JMS module, JMS subdeployment, one connection factory and one UDQ.

Before you run this script, you need to set environment by running following command.


>>>> java weblogic.WLST

import sys

from java.util import *
from import *   
from import FileInputStream

print "@@@ creating JMS resources ..."

propInputStream1 = FileInputStream("")
domainProps = util.Properties()

    connect(adminUserName, adminPassword, adminURL)

    #build JMS Server1 - target to managed server

    i = 1
    for managedServer in managedServers:
        set('Targets', jarray.array([ObjectName(msObjectName)], ObjectName))
        print "@@@ created JMS Server"
        i = i + 1
    # Build JMS Module - target preferrable cluster
    set('Targets',jarray.array([ObjectName('com.bea:Name='+clusterName+',Type=Cluster')], ObjectName))
    print "@@@ creating JMS module ..." 
    # Build JMS Connection Factory XA - target to cluster
    print "@@@ creating JMS connection factory ..."

    # Build JMS Subdeployment - target to all JMS servers
    print "@@@ creating JMS subdeployment ..."
    i = 1
    for managedServer in managedServers:
        i = i + 1
    set('Targets',jarray.array(list, ObjectName))
    print "@@@ created JMS subdeployment ..."
    #Email queue - XYZ_QUEUE
    print "@@@ completed creating JMS resources ..."
    activate(200000, block='true')
except Exception, e:
       print "@@@ exception occured"
       print e

Contents of

WLST Script to create persistent stores

This script creates persistent stores targeted to a cluster. Input properties are specified in

Before this script is run, set the environment using following command.


>>>java weblogic.WLST

import sys

from java.util import *
from import *   
from import FileInputStream

print "@@@ creating JDBC persistence stores ..."

propInputStream1 = FileInputStream("")
domainProps = util.Properties()



      connect(adminUserName, adminPassword, adminURL)

###################Create JDBC Stores for cluster####################


      i = 1
      for managedServer in managedServers:
    set('Targets',jarray.array([ObjectName(msObjectName)], ObjectName))
    print "@@@ created JDBC persistence store"
    i = i + 1

      print "@@@ script completed"

       print "@@@ exception in wlst script"

Friday, November 21, 2014

High CPU and/or stuck thread diagnosis

  1. You can configure max stuck thread timeout in WebLogic admin console
  2. When you get an alert or observe high CPU, do a top or prstat command
  3. #2 will identify high cpu consuming java processes
  4. Convert the PID to hex to get thread number
  5. Do a thread dump (using kill -3 or admin console or jstack) and identify the thread
  6. Look at where it is stuck or processing

xterm setup for GUI access on Linux

1.Logon to the host with your id using MobaXterm (or putty)
2. echo $DISPLAY
3. xauth list
you should get something like:      xyz1064/unix:10  MIT-MAGIC-COOKIE-1  3a6eab1ace1c1cd28ea0bc1569e0d112   
4. sudo su – oracle
5. $ export DISPLAY=(the same value your received in step 2)
6. $ xauth add xyz1064/unix:10  MIT-MAGIC-COOKIE-1  3a6eab1ace1c1cd28ea0bc1569e0d112  (the same string you received in step 3)

7. xclock    - to test it

Tuesday, October 21, 2014

Weblogic SSL Setup

Identity keystore - For others to access WebLogic using https
This will be used to store the server certificate(private key/digital certificate pairs). When the client contacts server the digital certificate presented in this keystore will be sent. You may also need to store root and intermediate certificates in truststore.

Trust Keystore - For WebLogic to access others (consumes webservices) using https
This will contain all the certificates for the trusted partners(ie partners/clients). When server connects with the partner it will use this key store.

WebLogic SSL self-signed certificate setup

Server49 - admin server and managedserver1
Server50 - managedserver2

on Server49 (repeat on Server50 )

  1. Generate key store and generate key

  2. keytool  -genkey -alias Server49 -keyalg RSA -keysize 1024 -validity 3650 -keypass cat360pa -keystore /appserver/Weblogic/admin/certs/Server49.jks -storepass cat360pa

  3. Save certificate in key store

  4. keytool  -export -alias Server49 -file /appserver/Weblogic/admin/certs/Server49.cer -keystore /appserver/Weblogic/admin/certs/Server49.jks -storepass cat360pa

  5. Save public key in trust store

keytool -import -alias Server49 -file /appserver/Weblogic/admin/certs/Server49.cer -keystore  /appserver/Weblogic/admin/certs/Server49_trust.jks -storepass cat360pa

keytool -list -v -keystore /appserver/Weblogic/admin/certs/Server49.jks -storepass cat360pa
keytool -list -v -keystore /appserver/Weblogic/admin/certs/Server49_trust.jks -storepass cat360pa
keytool -printcert -file  /appserver/Weblogic/admin/certs/Server49.cer -storepass cat360pa


import managed server2's certs into admin server's trust store (no need to import admin server's certificate since it is already there - same host)

keytool -import -alias Server50 -file /tmp/Server50.cer -keystore /appserver/Weblogic/admin/certs/Server49_trust.jks –storepass cat360pa

do admin console changes
- in adminserver--> keystores tab, change keystores to custom identity and custom trust
- specify the path to identity and trust key stores
- in adminserver --> ssl tab, under identity, set "private key alias" to local server host name (Server49)


Configure Nodemanager for SSL communication between adminserver and nodemanager

Add these to file



Wednesday, October 15, 2014

VIP (Virtual IP) and Virtual Host

Virtual IP
A Virtual IP (VIP) maps one external IP address and one external port to a multiple number of possible IP addresses and ports. It can also translate an external port to a different internal port. VIP addresses map traffic received at one IP address to another address based on the destination port number in the TCP or UDP segment header. If you have only one public IP address available, and you want to host multiple servers, use a VIP. An MIP should be used when you have multiple public IP addresses, and you want to host a single server to a single public IP. A VIP is the equivalent of what many network engineers call port forwarding. For example:

An HTTP packet destined for (that is, IP address and port 80) might be mapped to a Web server at
An FTP packet destined for might be mapped to an FTP server at
An SMTP packet destined for might be mapped to a mail server at

Virtual Host
Creating virtual host configurations on your Apache server does not magically cause DNS entries to be created for those host names. You must have the names in DNS, resolving to your IP address, or nobody else will be able to see your web site. You can put entries in your hosts file for local testing, but that will work only from the machine with those hosts entries.
Server configuration

 # Ensure that Apache listens on port 80  

 Listen 80 
 # Listen for virtual host requests on all IP addresses 
 NameVirtualHost *:80 
 <VirtualHost *:80> 
 DocumentRoot /www/example1 
 # Other directives here 
 <VirtualHost *:80> 
 DocumentRoot /www/example2 
 # Other directives here 

Monday, October 06, 2014

JSF 2 introduction

faces-config.xml contains
  • definition of Managed beans, 
  • defines navigation rules (map return conditions to results page), 
  • register validators, 
  • declare locates, 
  • inject bean properties, 


 <faces-config … version="2.2">


 <!DOCTYPE … >
 <html xmlns=""
 <h:head><title>JSF 2: Basic Navigation Rules</title>
 Your message:
 <h:inputText value="#{simpleController.message}"/>
 <h:commandButton value="Show Results"
 public class SimpleController {
  private String message="";
 // getMessage and setMessage
 public String doNavigation() {
 if (message.trim().length() < 2) {
 } else {
 String[] results =
 { "page1", "page2", "page3" };

Managed beans have following scope
  • request
  • application
  • session
  • flow
  • none
Other JSF info
  • web.xml declars extension of url *.jsf
  • You will enter URL as xyz.jsf but actual file name would be xyz.xhtml
  • view technology is facelets
  • JSF has integrated AJAX support (f:ajax tag) and can be thought of as an alternative to jQuery and Dojo etc
  • Event handling
  • built in capabilities for validation
  • Page templating
JSF life cycle
  1. Restore view 
  2. Apply request values; process events 
  3. Process validations; process events 
  4. Update model values; process events
  5. Invoke application; process events
  6. Render response

Friday, October 03, 2014

Typical JEE development process, stack

Agile development using SCRUM methodogy
In the Scrum method of agile software development, work is confined to a regular, repeatable work cycle, known as a sprint or iteration. In by-the-book Scrum, a sprint is 30 days long, but many teams prefer shorter sprints, such as one-week, two-week, or three-week sprints. But how long each sprint lasts is something for the team to decide, who must weigh the advantages or disadvantages of a longer or shorter sprint for their specific development environment. The important thing is that a sprint is a consistent duration.

During each sprint, a team creates a shippable product, no matter how basic that product is. Working within the boundaries of such an accelerated timeframe, the team would only be able to build the most essential functionality. However, placing an emphasis on working code motivates the Product Owner to prioritize a release’s most essential features, encourages developers to focus on short-term goals, and gives customers a tangible, empirically based view of progress. Because a release requires many sprints for satisfactory completion, each iteration of work builds on the previous. This is why Scrum is described as “iterative” and “incremental.”

Every sprint begins with the sprint planning meeting, in which the Product Owner and the team discuss which stories will be moved from the product backlog into the sprint backlog. It is the responsibility of the Product Owner to determine what work the team will do, while the team retains the autonomy to decide how the work gets done. Once the team commits to the work, the Product Owner cannot add more work, alter course mid-sprint, or micromanage.

During the sprint, teams check in at the daily Scrum meeting, also called the daily standup. This time-boxed meeting gives teams a chance to update project status, discuss solutions to challenges, and broadcast progress to the Product Owner (who may only observe or answer the team’s questions).

Just as every sprint begins with the sprint planning meeting, the sprint concludes with the sprint review meeting, in which the team presents its work to the Product Owner. During this meeting, the Product Owner determines if the team’s work has met its acceptance criteria. If a single criterion is not met, the work is rejected as incomplete. If it satisfies the established criteria, then the team is awarded the full number of points.

Because certain sprints are hugely successful and others less than ideal, a team also gathers at the end of each sprint to share what worked, what didn’t, and how processes could be improved. This meeting is called the sprint retrospective meeting.

  1. Architecture and design scenario
    1. architecture concepts
    2. architecture definition
    3. proof of concepts
  2. Setting up development environment
  3. data modelling
  4. analysis and design
    1. class diagrams - inheritance, association, aggregation, composition
    2. usecase diagrams
    3. deployment diagrams
  5. development - reusable components, continuous integration, build automation
  6. WebServices
    1. SOAP web services - stacks, security, 
    2. Restful - stacks, security
    3. Code first Vs contract(WSDL) first approaches
  7. xml binding
  8. Stateless session beans
  9. design patterns
  10. ORM - JPA - Hibernate
  11. Continuous integration (CI)
    1. Developers check out code into their private workspaces.
    2. When done, the commit changes to the repository.
    3. The CI server monitors the repository and checks out changes when they occur.
    4. The CI server builds the system and runs unit and integration tests.
    5. The CI server releases deployable artefacts for testing.
    6. The CI server assigns a build label to the version of the code it just built.
    7. The CI server informs the team of the successful build.
    8. If the build or tests fail, the CI server alerts the team.
    9. The team fix the issue at the earliest opportunity.
    10. Continue to continually integrate and test throughout the project.
    11. Tools used for CI
      1. Deployed jenkins.war in Tomcat
      2. Configure ANT and Maven in Jenkins
      3. Setup Jenkins jobs to build projects
  12. build automation