Wednesday, July 30, 2014

How to monitor your bluemix application through Monitoring and Analytics

IBM Bluemix Monitoring and Analytics identifies the root cause of application problems with code-level diagnostics. When deployed, analytics help you use production log files to keep tabs on performance.


How to use it ?It is very simple ,you can check out the below link.
 https://www.ng.bluemix.net/docs/Services/MonitoringAnalytics/usingapplmon.html

You can see some data from the page.Here I list my two projects use monitor service,you can see some performance data on that.


 Now I need to look at mydbtest application data.Notes: if you find performance monitoring tab has below warning,you need to push the application agian

just like below command to push your application

So you can see all kinds of monitoring information when you open this service console

You can see the application status such as available and unavailable

You can check JVM usage and GC etc information.
The most powerful feature Log Analysis,you can check the log and find your application detail issue.

If you are interested it,you can have a try.If your application have some issues ,you can also use this feature to diagnose your application.


Friday, July 25, 2014

IP address lookup application on BlueMix

These days I am trying to do a application on BlueMix,so it is less updated on the Blog.The aim is user put his ip address,we can quickly get his location on GoogleMap.
I did it on BlueMix,this application is based on SQLDB,java,Spring,google map api.Below are some technical details for my application.

1.create your IP Geolocation db.You can get some data from http://dev.maxmind.com/geoip/legacy/geolite/,if you need more strict location,you need pay the money to buy it.

2.Launch the SQLDB console to create your table and upload your data to these table.
Enter the below sql in the SQL command UI,



CREATE TABLE USER01."GeoLiteCity-Blocks" (       
        "startlpNum" BIGINT NOT NULL,
        "endlpNum" BIGINT NOT NULL,
        "locld" Integer
    );

CREATE TABLE USER01."GeoLiteCity-Location" (       
        "locld" Integer NOT NULL,
        "country" VARCHAR(256) ,
        "region" VARCHAR(256) ,
        "city"  VARCHAR(256),
        "postalCode"  VARCHAR(256) ,
        "latitude" DECIMAL(9 , 4),
        "longitude" DECIMAL(9 , 4)
    );
   
CREATE TABLE USER01."GeoLiteCity-Blocks" (		
		"startlpNum" BIGINT NOT NULL, 
		"endlpNum" BIGINT NOT NULL, 
		"locld" Integer
	);

CREATE TABLE USER01."GeoLiteCity-Location" (		
		"locld" Integer NOT NULL,
		"country" VARCHAR(256) , 
		"region" VARCHAR(256) ,
		"city"  VARCHAR(256),
		"postalCode"  VARCHAR(256) ,
		"latitude" DECIMAL(9 , 4),
		"longitude" DECIMAL(9 , 4)
	);
	
CREATE TABLE USER01."GeoLiteCity-Blocks" (		
		"startlpNum" BIGINT NOT NULL, 
		"endlpNum" BIGINT NOT NULL, 
		"locld" Integer
	);

CREATE TABLE USER01."GeoLiteCity-Location" (		
		"locld" Integer NOT NULL,
		"country" VARCHAR(256) , 
		"region" VARCHAR(256) ,
		"city"  VARCHAR(256),
		"postalCode"  VARCHAR(256) ,
		"latitude" DECIMAL(9 , 4),
		"longitude" DECIMAL(9 , 4)
	);
	
Using Load featur into an existing table to load data in created table
After finish you can check the sample data in these tables.I have inserted above 100000  records in the table,so if your application need lots of data ,I think it should not be a big problem for that.
If your csv file size  is  bigger ,I suggest you can split the csv samller to process faster.see my sample

3.Write java application to connect sqldb console.The most import part you need to write a db connection class to connect sqldb,see below sample code

 package com.ibm.web.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Set;

import com.ibm.db2.jcc.DB2SimpleDataSource;
import com.ibm.nosql.json.api.BasicDBList;
import com.ibm.nosql.json.api.BasicDBObject;
import com.ibm.nosql.json.util.JSON;
public class DBConnection {
  
