Thursday, May 29, 2014

How do I learn BlueMix

I have wroten my blog for sometime.Today I will conclude my leaning way on BlueMix.If you are a newbie you can draw lesson from me.The below are my steps to learn BlueMix.

1.First you need to understand Paas concept before you started BlueMix.I strongly recommand you to read "Programming for PaaS" book.




Whether you’re an entrepreneur or part of a large enterprise development team, this book shows you how PaaS can help you focus on innovative applications, rather than spend your time worrying about technical operations.
  • Track the cloud’s evolution from IaaS and DevOps to PaaS
  • Learn how PaaS combines the simplicity of shared web hosting with the control of dedicated hosting
  • Explore the benefits of both portable and non-portable PaaS options
  • Apply best practices for moving legacy apps to PaaS—and understand the challenges involved
  • Write new applications for PaaS from scratch with RESTful meta-services
  • Use PaaS to build mobile apps with backend services that scale
  • Examine the core services that each major provider currently offers
  • Learn the situations in which PaaS might not be advantageous
2.Register an account in https://ace.ng.bluemix.net/,now it is in beta status free to use by now.You can follow the offical document(lots of sample) to push your application to the BlueMix.You can try thee way to deploy it on the BlueMix.There are lots of opensource you might need to learn.I post some of links for your reference.

OAuth
---------
http://oauth.net/2/

https://developers.google.com/accounts/docs/OAuth2

OData
---------
http://www.odata.org/developers/articles/

http://msdn.microsoft.com/en-in/data/gg601462.aspx

http://jaydata.org/tutorials/how-to-build-a-simple-odata-based-ajax-application


JSON
-------
http://www.w3schools.com/json/

http://www.json.org/js.html

PostgreSQL
---------------
Bluemix link --> http://ng.w3.bluemix.net/docs/Services/PostgreSQL/Index.html

http://www.postgresql.org/docs/8.0/static/tutorial.html

http://www.postgresql.org/files/documentation/pdf/7.2/tutorial-7.2-US.pdf


PHP Tutorial
----------------
http://www.w3schools.com/php/

http://www.php.net/manual/en/tutorial.php


Python Tutorial
-------------------
http://www.python.org/about/gettingstarted/

http://www.php.net/manual/en/tutorial.php


MQTT
--------
http://w3.itso.ibm.com/redpieces/abstracts/sg248054.html

http://pic.dhe.ibm.com/infocenter/wmqv7/v7r1/index.jsp?topic=%2Fcom.ibm.mq.doc%2Ftt60100_.htm

http://pic.dhe.ibm.com/infocenter/wmqv7/v7r5/index.jsp?topic=%2Fcom.ibm.mm.tc.doc%2Ftc10140_.htm

http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/index.jsp?topic=%2Fcom.ibm.mq.amqtat.doc%2Ftt20026_.htm

http://www.hivemq.com/build-javascript-mqtt-web-application/

Ruby on Rails
-----------------
http://ruby.railstutorial.org/

http://ruby.railstutorial.org/ruby-on-rails-tutorial-book


RabbitMQ
-------------
Bluemix link -->http://ng.w3.bluemix.net/docs/Services/RabbitMQ/Index.html

http://www.rabbitmq.com/getstarted.html

http://www.rabbitmq.com/tutorials/tutorial-one-java.html


MongoDB
--------------
http://docs.mongodb.org/manual/tutorial/getting-started/

http://tour.mongohq.com/Mongo?k=Mongodb%20php&gclid=CLLkqsWojLwCFUom4god1gMA6w

https://education.mongodb.com/courses/10gen/M101J/2014_January/courseware/Week_1_Introduction/5254637ee2d4231cc6083fd5/


Node JS
----------
http://www.nodebeginner.org/

http://nodejs.org/docs/v0.4.1/api/modules.html

http://www.thinkster.io/pick/GtaQ0oMGIl/a-better-way-to-learn-angularjs

http://docs.angularjs.org/guide/concepts#directive

Cloudant
http://www.cloudant.com/

3.Practitioners should start with a quick grasp of CloudFounry.Esp for command line tools,most of your application you have to use command line tools to do that.
Cloudfoundry introduction from Pivotal - http://www.cloudfoundry.com/use
Cloudfoundry github repo - https://github.com/cloudfoundry
Cloudfoundry developer's mailing list on Google Groups - https://groups.google.com/a/cloudfoundry.org/forum/#!forum/vcap-dev

4.Try to develop or create your application on BlueMix.Like create a blog,rss site,phpAdmin etc.If you want to deploy othere language like php,perl you might need to use Buildpacks.
Buildpacks provide framework and runtime support for your applications. Buildpacks typically examine user-provided artifacts to determine what dependencies to download and how to configure applications to communicate with bound services.

5.If you have questions about BlueMix usage ,you can visit the Bluemix forum
This forum is hosted by IBM.You can ask questions and get experienced IBM staff support.

If you are an IBM staff,you can subscibe the email list in below address.
 http://webconf.ibm.com/mail/CloudOE-dev


Tuesday, May 27, 2014

