Handling Events in React

In post Rendering RESTful service with React we created simple UI which render employee list fetched from RESTful service. As part of this post we will extend the same app to support add and delete employees operation.

We will start with updating react-app backend api with add/delete employee operation along with modifying the existing get employee method to return the list of employees following below steps:

Step 1. Define addEmployee method flagged by @PostMapping(“/employee/add”) which will add employee in a class level employee list:

@PostMapping("/employee/add")
public List<Employee> addEmployee(final @RequestBody Employee employee) {
	System.out.println("Adding employee with name : " + employee.getName());
	if(employee.getName() != null && employee.getName().length() > 0)
              employeeList.add(new Employee(employeeList.size(), employee.getName(), "IT"));
	return employeeList;
}

Step 2. Define deleteEmployee method flagged by @PostMapping(“/employee/delete”) which will delete employee from a class level employee list matching the name of an employee, as follows:

@PostMapping("/employee/delete")
public List<Employee> deleteEmployee(final @RequestBody Employee employee) {
	System.out.println("Deleting employee with name : " + employee.getName());
	final Optional<Employee> optional = employeeList.stream().filter(e -> e.getName().equalsIgnoreCase(employee.getName())).findAny();
	 if(optional.isPresent()){
		employeeList.remove(optional.get());
	 }
	return employeeList;
}

Eventually, ReactAppApplication.java should look like:

@SpringBootApplication
@RestController
public class ReactAppApplication {

	final List<Employee> employeeList = new ArrayList<>();
	
	public static void main(String[] args) {
		SpringApplication.run(ReactAppApplication.class, args);
	}

	@GetMapping("/employee/get")
	public List<Employee> get() {
		return employeeList;
	}
	
	@PostMapping("/employee/add")
	public List<Employee> add(final @RequestBody Employee employee) {
		System.out.println("Adding employee with name : " + employee.getName());
		if(employee.getName() != null && employee.getName().length() > 0)
		 employeeList.add(new Employee(employeeList.size(), employee.getName(), "IT"));
		return employeeList;
	}
	
	@PostMapping("/employee/delete")
	public List<Employee> delete(final @RequestBody Employee employee) {
		System.out.println("Deleting employee with name : " + employee.getName());
		final Optional<Employee> optional = employeeList.stream().filter(e -> e.getName().equalsIgnoreCase(employee.getName())).findAny();
		if(optional.isPresent()){
			employeeList.remove(optional.get());
		}
		return employeeList;
	}
}

Step 3: Define addEmployee method/handler in ReactApp component which make a POST call with an employee name as a payload to the addEmployee method we just defined in our controller, as follows:

/Users/ArpitAggarwal/react-app/app/components/react-app.jsx

addEmployee(employeeName){

		let _this = this;
		this.Axios.post('/add', {
        	name: employeeName
         })
		  .then(function (response) {
		    console.log(response);
		    _this.setState({employees: response.data});
		  })
		  .catch(function (error) {
		    console.log(error);
		  });
}

Step 4: Bind addEmployee handler in the constructor of ReactApp component:

constructor(props) {
		super(props);
		this.state = {employees: []};
		this.addEmployee = this.addEmployee.bind(this);
		this.Axios = axios.create({
		    baseURL: "/employee",
		    headers: {'content-type': 'application/json', 'creds':'user'}
		});
}

Step 5: Render the child component – AddEmployee as part of ReactApp component render method, passing addEmployee handler as react props to establish the parent child communication:

render() {
		return (
				<div>
				  <AddEmployee addEmployee={this.addEmployee}/>
				  <EmployeeList employees={this.state.employees}/>
		        </div>
		)
}

Step 6: Create add-employee component inside component directory, as follows:

cd react-app/app/components/
touch add-employee.jsx

And copy the following content:

react-app/app/components/add-employee.jsx

import React, { Component, PropTypes } from 'react'

export default class AddEmployee extends React.Component {

  render(){
    return (
       <div>
          <input type = 'text' ref = 'input' />
          <button onClick = {(e) => this.handleClick(e)}>
             Add Employee
          </button>
       </div>
    )
  }
  handleClick(e) {
     const node = this.refs.input
     const text = node.value.trim()
     console.log(text);
     this.props.addEmployee(text)
     node.value = ''
  }
}

handleClick(e) function defined above is called on Add Employee button click which will further call addEmployee handler defined in ReactApp using props.

With all this in place, our react-app can perform add employee operation. Next we will extend the same to support delete employee operation, following further steps.