    String databaseHost = "localhost";
    int port = 50000;
    String databaseName = "mydb";
    String user = "myuser";
    String password = "mypass";
    String myurl = "myurl";
  
  
    public Connection getDBConnection(){
        Connection con = null;
        try {
             String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
             System.out.println("VCAP_SERVICES content: " + VCAP_SERVICES);

                if (VCAP_SERVICES != null) {
                    // parse the VCAP JSON structure
                    BasicDBObject obj = (BasicDBObject) JSON.parse(VCAP_SERVICES);
                    String thekey = null;
                    Set<String> keys = obj.keySet();              
                    // Look for the VCAP key that holds the SQLDB information
                    for (String eachkey : keys) {              
                        // Just in case the service name gets changed to lower case in the future, use toUpperCase
                    System.out.println("key"+eachkey.toUpperCase());
                        if (eachkey.toUpperCase().contains("SQLDB")) {
                            thekey = eachkey;
                        }
                    }
          
                    BasicDBList list = (BasicDBList) obj.get(thekey);
                    obj = (BasicDBObject) list.get("0");  
                    System.out.println("Service found: " + obj.get("name"));
                    obj = (BasicDBObject) obj.get("credentials");
                    databaseHost = (String) obj.get("host");
                    databaseName = (String) obj.get("db");
                    port = (Integer)obj.get("port");
                    user = (String) obj.get("username");
                    password = (String) obj.get("password");
                    myurl = (String) obj.get("jdbcurl");
                    System.out.println("databaseHost"+    databaseHost);
                    System.out.println("databaseName"+    databaseName);
                    System.out.println("username"+    user);
                    System.out.println("password"+    password);
                    System.out.println("port"+    port);
                    System.out.println("jdbc url"+    myurl);
                    String databaseUrl = "jdbc:db2://" + databaseHost + ":" + port + "/"
                            + databaseName;
                    System.out.println("Loading the Database Driver");
                    Class.forName("com.ibm.db2.jcc.DB2Driver");
                    System.out.println("connect db");
                    con = DriverManager.getConnection(databaseUrl, user, password);
                    con.setAutoCommit(false);
                }
                else {
                    System.out.println("VCAP_SERVICES is null");
                  
                }
                return con;
          
        }
        catch (SQLException e) {
            System.out.println("Error connecting to database");
            System.out.println("SQL Exception: " + e.toString());
           return null;
        }
      
        catch (Exception e) {
            System.out.println("cann;t get connection"+e.toString());
            return null;
        }
    }

}

 4.Aslo you need to write ip value convertion,
private static long ipValue(String ipAddress) {
		String[] ippart = ipAddress.split("\\.");
		long ipvalue = 256 * 256 * 256 * Integer.parseInt(ippart[0]) + 256
				* 256 * Integer.parseInt(ippart[1]) + 256
				* Integer.parseInt(ippart[2]) + Integer.parseInt(ippart[3]);
		return ipvalue;
	}

 private static long ipValue(String ipAddress) {
        String[] ippart = ipAddress.split("\\.");
        long ipvalue = 256 * 256 * 256 * Integer.parseInt(ippart[0]) + 256
                * 256 * Integer.parseInt(ippart[1]) + 256
                * Integer.parseInt(ippart[2]) + Integer.parseInt(ippart[3]);
        return ipvalue;
    }
So you can write the sql to query the actual result based on the ipValue,