Use Eclipse to deploy node.js application on BlueMix

IBM has release a plug-in called BlueMix for Eclipse Kepler Beta.You can see the detail in the link. It said not only support java liberty and also node.js deployment.I wrote the blog about how to use eclipse to deploy liberty demo to BlueMix.But how about node.js? There is little document about these things.I saw the internal email has this kind of information,so I forward here if you are interested in.

Creating a Node.js application for BlueMix from scratch
Summary of features covered:
- The ability to add JavaScript project to BlueMix
- Auto generation of required files to enable new projects to quickly be added to BlueMix
- Easily fill in the cloud deployment information via wizards
- The package.json file is parsed to determine which JavaScript entry file to run
- Easily allow the user to visit the URL of the project once it's on BlueMix
- Republish a project (that is, make a change and have it reflected without removing the application and then adding it back again)
- Allow the user to update existing cloud deployment information via the Applications Editor page
- Ability to remove the application from BlueMix

1. Create a JavaScript project in Eclipse. Let's call it HelloWorldNode

2. This project is empty and the user cannot add this application to BlueMix, until a facet is added to this project
Right click on the HelloWordlNode project > Properties > Project Facets

3.Click on "Convert to faceted form..." and select "Node.js Application"


4. Press OK
2 files will be generated if they don't already exist:
1. app.js - a skeleton entry JavaScript file
2. package.json - defines what the starting JavaScript should be, dependencies, and more. This is not cloud specific and is standard in Node.js applications

5.Right click on the BlueMix server > Add and Remove.HelloWorldNode to the right panel and click finish.

6. the deployment information wizards will now come up. This will enable the user to specify their application name and buildpack URL They can also choose the "Save to manifest file" option if they would like to save the properties that are being set by this wizard

7.Feature: the subdomain, domain, deployed URL, and memory limit can be set .If you don;t want to choose service you can pass the next wizard.

8 When you finish most of setting,you can see the console log.

Checking application - HelloWorldNode
Generating application archive
Creating application in Cloud Foundry server
Pushing application to Cloud Foundry server
Application successfully pushed to Cloud Foundry server
Staging application

-----> Downloaded app package (4.0K)
-----> Buildpack Version: 20140522-0208
-----> Resolving node version by IBM

       PRO TIP: Specify a node version in package.json

-----> Defaulting to latest stable node: 0.10.21
-----> Installing IBM SDK for Node.js from admin cache
-----> Read service config: MonitoringAndAnalytics.json at the start
-----> Read service config: SQLDB_BLUAcceleration.json at the start
-----> Writing a custom .npmrc to circumvent npm bugs
-----> Installing dependencies
       npm WARN package.json insert-title-here@0.0.1 No repository field.
       npm WARN package.json insert-title-here@0.0.1 No README data
-----> Cleaning up node-gyp and npm artifacts
-----> No Procfile found; Adding npm start to new Procfile
-----> Building runtime environment
-----> Read service config: MonitoringAndAnalytics.json at the end
-----> Read service config: SQLDB_BLUAcceleration.json at the end

9.Right click on the project in the Servers View > Open Home Page  you can see your application via the browser.


10.If you change the app.js code,you need to re-publish your application in the BlueMix server.

Monday, May 26, 2014

Cloudnant demo work on BlueMix

Last blog I discussed with Cloudant,but how do we use BlueMix application to visit Cloudant ? On the official site,it doesn't provide tutorial for that.Today I will show a node.js demo for Cloudant on BlueMix.Since node.js is one of my favorite language,also it provide  a ton of tools that make developing on CouchDB / Cloudant with Node.js effortless.You can read this blog to learn more about it.Finally I decide to choose express,Nano as my application library.I have put my code(you can use git to check out this url) at the jazz hub if you want to try it.

Installing the Required Modules

Express framework is required to run this app, to install the express framework, open the command prompt/shell and type the below command. The “–g” option simply means the module will be installed globally so that for each project we don’t need to install express separately.

    npm install –g express
    npm install nano (To install nano module)

Follow the Below Steps to Setup Our Project

After installing nodejs, execute the following commands in order-

    npm install express –g
    npm install jade –g
    express couchNano
    cd couchNano
    npm install nano
    npm link express
    npm link jade
    node app.js //to run the app

And go to browser (any browser) and type below in address bar http://localhost:3000. And press enter if you get the “welcome to express” page you have success created the basic structure required for this app.

Change or create  the createdb.js,index.jade,layout.jade,app.js.You can see the detail code at
https://hub.jazz.net/project/blackwhites/cloudant/overview.

In the app.js there is a piece of code you might need to config on your side .

var nano = require('nano')('https://username:password@yourdomain.cloudant.com:443');
/*Specify the database to use, so that we don't have to specify everytime*/
var db     = nano.use('yourdb')


You need to enter the correct username,password and your cloudant host address.Also you need to make sure you have create your db before in your hosted cloudant doamin.

After finish your code,you need to create a package.json file to add your node.js  dependency.

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.4",
    "jade": "*",
"nano": "*.*"
  }
}