Step 7: Define deleteEmployee handler and bind it in ReactApp in the same way we did for addEmployee handler:

/Users/ArpitAggarwal/react-app/app/components/react-app.jsx

constructor(props) {
		super(props);
		this.state = {employees: []};
		this.addEmployee = this.addEmployee.bind(this);
		this.deleteEmployee = this.deleteEmployee.bind(this);
		this.Axios = axios.create({
		    baseURL: "/employee",
		    headers: {'content-type': 'application/json', 'creds':'user'}
		});
}

deleteEmployee(employeeName){
        let _this = this;
        this.Axios.post('/delete', {
        	name: employeeName
          })
          .then(function (response) {
        	_this.setState({employees: response.data});
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
}

Step 8: Pass deleteEmployee handler to the EmployeeList component which will further pass it to it’s child container:

render() {
		return (
				<div>
				  <AddEmployee addEmployee={this.addEmployee}/>
				  <EmployeeList employees={this.state.employees} deleteEmployee={this.deleteEmployee}/>
		        </div>
			)
	}

Eventually, ReactApp component should look like:

'use strict';
const React = require('react');
var axios = require('axios');

import EmployeeList from './employee-list.jsx'
import AddEmployee from './add-employee.jsx'

export default class ReactApp extends React.Component {

	constructor(props) {
		super(props);
		this.state = {employees: []};
		this.addEmployee = this.addEmployee.bind(this);
		this.deleteEmployee = this.deleteEmployee.bind(this);
		this.Axios = axios.create({
		    baseURL: "/employee",
		    headers: {'content-type': 'application/json', 'creds':'user'}
		});
	}

	componentDidMount() {
		let _this = this;
		this.Axios.get('/get')
		  .then(function (response) {
		     console.log(response);
		    _this.setState({employees: response.data});
		  })
		  .catch(function (error) {
		    console.log(error);
		  });
	}
	
	addEmployee(employeeName){

		let _this = this;
		this.Axios.post('/add', {
        	name: employeeName
         })
		  .then(function (response) {
		    console.log(response);
		    _this.setState({employees: response.data});
		  })
		  .catch(function (error) {
		    console.log(error);
		  });
    }
    
    deleteEmployee(employeeName){
        let _this = this;
        this.Axios.post('/delete', {
        	name: employeeName
          })
          .then(function (response) {
        	_this.setState({employees: response.data});
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
    }
	render() {
		return (
				<div>
				  <AddEmployee addEmployee={this.addEmployee}/>
				  <EmployeeList employees={this.state.employees} deleteEmployee={this.deleteEmployee}/>
		        </div>
			)
	}
}

Step 9: Update EmployeeList component to pass the deleteEmployee handler to it’s child component – Employee by importing it along with the change in render method to have a Delete column:

const React = require('react');
import Employee from './employee.jsx'

export default class EmployeeList extends React.Component{
    
    render() {
		var employees = this.props.employees.map((employee, i) =>
			<Employee key={i} employee={employee} deleteEmployee={() => this.props.deleteEmployee(employee.name)}/>
		);
		
		return (
			<table>
				<tbody>
					<tr>
						<th>ID</th>
						<th>Name</th>
						<th>Department</th>
						<th>Delete</th>
					</tr>
					{employees}
				</tbody>
			</table>
		)
	}
}

Step 10: Update Employee component to render – DeleteEmployee component passing the deleteEmployee handler:

const React = require('react');
import DeleteEmployee from './delete-employee.jsx'

export default class Employee extends React.Component{
	render() {
		return (
			<tr>
				<td>{this.props.employee.id}</td>
				<td>{this.props.employee.name}</td>
				<td>{this.props.employee.department}</td>
				<td><DeleteEmployee deleteEmployee={this.props.deleteEmployee}/></td>
			</tr>
		)
	}
}

Step 11: Create delete-employee component inside component directory:

cd react-app/app/components/
touch delete-employee.jsx

And copy the following content:

react-app/app/components/delete-employee.jsx

import React, { Component, PropTypes } from 'react'

export default class DeleteEmployee extends React.Component {
  render(){
    return (
          <button onClick = {(employeeName) => this.handleDelete(employeeName)}>
             Delete
          </button>
    )

}
  handleDelete(employeeName) {
   this.props.deleteEmployee(employeeName);
  }
}

handleDelete(employeeName) function defined above is called on Delete button click which will further call deleteEmployee handler defined in ReactApp using props.

With all in place directory structure should look like:

Screen Shot 2017-05-15 at 8.38.57 pm

Now re-run the application and visit http://localhost:8080, it should look like as shown in below screenshot, once you add few employee.

Screen Shot 2017-05-15 at 8.41.06 pm

Complete source code is hosted on github.

Advertisements

Rendering RESTful service with React

Looking at the popularity of React, I thought of learning it and creating a simple UI which will render data from RESTful service.

With this post, I will try to replicate the steps I followed while writing it along with references. Before starting, let me give you a brief introduction about React.

What is React?

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It uses virtual DOM which improve apps performance since JavaScript virtual DOM is faster than the regular DOM with a limitation that it only covers view layer of the app so you still need to choose other technologies to get a complete tooling set for development.

Now, lets’ start with creating react-app running on port 8080, following below steps:

Step 1: Go to start.spring.io and create a new project react-app adding the Thymeleaf starters, based on the following image:

Screen Shot 2017-05-06 at 2.53.30 pm.png
Step 2: Edit ReactAppApplication.java to add a method which returns a list of employee, as follows:

package com.arpit.react.app;

import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class ReactAppApplication {

	public static void main(String[] args) {
		SpringApplication.run(ReactAppApplication.class, args);
	}

	@GetMapping("/employee/get")
	public List<Employee> get() {
		List<Employee> employeeList = new ArrayList<>();
		employeeList.add(new Employee(1, "Arpit", "IT"));
		employeeList.add(new Employee(2, "Sanjeev", "IT"));
		return employeeList;
	}
}

@Controller
class IndexPageController {

	@GetMapping(value = "/")
	public String index() {
		return "index";
	}
}

final class Employee {

	private int id;
	private String name;
	private String department;

	public Employee() {

	}

	public Employee(final int id, final String name, final String department) {
		this.id = id;
		this.name = name;
		this.department = department;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}
}

IndexPageController define index() method flagged by @GetMapping(value = “/”) to support the / route. It returns index as the name of the template, which Spring Boot’s autoconfigured view resolver will map to src/main/resources/templates/index.html.

Step 3: Define an HTML template src/main/resources/templates/index.html with the following content:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8" />
<title>React with Spring REST</title>
</head>
<body>
	<div id="react"></div>
	<script src="package/script.js"></script>
</body>
</html>

Step 4: Move to react-app directory and run command: mvn spring-boot:run. Once running open http://localhost:8080/employee/get which will give you the list of employees we are going to render on UI built with React.

Step 5: Next we will add frontend-maven-plugin in pom.xml  to install Node and NPM locally for the react-app followed by running Webpack  build, as follows:

<plugin>
				<groupId>com.github.eirslett</groupId>
				<artifactId>frontend-maven-plugin</artifactId>
				<version>1.2</version>
				<configuration>
					<installDirectory>target</installDirectory>
				</configuration>
				<executions>
					<execution>
						<id>install node and npm</id>
						<goals>
							<goal>install-node-and-npm</goal>
						</goals>
						<configuration>
							<nodeVersion>v4.4.5</nodeVersion>
							<npmVersion>3.9.2</npmVersion>
						</configuration>
					</execution>
					<execution>
						<id>npm install</id>
						<goals>
							<goal>npm</goal>
						</goals>
						<configuration>
							<arguments>install</arguments>
						</configuration>
					</execution>
					<execution>
						<id>webpack build</id>
						<goals>
							<goal>webpack</goal>
						</goals>
					</execution>
				</executions>
</plugin>

Step 6: Execute npm init in the root directory to create package.json in which we specify all the dependencies required to build our react-app like React, React DOM, Webpack, Babel Loader, Babel Core, Babel Preset: ES2015, Babel Preset: React, as follows:

$ cd react-app
$ touch npm init

Copy the following content:

{
  "name": "react-app",
  "version": "1.0.0",
  "description": "Rendering RESTful service with React",
  "repository": {
    "type": "git",
    "url": "git@github.com:arpitaggarwal/react-app.git"
  },
  "keywords": [
    "rest",
    "spring",
    "react"
  ],
  "author": "Arpit Aggarwal",
  "dependencies": {
    "axios": "^0.16.1",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "webpack": "^1.12.2"
  },
  "scripts": {
    "watch": "webpack --watch -d"
  },
  "devDependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.7",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0"
  }
}

Step 7: Next we will create webpack.config.js to configure webpack, as follows:

$ cd react-app
$ touch webpack.config.js

Copy the following content:

var path = require('path');

module.exports = {
    entry: './app/main.js',
    cache: true,
    debug: true,
    output: {
        path: __dirname,
        filename: './src/main/resources/static/package/script.js'
    },
    module: {
        loaders: [
            {
                test: path.join(__dirname, '.'),
                exclude: /(node_modules)/,
                loader: 'babel',
                query: {
                    cacheDirectory: true,
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

entry option specified above is the entry point for the bundle.
cache option specified above Cache generated modules and chunks to improve performance for multiple incremental builds.
output option specified above tell Webpack how to write the compiled files to disk.

For more configuration options you can explore here.

Step 8: Next we will create entry point for the webpack which is react-app/app/main.js, as:

$ cd react-app
$ mkdir app
$ cd app
$ touch main.js

Copy the following content:

'use strict';
const React = require('react');
const ReactDOM = require('react-dom')

import ReactApp from './components/react-app.jsx'

ReactDOM.render(
		<ReactApp />,
	document.getElementById('react')
)

React is the main library from Facebook for building the app.
ReactDOM provides DOM-specific methods that can be used at the top level.
ReactApp is the top level container for all React components.

Let’s define ReactApp along with it’s child components, as:

$ cd react-app/app/
$ mkdir components
$ cd components
$ touch react-app.jsx employee-list.jsx employee.jsx 

react-spring/app/components/react-app.jsx

'use strict';
const React = require('react');
var axios = require('axios');

import EmployeeList from './employee-list.jsx'

export default class ReactApp extends React.Component {

	constructor(props) {
		super(props);
		this.state = {employees: []};
		this.Axios = axios.create({
		    baseURL: "/employee",
		    headers: {'content-type': 'application/json', 'creds':'user'}
		});
	}

	componentDidMount() {
		let _this = this;
		this.Axios.get('/get')
		  .then(function (response) {
		     console.log(response);
		    _this.setState({employees: response.data});
		  })
		  .catch(function (error) {
		    console.log(error);
		  });
	}

	render() {
		return (
				<div>
				  <EmployeeList employees={this.state.employees}/>
		        </div>
			)
	}
}

react-spring/app/components/employee-list.jsx

const React = require('react');
import Employee from './employee.jsx'

export default class EmployeeList extends React.Component{
    
    render() {
		var employees = this.props.employees.map((employee, i) =>
			<Employee key={i} employee={employee}/>
		);
		
		return (
			<table>
				<tbody>
					<tr>
						<th>ID</th>
						<th>Name</th>
						<th>Department</th>
					</tr>
					{employees}
				</tbody>
			</table>
		)
	}
}

react-spring/app/components/employee.jsx

const React = require('react');

export default class Employee extends React.Component{
	render() {
		return (
			<tr>
				<td>{this.props.employee.id}</td>
				<td>{this.props.employee.name}</td>
				<td>{this.props.employee.department}</td>
			</tr>
		)
	}
}

With all this in place, your directory structure should look like:

Screen Shot 2017-05-06 at 4.49.26 pm

Now re-run the application and visit http://localhost:8080.

Complete source code is hosted on github.

Writing RESTful Service using Node, Express and MongoDB

Looking at the popularity of Node.js, I thought of learning and creating a rest api that should create, delete and get employees from database and fortunately I did it.

With this post, I will try to replicate the steps I followed while writing it along with references.

Assuming Node.js is already installed in our system, let’s start creating nodejs-rest-api, following below steps:

Step 1: Create a directory which will contain all the files related to our app, for me it’s /Users/ArpitAggarwal/nodejs-rest-api and execute npm init:

$ cd /Users/ArpitAggarwal/
$ mkdir nodejs-rest-api
$ npm init

npm init command specified above will create package.json which helps us to manage dependencies.

Step 2: Install Express as a dependency:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ npm install --save express

Step 3: Create default entry point for Node.js i.e server.js, inside the same directory we created earlier:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ touch server.js

Copy below content in server.js:

const express = require('express');
const app = express();

app.listen(9999, function() {
  console.log('Node server listening on 9999')
})

app.use(express.static(__dirname + '/public'));

Let’s understand what does each line mean.

require – imports modules into the current file.
const express = require(‘express’) – Creates an Express application.
const app = express() – Is app object conventionally denotes the Express application.
app.listen(9999) – Starts a UNIX socket and listens for connections on the given path.
app.use(express.static(__dirname + ‘/public’)) – Express serve static content for the app from the “public” directory in the application directory.

Step 4: Create index.html inside directory /Users/ArpitAggarwal/nodejs-rest-api/public as follows:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ mkdir public
$ cd public
$ touch index.html

Copy below content in index.html:

Hello Node!

Step 5: Modify server.js to add GET mapping to display the index.html we just created:

app.get('/', function(req, res){
  res.sendFile('/index.html')
});

Step 6: Move to directory /Users/ArpitAggarwal/nodejs-rest-api and start the app following below command:

$ cd /Users/ArpitAggarwal/nodejs-rest-api
$ node server.js

Now, opening http://localhost:9999/ in browser or executing command:

curl http://localhost:9999

will show us “Hello Node!” as response.

Step 7: Now, we will install MongoDB as a dependency moving to the directory /Users/ArpitAggarwal/nodejs-rest-api/:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ npm install --save mongodb

Step 8: Create config.js which will store all the configurable parameters of the app like username, password, urls, etc. It basically helps us to specify the input to an app at runtime based on different environments on which we are going to run the app:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ touch config.js

Copy the below content in config.js:

var config = {};

config.mongodb = {};
config.server = {};

config.server.port = process.env.WEB_PORT || 9999;

config.mongodb.username = process.env.MONGODB_USERNAME || 'arpit';
config.mongodb.password= process.env.MONGODB_PASSWORD || 'xxxx';
config.mongodb.host= process.env.MONGODB_HOST || 'ds047752.mlab.com';
config.mongodb.port = process.env.MONGODB_PORT || 47752;
config.mongodb.databaseName = process.env.MONGODB_NAME || 'my-database';

module.exports = config;

Do replace the properties with your’s or export from command line before starting the app, for example:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ export MONGODB_PASSWORD = p@ssword
$ node server.js

Step 9: Create mongodb.js where we will define MongoClient and export the connection to database as well as database object to utilize in a non redundant fashion while defining at one place, as follows:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ touch mongodb.js

Copy the below content in mongodb.js:


var MongoClient = require( 'mongodb' ).MongoClient;
var util = require('util');
var config = require('./config');
var _db;

var uri = util.format('mongodb://%s:%s@%s:%d/%s',
    config.mongodb.username, config.mongodb.password, config.mongodb.host, config.mongodb.port, config.mongodb.databaseName);

module.exports = {
  connectToServer: function( callback ) {
    /** Connect to the Mongo database at the URI using the client **/
    MongoClient.connect( uri, { auto_reconnect: true }, function( err, db ) {
      if (err) throw err;
      else if (!db) console.log('Unknown error connecting to database');
      else {
        console.log('Connected to MongoDB database server at:');
        console.log('\n\t%s\n', uri);
        _db = db;
      }
      return callback( err );
    } );
  },
  getDb: function() {
    return _db;
  }
};

require( ‘mongodb’ ).MongoClient specified above create a new MongoClient instance.

var config = require(‘./config’) – Imports config.js into the current file.

Step 10: Now let’s modify server.js to use the above two files we just created and setting up the server to listen on specified port only when MongoDB connection is successful:

const mongodb = require('./mongodb.js');
const config = require('./config.js');
var db

mongodb.connectToServer( function( err ) {
  app.listen(config.server.port, function() {
     console.log('Node server listening on ' + config.server.port);
     db = mongodb.getDb();
  })
});

Step 11: Next, modify GET request in server.js to get the list of employees from database using the MongoClient we just created, as follows:

app.get('/employee/get', function(req, res){
  db.collection('employees').find().toArray(function(err, results) {
  res.send(results);
  })
  res.set({
    'Cache-Control': 'no-cache'
  });
});

Executing the below command will list all the employees we create:

$ curl http://localhost:9999/employee/get

Step 12: Moving further to extend our app to create employee in a database by adding POST request. But, before introducing POST request we have to install body-parser as a node dependency which will help in parsing incoming request bodies in a middleware, as follows:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ npm install --save body-parser

Same like other dependencies we have to import it using require keyword to leverage the capability for parsing the JSON request, as follows:

const bodyParser= require('body-parser')

app.use(bodyParser.json())

app.post('/employee/create', (req, res) => {
  db.collection('employees').save(req.body, (err, result) => {
    if (err) return console.log(err)
    res.send('Employee created!');
  })
})

Now everything is in place for POST, let’s create an employee:

$ curl -H "Content-Type: application/json" -X POST -d '{"name": "Arpit Aggarwal","email":"aggarwalarpit.89@gmail.com"}' http://localhost:9999/employee/create

Next, we will extend our app to delete an employee and to that we will define the DELETE mapping in server.js, as follows:

app.delete('/employee/delete', (req, res) => {
  db.collection('employees').findOneAndDelete({name: req.body.name},
  (err, result) => {
    if (err) return res.send(500, err)
    res.send('Employee deleted!')
  })
})

Let’s verify DELETE call:

curl -H "Content-Type: application/json" -X DELETE -d '{"name": "Arpit Aggarwal"}' http://localhost:9999/employee/delete

Tired of restarting the Node.js server everytime you make changes to app?

If yes, we can use Nodemon, a utility that will monitor for any changes in our source and automatically restart our server. Let’s install it globally:

$ npm install -g nodemon

Once installed, we have to start our app with nodemon instead of node, for example:

$ cd /Users/ArpitAggarwal/nodejs-rest-api/
$ nodemon server.js

Complete source code is hosted on github.

Reference: http://expressjs.com/en/api.html#express

Deploying RESTful Service on Cloudfoundry

In this post, we will deploy RESTful service on Cloudfoundry using Pivotal Cloud Foundry (PCF) Dev. As creating a restful web service is not a part of this post, I already created employee-service which have a static backend and available for clone from GitHub.

Before deploying it on Cloudfoundry, let’s have a brief about it.

Cloudfoundry

Cloud Foundry is an open source cloud platform as a service (PaaS) on which developers can build, deploy, run and scale applications on public and private cloud models. It is VMware originally created by VMware and now it is part of Pivotal Software.

Now let’s set up lightweight PCF on our local workstation using PCF Dev, following below steps:

Step 1: Download and install cf-cli-installer_6.22.2_osx.pkg  in a directory, for me it’s /Users/ArpitAggarwal/cloudfoundry

$ cd /Users/ArpitAggarwal/cloudfoundry/ 
$ sudo installer -pkg ./cf-cli-installer_6.22.2_osx.pkg -target /

Step 2: Test if Cloudfoundry CLI installed successfully:

$ cf help

Step 3: Next we will download and install PCF Dev in the same directory we created earlier, as follows:

$ cd /Users/ArpitAggarwal/cloudfoundry/
$ unzip pcfdev-v0.22.0+PCF1.8.2-osx.zip
$ ./pcfdev-v0.22.0+PCF1.8.2-osx

Start 4: Start PCF Dev:

$ cd /Users/ArpitAggarwal/cloudfoundry/
$ cf dev start

Above command starts a single virtual machine on our workstation running PCF.

Step 5: Clone employee-service from GitHub in a directory, for me it’s /Users/ArpitAggarwal/

$ cd /Users/ArpitAggarwal/
$ git clone https://github.com/arpitaggarwal/empoyee-service.git

Step 6: Update the employee-service with manifest.yml:

$ cd /Users/ArpitAggarwal/employee-service
$ touch manifest.yml

manifest.yml created above is used by PCF for deployment to local workstation or on public cloud.

Step 7: Copy the below content in manifest.yml:

---
applications:
- name: empoyee-service
  memory: 1G
  random-route: true
  path: build/libs/empoyee-service-0.0.1.war
  buildpack: https://github.com/arpitaggarwal/java-buildpack.git

name attribute specified above is the name of an application.
path attribute is the directory location of an application.
buildpack attribute points to the java-buildpack, which is used by PCF for running JVM-based applications.

More about manifest.yml you can explore here.

Step 8: Next, we will build the application and push it to Cloudfoundry local workstation after login, as follows:

$ cd /Users/ArpitAggarwal/empoyee-service
$ empoyee-service git:(master) ./gradlew clean build
$ empoyee-service git:(master) ✗ cf login -a api.local.pcfdev.io --skip-ssl-validation
API endpoint: api.local.pcfdev.io

Email> user
Password> pass

$ cf push

cf push command specified above push an app or syncs changes to an existing app to the URL http://empoyee-service.local.pcfdev.io

Is application successfully deployed on Cloudfoundry?

Let’s verify it viewing the recent deployment logs where we can look server start up status, as follows:

$ cd /Users/ArpitAggarwal/empoyee-service
$ cf logs empoyee-service --recent

We can also verify application deployment executing GET and POST request against it, as follows:

GET Request to get all employees:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://empoyee-service.local.pcfdev.io/empoyee/get

POST Request to create an employee:

curl -H "Content-Type: application/json" -X POST -d '{"name": "Arpit Aggarwal","email":"aggarwalarpit.89@gmail.com"}' http://empoyee-service.local.pcfdev.io/employee/create

The complete source code is hosted on github.