String sqlStatement = "select a.\"country\",a.\"region\",a.\"city\",a.\"postalCode\",a.\"latitude\",a.\"longitude\"  from   USER01.\"GeoLiteCity-Location\" a, USER01.\"GeoLiteCity-Blocks\" b where b.\"startIpNum\"<="
					+ ipValue
					+ " and  b.\"endIpNum\">="
					+ ipValue
					+ " and a.\"locId\"=b.\"locId\"";
 String sqlStatement = "select a.\"country\",a.\"region\",a.\"city\",a.\"postalCode\",a.\"latitude\",a.\"longitude\"  from   USER01.\"GeoLiteCity-Location\" a, USER01.\"GeoLiteCity-Blocks\" b where b.\"startIpNum\"<="
                    + ipValue
                    + " and  b.\"endIpNum\">="
                    + ipValue
                    + " and a.\"locId\"=b.\"locId\"";
			String countryCode = "";
			String latitude = "";
			String longitude = "";
			String postalCode = "";
			String city = "";
			String region = "";			
			while (rs.next()) {
				countryCode =rs.getString(1);
				region=rs.getString(2);
				city=rs.getString(3);
				postalCode=rs.getString(4);
				latitude =String.valueOf(rs.getDouble(5));
				longitude=String.valueOf(rs.getDouble(6));
			}			
			rs.close();
			Locale l = new Locale("", countryCode);			
			serverLocation.setCountryCode(countryCode);
			serverLocation.setCountryName(l.getDisplayCountry());
			serverLocation.setRegion(region);
			serverLocation.setRegionName(null);
			serverLocation.setCity(city);
			serverLocation.setPostalCode(postalCode);
			serverLocation.setLatitude(latitude);
			serverLocation.setLongitude(longitude);

       
            while (rs.next()) {
                countryCode =rs.getString(1);
                region=rs.getString(2);
                city=rs.getString(3);
                postalCode=rs.getString(4);
                latitude =String.valueOf(rs.getDouble(5));
                longitude=String.valueOf(rs.getDouble(6));
            }          
            Locale l = new Locale("", countryCode);          
            serverLocation.setCountryCode(countryCode);
            serverLocation.setCountryName(l.getDisplayCountry());
            serverLocation.setRegion(region);
            serverLocation.setRegionName(null);
            serverLocation.setCity(city);
            serverLocation.setPostalCode(postalCode);
            serverLocation.setLatitude(latitude);
            serverLocation.setLongitude(longitude);