Finish all the setting,you can open node.js command in your project folder  to use npm install command to install node.js module.After that use node app.js to run your sample.

Open the browser and use localhost:3000 to visit,Here I add Contacts as the sample


You can see the successful info after you submit the contacts info.

You can check the data in the your online Cloudant db.

After pass the local testing,you need to write manifest.yml to deploy on the BlueMix.You can see my sample file.
---
applications:
- name: cludanttest
  memory: 256M
  instances: 1
  host: cludanttest
  domain:ng.bluemix.net
  path: .
  command: node app.js

You can use cf push command to push your application to the BlueMix.

Friday, May 23, 2014

DBaas on the BlueMix

I think most of person might not be familar with DBaas concept.Actually it is a cloud computing service model that provides users with some form of access to a database without the need for setting up physical hardware, installing software or configuring for performance. All of the administrative tasks and maintenance are taken care of by the service provider so that all the user or application owner needs to do is use the database. Of course, if the customer opts for more control over the database, this option is available and may vary depending on the provider.

So what dbaas service provided on the BlueMix? Let's have a look.Actually BlueMix not only support db2 also support most open source db.

I think some of them might not be famliar with every db list above.Below is a video will help you to understand  qucikly.The video name is 9 Databases in 45 Minutes,you can also find it in the youtube.

 
Stricly only Cloudant can be called DBaas.Becuase Dbaas will have below common characteristics.

On-demand:
 Users can easily opt-in and out from database-as-a-service. They do not need to configure or install any hardware or software to properly administer their database because these are provided by the DBaaS provider as part of their service.
Self-Service Console:
 The DBaaS provider should give users a self-service database management console so they can easily configure, provision, scale, and monitor database clusters, nodes, and instances according to their needs.Like mysql,mongodb on bluxmi doesn;t provide the management console for user to maintain these db,so we might need some work around way to do that.I will write some solutions in future blogs.
Pay-Per-Use Pricing Model:
The DBaaS provider should use a pay-per-use model so users only pay for what they used. Users should not pay for any upfront fees or one-time costs.
Ease of Deployment: Because the hardware, software, and database are readily available and on-demand, deploying your application to the DBaaS provider should be extremely fast.
Service Level Agreement:
 The DBaaS provider should provide a Service Level Agreement (SLA) that details how the DBaaS service is delivered, as well addressing issues such as uptime, backup, security, and others issues similar to the DBaaS Requirements mentioned above.
In essence, DBaaS providers should be easy to work with and simple to utilize. The service is designed so non-technical database professionals can easily leverage powerful database functionalities anytime and anywhere.

Cloudant as database-as-a-service (DBaaS) provider that enables developers to easily and quickly create next generation mobile and web apps.  February 2014, IBM announced an agreement to acquire Cloudant,I believe it will integrate IBM product in future.

Now Let's have a quick to see Cloudant's feature.The regiesteration is very easy.Also the whole operationis very easy and understood.

it a "document database" - i.e. it is all about storing documents which consist of sets of fields in a JSON document against a key. There is no schema - a document can consist of any JSON structure - there is no requirement that the same fields be present in each document unlike rows in a RDBMS.Tomorrow I will tell you how to setup a application with Cloudant on BlueMix.


Wednesday, May 21, 2014

Cloud IDE IBM DevOps Services

IBM DevOps Services(IDS) is a place where you can collaborate with others to develop, track, plan and deploy software.

The below are some featues about  IDS.See below screenshot.

  • DevOps Solution in the cloud for building mobile and cloud applications 
  • Integrated task tracking, agile planning, source control with auto deploy
  • Use your favorite tools or work from the Web IDE
  • Hosted Jazz SCM or Git or link to GitHub
  • Support Public and private projects
  • Built on SoftLayer
  • Mobile quality and application performance monitoring
  • Continuous Integration and Deployment with Jenkins and UrbanCode
  • Push your applications to BlueMix
By now it is totally free and asl you need just to register an IBM id to use it.

I will show somescreenshot to demostrate its feature.

a)Create Project

 You can choose different options to create your project. Private,Public,use java scm or git etc.
 b) Online code edit

c)Trace your work
d)Build and Deploy
e)Invite others to join your project
if you have any  questions you can go to this fourm to ask your problem.Also the offical site has lots of  tourial ,you can follow it and learn it.

Tuesday, May 20, 2014

Quick learn Cloud Foundry command line Tool

In the previous post,I referred the cf tools.This command line interface, or CLI, allows users to do almost everything necessary to deploy apps to Cloud Foundry, bind services to them, look at log files, and so on. If you are a beginner ,I suggest  you download the latest release version 6 and install it and  have a try.
installation:
(1) git clone https://github.com/cloudfoundry/cli
(2) git checkout v6.0.0
(3) run bin/build
(4)the binary build will be  be built into the the out/cf

Also you can directly download the release version  package based on your OS  from below url .
 https://github.com/cloudfoundry/cli/releases

Below are some useful commands.
1. cf login

cf login -a https://api.ng.bluemix.net

It will prompt you to enter the email and password to login into the CloudFoundry.Upon successful login, cf v6 saves a config.json file containing your API endpoint, organization, space values, and access token.

2.cf push

cf push APP [-b URL] [-c COMMAND] [-d DOMAIN] [-i NUM_INSTANCES] [-m MEMORY] [-n HOST] [-p PATH] [-s STACK] [--no-hostname] [--no-route] [--no-start]

Here I suggest you to use the manifests.yml to do the automate deployment. Application manifests tell cf push what to do with applications. This includes everything from how many instances to create and how much memory to allocate to what services applications should use.The detail you can reference the below link.You can learn more detail from http://docs.cloudfoundry.org/devguide/deploy-apps/manifest.html

3. cf apps

Check on the health of the app you pushed

4.cf logs XXX --recently

List the specified app logs dump

5. cf service
List all the services you have created

6. cf create-service
You can create a managed service instance with the command: cf create-service SERVICE PLAN SERVICE_INSTANCE
cf create-service takes the following required arguments:
  • SERVICE: The service you choose.
  • PLAN: Service plans are a way for providers to offer varying levels of resources or features for the same service.
  • SERVICE_INSTANCE: A name you provide for your service instance. This is an alias for the instance which is meaningful to you. Use any series of alpha-numeric characters, hyphens (-), and underscores (_). You can rename the instance at any time.
Following this step, your managed service instance is provisioned:

$ cf create-service rabbitmq small-plan my_rabbitmq

Notes: SERVICE,PLAN you get from cf marketplace command

7.cf bind-service
You can bind a service to an application with the command cf bind-service APPLICATION SERVICE_INSTANCE. Example:

$ cf bind-service my_app example_service

8.cf files XXX logs/env.log

XXX stands for your app
show the specified app  detail logs.Sometimes it is useful to check the log through the command.


8.cf marketplace

List all the support service and plans in this platform


9. cf files XXX

List deployed app file structure. You can even use like cf files MyNodeSample app/ to list the detail folder content.

There is help inside the CLI using cf help, which prints out the list of commands and a quick summary of each. You can also get additional help for a particular command using cf help <command>

Monday, May 19, 2014

Three ways to deploy your applications on BlueMix

If you are a newbie,you might not be clearly all three ways to deploy your applications on BlueMix. Today I will talk about these three tools a little bit.
Developers have the freedom to choose the development tools that work best for them. Developers don’t always want to work with the same tool sets and BlueMix provides several options, including the following:

Command line: The Cloud Foundry (CF) command line provides integration for developers that prefer coding without an integrated development environment (IDE). This is also helpful for developing automation scripts with BlueMix. The CF application programming interfaces (APIs) can be integrated with multiple languages, frameworks and services.

BlueMix for Eclipse Kepler Beta: Since Eclipse is widely used by developers, they can continue to use the tools with which they are comfortable.This plug-in expose some of the unique features of the Liberty buildpack such as deploying a Liberty packaged server. In addition, support for deploying node.js applications allows you to target your JavaScript project, and then deploy and run your server side JavaScript application in the Cloud.

IDS(IBM DevOps Services): The cloud-based software development service(the former name is jazz hub) is based on IBM's software development tool Rational Team Concert.Developers can work with the IDS using web IDE to edit the code online and  provide  automatically deployment to BlueMix . It also provide integration to several source control management (SCM) systems like Git, GitHub and Jazz SCM.

I will blog  three tools details in the next few days.

Sunday, May 18, 2014

How do you choose your PaaS?

Platform as a Service (PaaS) is a cloud model designed for software developers that streamlines the development process by shifting specific aspects of systems management to the service provider. PaaS is used to develop web and mobile applications using components that are pre-configured and maintained by the service provider, including programming languages, application servers and databases.


Today I will list some popular PAAS vendors for your reference.

BlueMix
BlueMix is an implementation of IBM’s Open Cloud Architecture, leveraging Cloud Foundry to enable developers to rapidly build, deploy, and manage their cloud applications, while tapping a growing ecosystem of available services and runtime frameworks. IBM will provide services and runtimes into the ecosystem based on our extensive software portfolio.It offically support Liberty for Java™,Node.js,Ruby on Rails,Ruby Sinatra.Since itis built on top of Cloud Foundry and you can add support for languages or frameworks not supported in Cloud Foundry by default.Now it is in beta

Heroku 
Heroku was acquired by Salesforce.com in 2010. one of the first cloud platforms, has been in development since June 2007, when it supported only the Ruby programming language, but has since added support for Java, Node.js, Scala, Clojure and Python and (undocumented) PHP and Perl. The base operating system is Debian or, in the newest stack, the Debian-based UbuntuHeroku is the leading platform as a service in the world and supports Ruby, Java, Python, Scala, Clojure, and Node.js. Deploying an app is simple and easy.


Red Hat OpenShift
Red Hat OpenShift is based on open source applications and offers a wide variety of languages, databases and components. The PaaS is highly customizable and offered in three forms: OpenShift Online (a cloud-based hosting service), OpenShift Enterprise (a private PaaS that runs in your data center) and OpenShift Origin (the open source application hosting platform). OpenShift automates system administration tasks such as virtual server provisioning, configuration and scaling and supports git repositories for code management.