private static long ipValue(String ipAddress) {
		String[] ippart = ipAddress.split("\\.");
		long ipvalue = 256 * 256 * 256 * Integer.parseInt(ippart[0]) + 256
				* 256 * Integer.parseInt(ippart[1]) + 256
				* Integer.parseInt(ippart[2]) + Integer.parseInt(ippart[3]);
		return ipvalue;
	}

 5.For jsp part,we need to use jquery to parse the result json and use google api to make the Latitude and  longitude location on the google map.Sample code for your reference.
	var map;
		
		function showMap(latitude,longitude) { 
			
			var googleLatandLong = new google.maps.LatLng(latitude,longitude);
		
			var mapOptions = { 
				zoom: 5,
				center: googleLatandLong,
				mapTypeId: google.maps.MapTypeId.ROADMAP 
			};
		
			var mapDiv = document.getElementById("map");
			map = new google.maps.Map(mapDiv, mapOptions);
			
			var title = "Server Location"; 
			addMarker(map, googleLatandLong, title, "");
			
		}
		
		function addMarker(map, latlong, title, content) { 
			
			var markerOptions = {
				position: latlong, 
				map: map,
				title: title, 
				clickable: true
			};
			var marker = new google.maps.Marker(markerOptions); 
		}
		
    var map;
       
        function showMap(latitude,longitude) {
           
            var googleLatandLong = new google.maps.LatLng(latitude,longitude);
       
            var mapOptions = {
                zoom: 5,
                center: googleLatandLong,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
       
            var mapDiv = document.getElementById("map");
            map = new google.maps.Map(mapDiv, mapOptions);
           
            var title = "Server Location";
            addMarker(map, googleLatandLong, title, "");
           
        }
       
        function addMarker(map, latlong, title, content) {
           
            var markerOptions = {
                position: latlong,
                map: map,
                title: title,
                clickable: true
            };
            var marker = new google.maps.Marker(markerOptions);
        }
       
 6.After finish your application,you can export your application to war format.Write a manifest.yml
 for deploy usage.
# this manifest deploys the IP Lookup Sample application
applications:
- name: IPLookup
  #host: IPLookup-${random-word}
  memory: 512M
  instances: 1
  # replace the service name below with appropriate SQLDB service you created
  services:
  - SQLDB-Sample-01
 # this manifest deploys the IP Lookup Sample application
applications:
- name: IPLookup
  #host: IPLookup-${random-word}
  memory: 512M
  instances: 1
  # replace the service name below with appropriate SQLDB service you created
  services:
  - SQLDB-Sample-01

So the main steps are completed,I will share my code at jazzhub,if you are interested in,you can have a look.
package com.ibm.web.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Set;

import com.ibm.db2.jcc.DB2SimpleDataSource;
import com.ibm.nosql.json.api.BasicDBList;
import com.ibm.nosql.json.api.BasicDBObject;
import com.ibm.nosql.json.util.JSON;
public class DBConnection {
	
	String databaseHost = "localhost";
	int port = 50000;
	String databaseName = "mydb";
	String user = "myuser";
	String password = "mypass";
	String myurl = "myurl";
	
	
	public Connection getDBConnection(){
		Connection con = null;
		try {
			 String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
			 System.out.println("VCAP_SERVICES content: " + VCAP_SERVICES);

				if (VCAP_SERVICES != null) {
					// parse the VCAP JSON structure
					BasicDBObject obj = (BasicDBObject) JSON.parse(VCAP_SERVICES);
					String thekey = null;
					Set<String> keys = obj.keySet();				
					// Look for the VCAP key that holds the SQLDB information
					for (String eachkey : keys) {				
						// Just in case the service name gets changed to lower case in the future, use toUpperCase
					System.out.println("key"+eachkey.toUpperCase());
						if (eachkey.toUpperCase().contains("SQLDB")) {
							thekey = eachkey;
						}
					}
			
					BasicDBList list = (BasicDBList) obj.get(thekey);
					obj = (BasicDBObject) list.get("0");	
					System.out.println("Service found: " + obj.get("name"));
					obj = (BasicDBObject) obj.get("credentials");
					databaseHost = (String) obj.get("host");
					databaseName = (String) obj.get("db");
					port = (Integer)obj.get("port");
					user = (String) obj.get("username");
					password = (String) obj.get("password");
					myurl = (String) obj.get("jdbcurl");
					System.out.println("databaseHost"+	databaseHost);
					System.out.println("databaseName"+	databaseName);
					System.out.println("username"+	user);
					System.out.println("password"+	password);
					System.out.println("port"+	port);
					System.out.println("jdbc url"+	myurl);
					String databaseUrl = "jdbc:db2://" + databaseHost + ":" + port + "/"
							+ databaseName;
					System.out.println("Loading the Database Driver");
					Class.forName("com.ibm.db2.jcc.DB2Driver");
					System.out.println("connect db");
					con = DriverManager.getConnection(databaseUrl, user, password);
					con.setAutoCommit(false);
				}
				else {
					System.out.println("VCAP_SERVICES is null");
					
				}
				return con;
			
		} 
		catch (SQLException e) {
			System.out.println("Error connecting to database");
			System.out.println("SQL Exception: " + e.toString());
		   return null;
		}
		
		catch (Exception e) {
			System.out.println("cann;t get connection"+e.toString());
			return null;
		} 
	}

}

package com.ibm.web.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Set;

import com.ibm.db2.jcc.DB2SimpleDataSource;
import com.ibm.nosql.json.api.BasicDBList;
import com.ibm.nosql.json.api.BasicDBObject;
import com.ibm.nosql.json.util.JSON;
public class DBConnection {
	
	String databaseHost = "localhost";
	int port = 50000;
	String databaseName = "mydb";
	String user = "myuser";
	String password = "mypass";
	String myurl = "myurl";
	
	
	public Connection getDBConnection(){
		Connection con = null;
		try {
			 String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
			 System.out.println("VCAP_SERVICES content: " + VCAP_SERVICES);

				if (VCAP_SERVICES != null) {
					// parse the VCAP JSON structure
					BasicDBObject obj = (BasicDBObject) JSON.parse(VCAP_SERVICES);
					String thekey = null;
					Set<String> keys = obj.keySet();				
					// Look for the VCAP key that holds the SQLDB information
					for (String eachkey : keys) {				
						// Just in case the service name gets changed to lower case in the future, use toUpperCase
					System.out.println("key"+eachkey.toUpperCase());
						if (eachkey.toUpperCase().contains("SQLDB")) {
							thekey = eachkey;
						}
					}
			
					BasicDBList list = (BasicDBList) obj.get(thekey);
					obj = (BasicDBObject) list.get("0");	
					System.out.println("Service found: " + obj.get("name"));
					obj = (BasicDBObject) obj.get("credentials");
					databaseHost = (String) obj.get("host");
					databaseName = (String) obj.get("db");
					port = (Integer)obj.get("port");
					user = (String) obj.get("username");
					password = (String) obj.get("password");
					myurl = (String) obj.get("jdbcurl");
					System.out.println("databaseHost"+	databaseHost);
					System.out.println("databaseName"+	databaseName);
					System.out.println("username"+	user);
					System.out.println("password"+	password);
					System.out.println("port"+	port);
					System.out.println("jdbc url"+	myurl);
					String databaseUrl = "jdbc:db2://" + databaseHost + ":" + port + "/"
							+ databaseName;
					System.out.println("Loading the Database Driver");
					Class.forName("com.ibm.db2.jcc.DB2Driver");
					System.out.println("connect db");
					con = DriverManager.getConnection(databaseUrl, user, password);
					con.setAutoCommit(false);
				}
				else {
					System.out.println("VCAP_SERVICES is null");
					
				}
				return con;
			
		} 
		catch (SQLException e) {
			System.out.println("Error connecting to database");
			System.out.println("SQL Exception: " + e.toString());
		   return null;
		}
		
		catch (Exception e) {
			System.out.println("cann;t get connection"+e.toString());
			return null;
		} 
	}

}
package com.ibm.web.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Set;

import com.ibm.db2.jcc.DB2SimpleDataSource;
import com.ibm.nosql.json.api.BasicDBList;
import com.ibm.nosql.json.api.BasicDBObject;
import com.ibm.nosql.json.util.JSON;
public class DBConnection {
	
	String databaseHost = "localhost";
	int port = 50000;
	String databaseName = "mydb";
	String user = "myuser";
	String password = "mypass";
	String myurl = "myurl";
	
	
	public Connection getDBConnection(){
		Connection con = null;
		try {
			 String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
			 System.out.println("VCAP_SERVICES content: " + VCAP_SERVICES);

				if (VCAP_SERVICES != null) {
					// parse the VCAP JSON structure
					BasicDBObject obj = (BasicDBObject) JSON.parse(VCAP_SERVICES);
					String thekey = null;
					Set<String> keys = obj.keySet();				
					// Look for the VCAP key that holds the SQLDB information
					for (String eachkey : keys) {				
						// Just in case the service name gets changed to lower case in the future, use toUpperCase
					System.out.println("key"+eachkey.toUpperCase());
						if (eachkey.toUpperCase().contains("SQLDB")) {
							thekey = eachkey;
						}
					}
			
					BasicDBList list = (BasicDBList) obj.get(thekey);
					obj = (BasicDBObject) list.get("0");	
					System.out.println("Service found: " + obj.get("name"));
					obj = (BasicDBObject) obj.get("credentials");
					databaseHost = (String) obj.get("host");
					databaseName = (String) obj.get("db");
					port = (Integer)obj.get("port");
					user = (String) obj.get("username");
					password = (String) obj.get("password");
					myurl = (String) obj.get("jdbcurl");
					System.out.println("databaseHost"+	databaseHost);
					System.out.println("databaseName"+	databaseName);
					System.out.println("username"+	user);
					System.out.println("password"+	password);
					System.out.println("port"+	port);
					System.out.println("jdbc url"+	myurl);
					String databaseUrl = "jdbc:db2://" + databaseHost + ":" + port + "/"
							+ databaseName;
					System.out.println("Loading the Database Driver");
					Class.forName("com.ibm.db2.jcc.DB2Driver");
					System.out.println("connect db");
					con = DriverManager.getConnection(databaseUrl, user, password);
					con.setAutoCommit(false);
				}
				else {
					System.out.println("VCAP_SERVICES is null");
					
				}
				return con;
			
		} 
		catch (SQLException e) {
			System.out.println("Error connecting to database");
			System.out.println("SQL Exception: " + e.toString());
		   return null;
		}
		
		catch (Exception e) {
			System.out.println("cann;t get connection"+e.toString());
			return null;
		} 
	}

}
package com.ibm.web.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Set;

import com.ibm.db2.jcc.DB2SimpleDataSource;
import com.ibm.nosql.json.api.BasicDBList;
import com.ibm.nosql.json.api.BasicDBObject;
import com.ibm.nosql.json.util.JSON;
public class DBConnection {
	
	String databaseHost = "localhost";
	int port = 50000;
	String databaseName = "mydb";
	String user = "myuser";
	String password = "mypass";
	String myurl = "myurl";
	
	
	public Connection getDBConnection(){
		Connection con = null;
		try {
			 String VCAP_SERVICES = System.getenv("VCAP_SERVICES");
			 System.out.println("VCAP_SERVICES content: " + VCAP_SERVICES);

				if (VCAP_SERVICES != null) {
					// parse the VCAP JSON structure
					BasicDBObject obj = (BasicDBObject) JSON.parse(VCAP_SERVICES);
					String thekey = null;
					Set<String> keys = obj.keySet();				
					// Look for the VCAP key that holds the SQLDB information
					for (String eachkey : keys) {				
						// Just in case the service name gets changed to lower case in the future, use toUpperCase
					System.out.println("key"+eachkey.toUpperCase());
						if (eachkey.toUpperCase().contains("SQLDB")) {
							thekey = eachkey;
						}
					}
			
					BasicDBList list = (BasicDBList) obj.get(thekey);
					obj = (BasicDBObject) list.get("0");	
					System.out.println("Service found: " + obj.get("name"));
					obj = (BasicDBObject) obj.get("credentials");
					databaseHost = (String) obj.get("host");
					databaseName = (String) obj.get("db");
					port = (Integer)obj.get("port");
					user = (String) obj.get("username");
					password = (String) obj.get("password");
					myurl = (String) obj.get("jdbcurl");
					System.out.println("databaseHost"+	databaseHost);
					System.out.println("databaseName"+	databaseName);
					System.out.println("username"+	user);
					System.out.println("password"+	password);
					System.out.println("port"+	port);
					System.out.println("jdbc url"+	myurl);
					String databaseUrl = "jdbc:db2://" + databaseHost + ":" + port + "/"
							+ databaseName;
					System.out.println("Loading the Database Driver");
					Class.forName("com.ibm.db2.jcc.DB2Driver");
					System.out.println("connect db");
					con = DriverManager.getConnection(databaseUrl, user, password);
					con.setAutoCommit(false);
				}
				else {
					System.out.println("VCAP_SERVICES is null");
					
				}
				return con;
			
		} 
		catch (SQLException e) {
			System.out.println("Error connecting to database");
			System.out.println("SQL Exception: " + e.toString());
		   return null;
		}
		
		catch (Exception e) {
			System.out.println("cann;t get connection"+e.toString());
			return null;
		} 
	}

}

Wednesday, July 23, 2014

Is bluemix good for setup a website

A static website which just shows content can easily be achieved with the Nginx buildpack mentioned above, as well as a few other options. A more dynamic website that requires code running on the server (a web 'application') is an even better use case for Bluemix because you can write your server code (in almost any language) and run it on Bluemix (with essentially endless scaling) while taking advantage of many services that might help your application (want to store data..? use a data service. Want to send emails..? use an email service, etc. etc).
You can use nginx buildpack to setup static web site. To verify this feature, try this.
  1. Create simple index.html file.
  2. Push the file contents to Bluemix with nginx buildpack.
Come from dw answer https://developer.ibm.com/answers/questions/20209/is-bluemix-good-for-setup-a-website/

Wednesday, July 16, 2014

Import the data in SQLDatabase on BlueMix

BlueMix provide lots of database solution.But some of them don;t provide directly import data feature,so you have to find some solution for that.But for SQLData base ,IBM provide a very good console for you to maintain the data on the Cloud.

1.First you need to create SQL Database service on the BlueMix.

2.Clcik the Launch like to start the SQL Database Console 
3.After Login,if you have existed csv sheet,I suggest you can use import feature to create table and import data.
4.Upload your csv file choose the comma as the Separator character 


5.Click the load button to upload your csv.,and also  we need to choose "create a new table and load" Option

6.Create the table name and name the column name for this table.
7.Click the finish button to complete the loading.

8.You can aslo check this table in the "Work with Database Objects" option.

Tuesday, July 8, 2014

PHP CRUD operation on BlueMix

When you want do to an application to initialize the database (including create table and date),I think use PHP is a quick solution to do that.I was trying to find this kind of sample,fortunate I find one in jazzHub,so you can follow it to do your mysql solution on BlueMix.

The project  url is at https://hub.jazz.net/project/andrewhujazz/PHPMySQLProject/overview.You can apply a jazzhub account to fork his application to deploy on the BlueMix,or use git clone command to clone the project on your local side.The git url is https://hub.jazz.net/git/andrewhujazz/PHPMySQLProject.

The detail function you can see below screenshot,it provide create table,insert table,drop table,

When you write code you need to notice ,when you open the mysql connection,you also need to provide port,since the port might be not default port..I list some code for your reference.

<div id="content2">
<h2>MySQL Service</h2><hr>
<b>MySQL Information</b>
<hr>
<?php
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services,true);
$mysql_config = $services_json["mysql-5.5"][0]["credentials"];
$db = $mysql_config["name"];
$host = $mysql_config["host"];
$port = $mysql_config["port"];
$username = $mysql_config["user"];
$password = $mysql_config["password"];
if ($host=="") {
echo "<b> There is no mysql service.</b><br>";
} else {
?>
MySQL DB Name : <?php echo $db ?> <br>
MySQL Host : <?php echo $host ?> <br>
MySQL Port : <?php echo $port ?> <br>
MySQL username : <?php echo $username ?> <br>
MySQL password : <?php echo "********" ?><br>
<hr>
<b> Create Table</b><br>
<?php
$conn = mysql_connect($host . ':' . $port, $username, $password);
if(! $conn ) {
 echo('Could not connect: ' . mysql_error());
}
mysql_select_db($db);
 if ($cmd=="create") {
$sql_create = 'CREATE TABLE SAMPLE (name CHAR(30), comment CHAR(255), time DATETIME)';
$retval = mysql_query($sql_create, $conn );
if(! $retval ) {
 echo('Could not create database table: ' . mysql_error() . '<br/>');
} else {
    echo "<script>alert('Created database table successfully')</script><script>window.location='mysql.php'</script>";
    }
 } ?>
<a href="mysql.php?cmd=create">[Create] </a>
<hr>
<b> Insert Data</b><br>
<?php
$sql_read = 'SELECT * FROM SAMPLE ';
$retval = mysql_query($sql_read, $conn );
if(! $retval )
{
  echo('Could not read SAMPLE table: ' . mysql_error());
}
echo "<table><tr><td>name</td><td>comment</td><td>Date</td>";
while ($dbfield = mysql_fetch_assoc($retval)) {
    echo "<tr><td>".$dbfield['name'] . '</td>';
    echo "<td>".$dbfield['comment'] . '</td/>';
    echo "<td>".$dbfield['time'] . '</td></tr>';
}
echo "</table>";
?>

<?php
if ($cmd=="insert") {
$sql_insert = 'INSERT INTO SAMPLE (name, comment, time) VALUES ( "name",   "comment", NOW() )';
$retval = mysql_query($sql_insert, $conn );
if(! $retval ) {
 echo('Could not enter data: ' . mysql_error() . '<br/>');
} else {
    echo "Entered data successfully<br/><script>window.location='mysql.php'</script>";
    }
 } ?>
<a href="mysql.php?cmd=insert">[Insert] </a>
<hr>
<b> Drop Table</b><br>
<?php
 if ($cmd=="drop") {
$sql_drop = 'DROP TABLE SAMPLE';
$retval = mysql_query($sql_drop, $conn );
if(! $retval ) {
 echo('Could not drop database table: ' . mysql_error() . '<br/>');
} else {
    echo "<script>alert('Dropped database table successfully')</script><script>window.location='mysql.php'</script>";
    }
 } ?>
<a href="mysql.php?cmd=drop">[Drop] </a>
<?php }?>
</div>