Google App Engine
Google App Engine is designed for distributed web applications and developers using Java, Python, PHP and Go. The Java environment supports other languages that make use of the JRE and there is a SDK for each of the four main supported languages as well as a plugin for Eclipse. The PaaS offers managed infrastructure and runtime environments that are guaranteed to scale, but only if the applications fit the restrictions of Google App Engine. The Datastore, a transactional, schema-less data store based on key-value pairs, handles the complex management of data that's accessible to multiple machine instances. Programming languages are limited to Java, Python, Go and PHP.

AppFog
AppFog is a multi-language, multi-framework PaaS that's a good option for multi-cloud deployments, including private clouds. AppFog supports Java, Ruby, PHP, Python, Node, Scala and Erlang and offers MySQL, PostgreSQL, Redis and RabbitMQ along with third party add-on services. It can be used as a DaaS with ClearDB, MongoHQ, MongoLab, Redis Cloud and Xeround. AppFog is based on the open source Cloud Foundry platform and supports Git, SVN and Mercurial for code management.

Windows Azure Cloud Services

Within Windows Azure, Microsoft is blurring the lines between IaaS and PaaS. Windows Azure Cloud Services supports .NET, Node.js, PHP, Python, Java and Ruby. In addition to software development kits, developers can use Visual Studio for creating and deploying applications. Developers can choose between a SQL Database, Tables and Blobs when it comes to persistent storage. Applications are administered through the Windows Azure dashboard or through a command line interface.


Amazon AWS

Although Amazon Web Services is primarily an IaaS, many of the services available in AWS are comparable to PaaS offerings. You can use the platform services available in AWS without having to create or maintain your own application servers. AWS readily supports Java, Python, Ruby, Perl and other languages. Oracle, MySQL and SQL Server can be set up and managed, but AWS offers RDS web service as well, which eliminates database administration tasks. Developers can take advantage of Amazon Elastic Beanstalk for automatic load balancing, auto-scaling, and application health monitoring

force.com
Force.com is a Platform as a Service (PaaS) product designed to simplify the development and deployment of cloud-based applications and websites. Developers can create apps and websites through the cloud IDE (integrated development environment) and deploy them quickly to Force.com’s multi-tenant servers.

Also there is a good site http://www.paasify.it/vendors ,you can choose your PAAS based on the predefined search condition.
Also it is very cool to know all kinds of PAAS feature and status.Enjoy it.



RabbitMQ deployment on BlueMix

RabbitMQ is open source message broker software (sometimes called message-oriented middleware) that implements the Advanced Message Queuing Protocol (AMQP). The RabbitMQ server is written in the Erlang programming language and is built on the Open Telecom Platform framework for clustering and failover. Client libraries to interface with the broker are available for all major programming languages.RabbitMQ can run all major operation systems (for example, Windows, Linux, MacOS) and supports a huge number of developer platforms (for example, Java, Ruby, Python, .NET, Node.JS, and etc).

Today I will talk about how to use node.js or jave to send message using RabbitMQ on the BlueMix.Let's get started.

1.Node.js

a)Firstly, you need to create a new RabbitMQ service instance with the cf create-service command. Type the following command at terminal:

cf login -a https://api.ng.bluemix.net
cf create-service rabbitmq 100 rabbitmq-test

b)Create a manifest.yml,it will describe the deployment strcture on BlueMix.The service name should be "rabbitmq-test" you created before.
applications:
- services:
  - rabbitmq-test
  host: RabbitMQ
  disk: 1024M
  name: RabbitMQ
  command: node app.js
  path: .
  domain: ng.bluemix.net
  instances: 1
  memory: 128M


Notes: Pls make sure the host name is not taken by others,otherwise the deployment will report error.You have to change other name to instead of it.
c) Since our command point the start node from app.js,so we need to create app.js file.You can copy below content into your files.

var http = require('http');
var amqp = require('amqp');

if (process.env.VCAP_SERVICES) {
  var env = JSON.parse(process.env.VCAP_SERVICES);
  var credentials = env['rabbitmq-2.8'][0]['credentials'];
} else {
  var credentials = {"url": "amqp://user1:secret@localhost:5672/vhost"}
}

var port = (process.env.VCAP_APP_PORT || 1337);
var host = (process.env.VCAP_APP_HOST || '0.0.0.0');

http.createServer(function(req, res) {
 
  res.writeHead(200, {'Content-Type': 'text/plain'});

  var conn = amqp.createConnection({url: credentials.url});

  conn.on('ready', function() {
    var exchange = conn.exchange('test-event', {type: 'fanout'});
    conn.queue('test-event-queue', function(q) {
      q.bind(exchange, '');
      q.subscribe(function(json) {
        res.end("Fetched message: " + json.body);
        conn.end();
      });
   
      exchange.publish('test-event-queue', {'body': 'Hello, world!'} );
    });
  }); 

}).listen(port, host);

d) Create a package.json.
This text file contains all the information about the project, like project path, dependencies, author name, tags, bug tracking info etc.. To create a package.json run npm init command from the root folder. It will ask series of questions and finally it will create package.json file.

Our package.json file will look like this.

{
  "version":"1.0.0",
  "scripts":{"start":"node app.js"},
  "dependencies":{"amqp":"*"},
  "name":"hellorabbitmq",
  "description":"This is a Bluemix demo"
}
Notes:
You need to add dependencies amqp,it will automatic download the node module when you deploy to the BlueMix.

e) use cf push command to deploy Node application to the BlueMix.You can see below sucessfule info.

1 of 1 instances running

App started

Showing health and status for app RabbitMQ in org gyyuan@cn.ibm.com / space dev
as XXX@XXX...
OK

requested state: started
instances: 1/1
usage: 128M x 1 instances
urls: RabbitMQ..ng.bluemix.net

     state     since                    cpu    memory          disk
#0   running   2014-05-18 11:26:27 PM   0.0%   30.6M of 128M   21.8M of 1G
f) Open the browser and luanch the url http://rabbitmq.ng.bluemix.net ,you can see the below screenshot.It means your deployment sucessfule.


2. Java 

In ordet to quick to demostrate the java ability,  I decied to use servlet to show the sending message to RabbitMQ result .Also I will use java liberty as my runtime enviorment.If you have no experience for that you should read my previous post "How to use eclipse to develop liberty java application to BlueMix"

a.Create a dynamic web project named RabbitMQTest. Download below  two libs and copy to WEB_inf lib folder.
rabbitmq-client.jar  
cloudfoundry-runtime-0.7.1.jar
get it from http://www.java2s.com/Code/Jar/c/Downloadcloudfoundryruntime071jar.htm


b) Create a java package named com.ibm.bluemix,and create a servlet class named RabbitMq.The detail code you can see below

package com.ibm.bluemix;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cloudfoundry.runtime.env.CloudEnvironment;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Servlet implementation class RabbitMq
 */
@WebServlet("/RabbitMq")
public class RabbitMq extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
    private final static String QUEUE_NAME = "hello";
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RabbitMq() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         PrintWriter out = response.getWriter();
            try{
              String connURL = getServiceInfo();
              ConnectionFactory factory = new ConnectionFactory();
              factory.setUri(connURL);
              Connection connection = factory.newConnection();
              Channel channel = connection.createChannel();

              channel.queueDeclare(QUEUE_NAME, false, false, false, null);
              String message = "Hello World!";
              channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
              out.println(" [x] Sent '" + message + "'");

              channel.close();
              connection.close();

              out.println( "Successful" );
            }catch(Exception e){
              out.println( "Error running query: " + e.getMessage() );
              e.printStackTrace();
            }
    }
   
    public String getServiceInfo() throws Exception {
        CloudEnvironment environment = new CloudEnvironment();
        List<Map<String, Object>> services= environment.getServices();
        List<Map<String, Object>> matchedServices = new ArrayList();
        List<String> listlabels=new ArrayList();
        listlabels.add("rabbitmq-2.8");
        for (Map service : services) {
          if ( listlabels.contains(service.get("label"))) {
              System.out.println("we get match service");
            matchedServices.add(service);
          }else{
              System.out.println("service name"+service.get("label"));
          }
        }
        if (  matchedServices.size() == 0 ) {
            throw new Exception( "No RabbitMQ service is bund to this app!!" );
        }

        Map credential = (Map)( matchedServices.get(0)).get( "credentials" );
   
        return (String)credential.get( "url" );
      }

}

Notes:
Here getServiceInfo() method will include all the service deployed on the BlueMix,so we need to filter the service which only used the rabbitmq-2.8.You can use this way to filter other service. The service detail parameter you can check your application run time enviroment variable.


c)Create an IBM BlueMix server like below screenshot.
d) Fill the credential info and use validate account to connect remote BlueMix env,
e)When your BlueMix server is started,you can add the RabbitMQTest project to the server,in the launch deployment wizard,you need to enter the deploy host name and application name etc info.



f) Choose the rabbitMQ service "rabbitmq-test"we created before .
g)You should see the console some logs.If you see below logs,it means your deployment is successful.

Checking application - RabbitMQTest
Generating application archive
Creating application in Cloud Foundry server
Pushing application to Cloud Foundry server
Application successfully pushed to Cloud Foundry server

h) Login into the BlueMix website and click the Dashboard tab and you can see your application is not started.Click the start button to start the application.

i) After started and launch the browser and open the url  rabbitmqtest.ng.bluemix.net/RabbitMq, you should see the below screenshot.
Notes: /RabbitMq part url  is defined in the RabbitMq servlet annations.
@WebServlet("/RabbitMq")

Now all are done.Enjoy the node.js and java integration with RabbitMQ.

Friday, May 16, 2014

Ten minutes to create a node.js based album on BlueMix (Part Two)

This part I will step by step to show how to write my album application.You can download my code from here.If you don;t have jazz hub account,pls register one and use your IBM id to login on .