Also when you deploy your php application,you had better provide a manifest.yml,it describe the deployment info on the BlueMix.See below sample manifest.yml

---
applications:
- name: myphpsample
  memory: 128M 
  instances: 1
  host: myphpsample
  domain: ng.mybluemix.net
  buildpack: https://github.com/dmikusa-pivotal/cf-php-build-pack.git
  path: .

After deployment,you need to bind your php application on existing my sql service.

How to track the error log on BlueMix

Sometimes when we run the application or deploy the application we will meet all kinds of strange error.Is that a way to check that. I forward the answer from dw.Hope it will help you.

This is a 14 step must-gather when the app fails to stage or does not work correctly at runtime ....
1.cf logs appName --recent
2.cf events appName will reveal errors that staging sometimes won't like OOM errors or PORT not being listened on.
3.cf files appName logs/messages.log logs/staging_task.log and other log files in the logs/ directory
4.To enable trace for the Liberty server configure a traceSpecification stanza in the server.xml and push a server package.
5.If you bound any services, cf files appName logs/env.log | grep VCAP_SERVICES will give you any service connection and credential information.
6.For Liberty server configuration look at cf files appName app/.liberty/usr/servers/defaultServer/server.xml
7.cf se JBP_LOG_LEVEL DEBUG will turn on debug logs in the buildpack that can be accessed with cf files appName app/.buildpack-diagnostics/buildpack.log
8.If you need CF level trace and GUIDs etc to talk to the cloud controller via REST APIs then set the environment variable CF_TRACE to true on the command line. Syntax depends on the OS.
9.Confirm that the war/ear/jar/server-package file works on standalone liberty
10.Look at the VCAP_SERVICES environment variable information from the ace tool.
11.If you don't have access to the logs then do a cf push from one window and cf tail logs in the other command window.
12.Push using the open source liberty Buildpack with the -b option. cf push appName -p /absolute/path/my.war -b https://github.com/cloudfoundry/ibm-websphere-liberty-buildpack.git
13.Fork the OSS buildpack and push it as an application on Bluemix. This is called buildpack as an app and enables you work with your fork of the BP on BlueMix. Details on this later.
14.If ALL fails then try pushing to a CF installed locally via bosh-lite or push to an alternate environment
Notes
■REPLACE appName with the name of your app
■There are a number of ways to push an application to BlueMix i.e. via 1. command line 2. eclipse & 3. JazzHub. The best way to debug, is by pushing the built artifact (war/ear/jar/server-package) via the cf command line since the command line gives complete control on file navigation and insight into CF.
■For other troubleshooting tips checkout https://www.ng.bluemix.net/docs/FAQ.jsp