1.Create a project album use the express project as the template to generate project structure.Also create image folder under the public folder.Create a car folder under the image folder.
2.In order to control my UI easily,I decide to use the bootstrap.Download it from the official site.Unzip the package and put all the css,js folder including files under the public folder. You should see the below structure generated.



3.Modify layout.jade under the views folder.You can copy the below code to this file.

doctype html
html
    head
        title= title
        link(rel='stylesheet', href='/stylesheets/style.css')
        link(rel='stylesheet', href='/stylesheets/bootstrap.min.css')
        link(rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css")
        link(rel="stylesheet" href="/stylesheets/bootstrap-image-gallery.min.css")
    body(style='background:black')
        div(class="navbar navbar-inverse navbar-fixed-top" )
            div(class='container')
                div(class='navbar-header')
                        span(class='sr-only')='Toggle navigation'
                        span(class='icon-bar')
                        span(class='icon-bar')
                        span(class='icon-bar')
                    a(class='navbar-brand' href='#')='My tesla'
                div(class='collapse navbar-collapse' style='height: 1px;')                
       

        block content
        script(src='http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js')
        script(src='/bootstrap.js')
        script(src="http://blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js")
        script(src="/bootstrap-image-gallery.min.js")

4.Change index.js under the routes folder.Copy below code to this file.

var fs = require('fs');
exports.index = function(req, res){
 
 var files = fs.readdirSync('public/images/car');
  res.render('index', { title: 'My  car',imgs:files });
};

5.Change index.jade under the views folder.Copy below code to this file
extends layout
block content
    div(style='height:210px')
        for img in imgs
            a(href='images/car/'+img title=img data-gallery)
                img(src='images/baby/'+img  class="img-thumbnail" style='width:140px;height:140px;margin:5px' )


6.put some car pictures in the car folders.Run the app.js in the eclipse and open the browser and use http://localhost:3000 to visit my application,you can see my album is generated.


7.In order to deploy to the BlueMix,I need to create two files manifest.yml,package.json.
a)manifest.yml it defines the deploy settings on BlueMix.
applications:
- host: node-album
  disk: 1024M
  name: node-album
  command: node app.js
  path: .
  domain: ng.bluemix.net
  instances: 1
  memory: 128M

Notes:
If you don;t know how to write the manifest.yml,you can create a sample node.js application on the BlueMix, download the sample package,it will ship this file.
b)package.json It defines the node dependencies module,so when you deploy node.js application,the buildpack will automatic download the node module from this file.

{
  "name": "NodeAlbum",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
   "dependencies": {
    "express": "3.2.6",
    "jade": "*"
  }
}

8. Deploy to the BlueMix
After review the project,I found some files/folder are  not necessary when you  deploy to the BlueMix.Like .settings,node_modules. We can delete these two folders.
Next we can use below cf command to deploy it on the BlueMix.
cf api https://api.ng.bluemix.net

After login into the bluemix,you can directly use cf push command.Pls make sure the application host name is not occupied by others.

cf push

Now our node.js demo is completed deployed on to the BlueMix.


Ten minutes to create a node.js based album on BlueMix (Part One)

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.Now most paas support Node.js runtime env.Node.js has now became the most popular choice for building Real-time Web Applications since it’s first release on May 27, 2009.Now BlueMix host nodejs for developer to use.Today I will talk about how to write  my albumn application based on node.js and deploy on the bluemix.

Setup Node.js IDE

If you are a java developer, I recommend you to use Eclipse. Nodeclipse plug-in is free open-source software released every month and it became #1 in Eclipse Top 10 NEW Plugins for 2013.You can install it through the eclipse(http://www.nodeclipse.org/updates).You can also download the node.js eclipse version from this link.When you finish the plug-in installation,you should see the below screenshot.


Now we will build the app, we'll use the Express.js framework ,use nodeeclipse we can easily to create a sample project for that.Here we choose jade as our template engine.

When you click the finish button,it will automatic download the express,jade module and also create express project structure.

Choose the app.js and right click the menu and run as node application.You will see below screenshot.



Notes: there is a issue in layout.jade.You need to manually change it.
doctype 5  //you need to change doctype htnl
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

Next part  I will focus on how to write a node.js application with bootstrap to create my Album.



Wednesday, May 14, 2014

Is that possible to manage the Mongo data on BlueMix ?

Most applications need db support.Sometimes people we need client tools to maintain these db structure and data.In local environment,we can install db client tools to control these db,but how about BlueMix ? After some research I found IBM only provide SQLDB(DB2) Console to manage SQLDB. For other db we might have use own way to provide it.The next part I will introduce how to maintain the mongo db on the BlueMix.

After some research,I decide to use RockMongo.It is a MongoDB administration tool, written in PHP5, is Best in PHP world, more like PHPMyAdmin.You can download it from http://rockmongo.com/downloads.

Since it used PHP and Mongo db,when we deploy this app to the BlueMix,there are some steps we need to do.