Sunday, July 6, 2014

Open Rule Desiner

IBM announced the BlueMix pricing plan, the beginner you can have a one month free trial .The idea of BlueMix is that a developer can create an application very quickly and get it deployed without having to go through the usual rigmarole of enterprise app deployment which can take weeks or months.
       Today I will talk about the rule service,IBM have public the rule designer for free to use.The only thing you need to just  download the  an Eclipse Helios 3.6.2 version. Decompress the Eclipse IDE archive,the Add Repository dialog, enter the following repository details.
Name: Rules Service Rule Designer
Location: http://rd-851-installer.ng.bluemix.net/

When you launch the eclipse you should see the below UI.

You can choose one of  two ruleset mode.

What is the difference of Classic rule engine and Decision engine
Main improvements for the Rule Execution Server are coming from the next generation engine called  Decision Engine (DE) which is now available for distributed.
Thanks to its ability to natively compile ruleflows and decision tables, and to generate Java bytecode in the ruleset archive (DE Java bytecode), Decision Engine offers Major Enhancements, and impressive performance over previous releases :

DE is much more scalable than CRE
With HTDS REST and SOAP, the performance are more stable when the number of concurrent execution is raising.
With Decision Engine you :
Need less JVM tuning than CRE (no extra JIT configuration)
Can deploy the Rule Execution Server (RES) on machines/devices with limited resources, so enabling new use cases or application architecture.

If you are a rule newbie,you can reference the http://pic.dhe.ibm.com/infocenter/dmanager/v8r5/index.jsp to learn more abut usage.