1.Unzip the download package to specified folder. For exmaple c:\rockmongo
2.Create  a manifest.yml in the c:\rockmongo.The manifest document has captured all of the configuration that we entered above for the application push into a description of the application deployment. Once you have a manifest.yml file, you can modify it however you would like.Copy the below content to this manifest.yml

---
applications:
- name: php-mongoAdmin
  memory: 128M
  instances: 1
  path: .
  buildpack:  https://github.com/dmikusa-pivotal/cf-php-build-pack

3.Since this php application need to use mongo module,so you need to included php_mongo in the list of extensions in the buildpack options file. This is documented here:
https://github.com/dmikusa-pivotal/cf-php-build-pack/blob/master/docs/config.md#php-extensions

So we need to create a folder named .bp-config under your project and create a options.json file which will include php extension ,so when you install php buildpack it will install the dependency based on this  options.json file.
4.Copy the below content to the options.json

{
  "WEB_SERVER": "httpd",
  "PHP_EXTENSIONS": ["bz2", "zlib", "curl", "mcrypt", "mongo"]
}

5.When we config rockmongo db info we need to know the mongo db name,ip ,user name ,password etc info.In order to get this kind of info,we double click the mongo db service,choose the application used this service then find the env log under the  Files and Logs directory.You can get db credential info.

6.Open the config,php change the setting value based on the step5.You can add multiple server in this configuration file.

$MONGO["servers"][$i]["mongo_name"] = "192.155.236.166";//mongo server name
$MONGO["servers"][$i]["mongo_host"] = "192.155.236.166";//mongo host
$MONGO["servers"][$i]["mongo_port"] = "10014";//mongo port
$MONGO["servers"][$i]["mongo_timeout"] = 0;//mongo connection timeout
$MONGO["servers"][$i]["mongo_db"] = "db";//default mongo db to connect, works only if mongo_auth=false
$MONGO["servers"][$i]["mongo_user"] = "430f4c04-9ab0-49b2-95c8-226a3db5386f";//mongo authentication user name, works only if mongo_auth=false
$MONGO["servers"][$i]["mongo_pass"] = "a30d54be-2159-48ee-ae33-ca50d1ecc3ef";//mongo authentication password, works only if mongo_auth=false
$MONGO["servers"][$i]["mongo_auth"] = true;//enable mongo authentication?

7.Create a composer.json empty file. This file describes the dependencies of your project and may contain other metadata as well.

So by now all the configuration changes are done.The next step just deploy the app to the BlueMix.
Using the cloud foundry v6 cli, login to BlueMix and deploy your modified files using a PHP buildpack runtime.  
# Step 0: cf login -a <api target url> 
$ cf login -a https://api.ng.bluemix.net
# Step 1: under the  rockmongo project folder

$ cf push

After successfully deployment,open the browser and visit the http://php-mongoadmin.ng.bluemix.net/,you will see below login screen

After  input the db credential ,you can see Mongo db management UI.Now we can totally control our db in the cloud.

During my research ,I find some technical difficulty,so I post some questions on dw bluemix fourm and got my answers.It is a place to ask  BlueMix usage questions since lots of IBM experts there.

Tuesday, May 13, 2014

Deploy HelloWorld Ruby Sinatra web application on BlueMix

Today I will  share my step-by-step process to build and deploy a Ruby-based Sinatra application on BlueMix.Sinatra is a free and open source software web application library and domain-specific language written in Ruby. It is an alternative to other Ruby web application frameworks such as Ruby on Rails, Merb, Nitro and Camping. I am a newbie for Ruby,I thought it might take me lots effort to do this,but after trial,it is beyond my expectation,the whole operation is less five minutes.

1.Visit https://ace.ng.bluemix.net/ and setup an IBM account.After login into the BlueMix site, Click the catalog link,you will see below screen.
2.Double Click the Ruby Sinatra,it will popup a dialog for you to create your Ruby Sinatra name and host name. For example I create the app name to HelloWordlRuby,the domain name is also HelloWorld.ng.bluemix.net.After click the "Create" Button,it will automatic create this app into the DashBoard.

3.You can double click the HelloWorldRuby app link http://hellowordlruby.ng.bluemix.net to see the actual result.

4.Actually the web UI show the most variable of the Ruby(version 1.9.3) Sinatra environment info.I want to make some changes  on the UI. Just click on the settings(gear) icon next to your application name and select view guide to download the whole package.

5.Unzip the package to my local machine to c:\sinatra, open the helloWorld.rb and change the content to below screen.
6.Visit this CLI link and download the installer for your OS.Use below command to connect your bluemix
cf api https://api.ng.bluemix.net
Setting api endpint to https://api.ng.bluemix.net... OK
Notes:
Since the package already shipped with manifest.yml file,so we can directly use cf push command to deploy it.
applications:
- host: HelloWordlRuby
  disk: 1024M
  name: HelloWordlRuby
  path: .
  domain: ng.bluemix.net
  instances: 1
  memory: 128M

After  authentication, we can use cf push command  to deploy our application(make sure you execute command under the application fold) to BlueMix again.After successful deployment and re-visit the url you can see the below new UI,