Spring MVC AngularJS Address Book

Try it: http://cloudsole-angular.herokuapp.com
Clone it: https://github.com/thysmichels/cloudsole-angular

1. Address Book Model
2. Address Book Service
3. Address Book Service Implementation
4. Address Book Controller
5. Address Book Angular Controller
6. Address Book HTML

1. Address Book Model

package com.cloudsole.angular.model;

/**
 * Created by tmichels on 8/3/14.
 */
public class AddressBook {

    private long id;
    private String firstName;
    private String lastName;
    private String phone;
    private String email;

    public long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

2. Address Book Service

package com.cloudsole.angular.service;

import com.cloudsole.angular.model.AddressBook;

import java.util.List;

/**
 * Created by tmichels on 8/3/14.
 */
public interface AddressBookService {
     List<AddressBook> viewAllAddressBook();
     void createAddressBook(AddressBook addressBook);
     void updateAddressBook(int pos, AddressBook updateAddressBook);
     void deleteAddressBook(int id);
     void deleteAllAddressBook();
     AddressBook findAddressBook(int id);
}

3. Address Book Service Implementation

package com.cloudsole.angular.service;

import com.cloudsole.angular.model.AddressBook;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tmichels on 8/3/14.
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {

    List<AddressBook> addressBooks = new ArrayList<AddressBook>();
    private static Long id = 0L;

    @Override
    public List<AddressBook> viewAllAddressBook() {
        return addressBooks;
    }

    @Override
    public void createAddressBook(AddressBook addressBook) {
        addressBook.setId(id);
        addressBooks.add(addressBook);
        ++id;
    }

    @Override
    public void updateAddressBook(int pos, AddressBook updateAddressBook) {
        addressBooks.set(pos, updateAddressBook);
    }

    @Override
    public void deleteAddressBook(int id) {
        addressBooks.remove(id);
    }

    @Override
    public void deleteAllAddressBook() {
        addressBooks.clear();
        id = 0L;
    }

    @Override
    public AddressBook findAddressBook(int id) {
        return addressBooks.get(id);
    }
}

4. Address Book Controller

package com.cloudsole.angular.controller;

import com.cloudsole.angular.model.AddressBook;
import com.cloudsole.angular.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by tmichels on 8/3/14.
 */

@Controller
@RequestMapping("/address")
public class AddressBookController {

    @Autowired
    AddressBookService addressBookService;

    @RequestMapping(value = "/all.json", method = RequestMethod.GET)
    public @ResponseBody List<AddressBook> viewAllAddressBook(){
        return addressBookService.viewAllAddressBook();
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody void addAddressBookEntry(@RequestBody AddressBook addressBook){
        addressBookService.createAddressBook(addressBook);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public @ResponseBody void deleteAddressBookEntry(@PathVariable("id") String id){
        addressBookService.deleteAddressBook(Integer.valueOf(id));
    }

    @RequestMapping(value = "/update/{pos}", method = RequestMethod.PUT)
    public @ResponseBody void updateAddressBook(@RequestBody AddressBook addressBook, @PathVariable("pos") String pos){
        addressBookService.updateAddressBook(Integer.valueOf(pos), addressBook);
    }

    @RequestMapping(value="/delete/all", method = RequestMethod.DELETE)
    public @ResponseBody void deleteAllAddressBook(){
        addressBookService.deleteAllAddressBook();
    }

    @RequestMapping("/layout")
    public String getTodoPartialPage() {
        return "addressbook/layout";
    }
}

5. Address Book Angular Controller

/**
 * Created by tmichels on 8/3/14.
 */


var AddressBookController = function($scope, $http){

    $scope.editMode = false;
    $scope.position = '';

    $scope.viewAllAddressBook = function(){
        $http.get('address/all.json').success(function(response){
            $scope.addressBooks = response;
        })
    }

    $scope.resetAddressBookField = function(){
        $scope.ab.firstName='';
        $scope.ab.lastName='';
        $scope.ab.phone = '';
        $scope.ab.email = '';
        $scope.editMode = false;
    }

    $scope.addAddressBook = function(ab) {
        $http.post('address/add', ab).success(function(response){
            $scope.viewAllAddressBook();
            $scope.ab.firstName='';
            $scope.ab.lastName='';
            $scope.ab.phone = '';
            $scope.ab.email = '';
        }).error(function(response){
            console.log(response);
        })
    }

    $scope.updateAddressBook = function(ab) {
        $http.put('address/update/'+$scope.position, ab).success(function(response){
            $scope.ab.firstName='';
            $scope.ab.lastName='';
            $scope.ab.phone = '';
            $scope.ab.email = '';
            $scope.viewAllAddressBook();
            $scope.editMode = false;
        }).error(function(response){
            console.log(response);
        })
    }

    $scope.deleteAddressBook = function(id) {
        $http.delete('address/delete/' + id).success(function(response){
            $scope.viewAllAddressBook();
        }).error(function(response){
            console.log(response);
        })
    }

    $scope.deleteAllAddressBook = function(){
        $http.delete('address/delete/all').success(function(response){
            $scope.viewAllAddressBook();
        })
    }

    $scope.editAddressBook = function(pos, addressBook){
        $scope.position = pos;
        $scope.ab = addressBook;
        $scope.editMode = true;
    }

    $scope.viewAllAddressBook();
}

6. Address Book HTML

<div class="alert alert-error" ng-show="error">{{errorMessage}}</div>
<div class="row">
    <form ng-submit="addAddressBook(ab)">
        <div class="col-lg-8">
            <input class="form-control" placeholder="Enter First Name" type="text" ng-model="ab.firstName" required min="1" />
            <input class="form-control" placeholder="Enter Last Name" type="text" ng-model="ab.lastName" required min="1" />
            <input class="form-control" placeholder="Enter Phone" type="text" ng-model="ab.phone" required min="1" />
            <input class="form-control" placeholder="Enter Email" type="text" ng-model="ab.email" required min="1" />
        </div>
    </form>

    <button class="btn btn-primary" ng-disabled="!ab" ng-hide="editMode" ng-click="addAddressBook(ab)">Add Entry</button>
    <button type="btn btn-primary" class="btn btn-primary"
            ng-disabled="!ab" ng-show="editMode"
            ng-click="updateAddressBook(ab)">Save</button>
    <button type="btn btn-primary" class="btn btn-primary" ng-click="resetAddressBookField()">Reset</button>
</div>
<hr />

<div class="row">
    <div class="col-lg-8">
        <div class="form-group">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search" id="search-query-3" ng-model="searchAddressBook">
                  <span class="input-group-btn">
                    <button type="submit" class="btn"><span class="fui-search"></span></button>
                  </span>
            </div>
        </div>
    </div>
</div>
<hr />

<div class="alert alert-info" style="width:400px;margin-left:100px;" ng-show="addressBooks.length == 0">
    No address book entry found
</div>
<table class="table table-bordered table-striped" ng-show="addressBooks.length > 0">
    <thead>
    <tr>
        <th style="text-align: center; width: 25px;">Delete</th>
        <th style="text-align: center; width: 25px;">Update</th>
        <th style="text-align: center;">First Name</th>
        <th style="text-align: center;">Last Name</th>
        <th style="text-align: center;">Phone Number</th>
        <th style="text-align: center;">Email</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="addressBook in addressBooks">
        <td  style="width:70px;text-align:center;"><button class="btn btn-mini btn-danger" ng-click="deleteAddressBook(addressBooks.indexOf(addressBook))">Delete</button></td>
        <td  style="width:70px;text-align:center;"><button class="btn btn-mini btn-danger" ng-click="editAddressBook(addressBooks.indexOf(addressBook), addressBook)">Update</button></td>
        <td>{{addressBook.firstName}}</td><td>{{addressBook.lastName}}</td><td>{{addressBook.phone}}</td><td>{{addressBook.email}}</td>
    </tr>
    </tbody>
</table>
<button class="btn btn-danger"  ng-show="addressBooks.length >= 1" ng-click="deleteAllAddressBook()">Delete All Address Book</button>

Spring MVC AngularJs Todo List

Try it: http://cloudsole-angular.herokuapp.com
Clone it: https://github.com/thysmichels/cloudsole-angular

1. Todo Service
2. Todo Service Implementation
3. Todo Spring MVC Controller
4. Angular App.js
5. Angular TodoController
6. Todo html page

1. Todo Service

package com.cloudsole.angular.service;

import java.util.List;

/**
 * Created by tmichels on 8/1/14.
 */
public interface TodoService {
    public List<String> allTodos();
    public void addTodo(String todo);
    public void deleteTodo(String todo);
    public void deleteAll();
    public void updateTodo(int position, String todo);
}

2. Todo Service Implementation

package com.cloudsole.angular.service;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tmichels on 8/1/14.
 */

@Service
public class TodoServiceImpl implements TodoService {

    List<String> todos = new ArrayList<String>();

    @Override
    public List<String> allTodos() {
        return todos;
    }

    @Override
    public void addTodo(String todo) {
        todos.add(todo);
    }

    @Override
    public void deleteTodo(String todo) {
        if (todos.contains(todo)){
            todos.remove(todo);
        }
    }

    @Override
    public void deleteAll() {
        todos.clear();
    }


    @Override
    public void updateTodo(int position, String todo) {
        todos.set(position, todo);
    }
}

3. Todo Spring MVC Controller

package com.cloudsole.angular.controller;

import com.cloudsole.angular.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by tmichels on 8/1/14.
 */

@Controller
@RequestMapping("/todo")
public class TodoController {

    @Autowired
    private TodoService todoService;

    @RequestMapping(value = "/all.json")
    public @ResponseBody List<String> viewAllTodos(){
        return todoService.allTodos();
    }

    @RequestMapping(value = "/add/{todo}", method = RequestMethod.POST)
    public @ResponseBody void addTodo(@PathVariable("todo") String todo){
        todoService.addTodo(todo);
    }

    @RequestMapping(value = "/delete/{todo}", method = RequestMethod.DELETE)
    public @ResponseBody void deleteTodo(@PathVariable("todo") String todo){
        todoService.deleteTodo(todo);
    }

    @RequestMapping(value = "/deleteAll", method = RequestMethod.DELETE)
    public @ResponseBody void deleteAllTodo(){
        todoService.deleteAll();
    }

    @RequestMapping(value="/update/{position}/{todo}", method = RequestMethod.PUT)
    public @ResponseBody void updateTodo(@PathVariable("position") String position, @PathVariable("todo") String todo){
        todoService.updateTodo(Integer.valueOf(position), todo);
    }

    @RequestMapping("/layout")
    public String getTodoPartialPage() {
        return "todo/layout";
    }
}

4. Angular App.js

'use strict';

var AngularSpringApp = {};

var App = angular.module('AngularSpringApp', ['AngularSpringApp.filters', 'AngularSpringApp.services', 'AngularSpringApp.directives', 'ngRoute', 'ui.bootstrap', 'ngTable', 'ui.ace', 'angularFileUpload']);

// Declare app level module which depends on filters, and services
App.config(['$routeProvider', function ($routeProvider) {

    $routeProvider.when('/todo', {
        templateUrl: 'todo/layout',
        controller: TodoController
    });
    $routeProvider.when('/address', {
        templateUrl: 'address/layout',
        controller: AddressBookController
    });
    $routeProvider.when('/table', {
        templateUrl: 'table/layout',
        controller: TableController
    });
    $routeProvider.when('/file', {
        templateUrl: 'file/layout',
        controller: FileController
    });
    $routeProvider.when('/editor', {
        templateUrl: 'editor/layout',
        controller: EditorController
    });
    $routeProvider.when('/rest', {
        templateUrl: 'restangular/layout',
        controller: RestController
    });
    $routeProvider.when('/force', {
        templateUrl: 'force/layout',
        controller: ForceController
    });

    $routeProvider.otherwise({redirectTo: '/todo'});
}]);

5. Angular TodoController


var TodoController = function($scope, $http){

    $scope.editMode = false;
    $scope.position = '';

    $scope.getAllTodos = function(){
        $scope.resetError();
        $http.get('todo/all.json').success(function(response){
            $scope.todos = response;
        }).error(function() {
            $scope.setError('Could not display all todos');
        });
    }

    $scope.addTodo = function(newTodo){
        $scope.resetError();
        $http.post('todo/add/' + newTodo).success(function(response){
            $scope.getAllTodos();
        }).error(function() {
            $scope.setError('Could add todo');
        });
        $scope.todoName = '';
    }

    $scope.deleteTodo = function(deleteTodo){
        $scope.resetError();
        $http.delete('todo/delete/'+deleteTodo).success(function(response){
            $scope.getAllTodos();
        }).error(function() {
            $scope.setError('Could not delete todo');
        });
    }

    $scope.deleteAllTodo = function(){
        $scope.resetError();
        $http.delete('todo/deleteAll').success(function(response){
            $scope.getAllTodos();
        }).error(function() {
            $scope.setError('Could not delete all todos');
        })
    }

    $scope.editTodo = function(position, todo){
        $scope.resetError();
        $scope.todoName = todo;
        $scope.position = position;
        $scope.editMode = true;
    }

    $scope.updateTodo = function(updateTodo){
        $scope.resetError();
        $http.put('todo/update/'+ $scope.position +'/'+updateTodo).success(function(response){
            $scope.getAllTodos();
            $scope.position = '';
            $scope.todoName = '';
            $scope.editMode = false;
        }).error(function(){
            $scope.setError('Could not update todo');
         })
    }

    $scope.resetTodoField = function() {
        $scope.resetError();
        $scope.todoName = '';
        $scope.editMode = false;
    };

    $scope.resetError = function() {
        $scope.error = false;
        $scope.errorMessage = '';
    };

    $scope.setError = function(message) {
        $scope.error = true;
        $scope.errorMessage = message;
    };

    $scope.getAllTodos();
}

6. Todo html page

<div class="alert alert-error" ng-show="error">{{errorMessage}}</div>
<div class="row">
    <form ng-submit="addTodo(todoName)">
    <div class="col-lg-8">
     <input class="form-control" placeholder="Enter Todo" type="text" ng-model="todoName" required min="1" />
    </div>
   </form>

    <button class="btn btn-primary" ng-disabled="!todoName" ng-hide="editMode" ng-click="addTodo(todoName)">Add Todo</button>
    <button type="btn btn-primary" class="btn btn-primary"
            ng-disabled="!todoName" ng-show="editMode"
            ng-click="updateTodo(todoName)">Save</button>
    <button type="btn btn-primary" class="btn btn-primary" ng-click="resetTodoField()">Reset</button>
</div>
 <hr />

<div class="row">
    <div class="col-lg-8">
        <div class="form-group">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search" id="search-query-3" ng-model="searchTodo" typeahead="todo for todo in todos | filter:$viewValue | limitTo:8">
                  <span class="input-group-btn">
                    <button type="submit" class="btn"><span class="fui-search"></span></button>
                  </span>
            </div>
        </div>
    </div>
</div>
<hr />

<div class="alert alert-info" style="width:400px;margin-left:100px;" ng-show="todos.length == 0">
    No todos found
</div>
<table class="table table-bordered table-striped" ng-show="todos.length > 0">
    <thead>
    <tr>
        <th style="text-align: center; width: 25px;">Delete</th>
        <th style="text-align: center; width: 25px;">Update</th>
        <th style="text-align: center;">Todo</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="todo in todos | filter:searchTodo">
        <td  style="width:70px;text-align:center;"><button class="btn btn-mini btn-danger" ng-click="deleteTodo(todo)">Delete</button></td>
        <td  style="width:70px;text-align:center;"><button class="btn btn-mini btn-danger" ng-click="editTodo(todos.indexOf(todo), todo)">Update</button></td>
        <td>{{todo}}</td>
    </tr>
    </tbody>
</table>
<button class="btn btn-danger"  ng-show="todos.length >= 1" ng-click="deleteAllTodo()">Delete All Todos</button>

Heroku OAuth 2.0 Scribe Spring MVC Example

ApplicationContext.xml defines herokuServiceConfig and herokuServiceProvider Bean

  <bean id="herokuServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx" />
		<constructor-arg value="xxx"/>
		<constructor-arg value="https://www.example.com/oauth/heroku"/>
		<constructor-arg value="com.example.oauth.HerokuOauthApi"/>
	</bean>
	
	<bean id="herokuServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="herokuServiceConfig" />
	</bean>

Spring MVC Heroku OAuth Controller

package com.example.oauth.controller;

import static org.springframework.web.context.request.RequestAttributes.SCOPE_SESSION;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import com.example.oauth.OAuthServiceProvider;

/**
 * @author tmichels
 */

@Controller
@RequestMapping("/oauth/heroku")
public class HerokuController {
	
	@Autowired
	@Qualifier("herokuServiceProvider")
	private OAuthServiceProvider herokuServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;
	
	@RequestMapping(value="/login-heroku", method=RequestMethod.GET)
	 public String loginToHeroku(Map<String, Object> map, WebRequest request) {
			OAuthService service = herokuServiceProvider.getService();
			String authUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
			System.out.println("RequestToken: " + authUrl );
			return "redirect:" + authUrl;
    }
	
	@RequestMapping(value={""}, method = RequestMethod.GET)
	public String callback(@RequestParam(value="oauth_token", required=false) String oauthToken,
			@RequestParam(value="code", required=false) String oauthVerifier, WebRequest request, Map<String, Object> map) {

		OAuthService service = herokuServiceProvider.getService();

		// getting access token
		Verifier verifier = new Verifier(oauthVerifier);
		Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);

		// store access token as a session attribute
		request.setAttribute("oauthAccessToken", accessToken, SCOPE_SESSION);

		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession session = attr.getRequest().getSession(false); //create a new session
		session.setAttribute("accessToken",accessToken);
		
		return "settings";
	}
		
}

HerokuOauthApi extends DefaultApi20

package com.example.oauth;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Verb;

public class HerokuOauthApi extends DefaultApi20{

	private static final String ACCESSTOKEN = "https://id.heroku.com/oauth/token";

	@Override
	public String getAccessTokenEndpoint() {
		return ACCESSTOKEN;
	}

	@Override
	public String getAuthorizationUrl(OAuthConfig config) {
		return String.format("https://id.heroku.com/oauth/authorize?client_id=%s&response_type=code&scope=global", config.getApiKey());
	}
	
	 @Override
	 public Verb getAccessTokenVerb(){
	       return Verb.POST;
	 }
	 
	 @Override
	 public AccessTokenExtractor getAccessTokenExtractor() {
	    return new JsonTokenExtractor();
	 }
}

Spring MVC form checkbox binding

DeployList Model

package com.example.util;

import java.util.List;

public class DeployLists {

	private List<String> deployList;
	
	public List<String> getDeployList() {
		return deployList;
	}

	public void setDeployList(List<String> deployList) {
		this.deployList = deployList;
	}
}

ModelAndView DeployLists

	@RequestMapping("")
	public ModelAndView deployView(){
		ModelAndView mav = new ModelAndView("deploy");
		
		QueryResult<Map> apexClass = loginService.loginToSalesforce().query("Select Id, Name, ApiVersion, Status from ApexClass");
		
		List<String> apexClassNames= new ArrayList<String>();
		for (Map className : apexClass.getRecords()){
			apexClassNames.add(className.get("Name").toString());
		}

		mav.addObject("deployList", apexClassNames);
		mav.addObject("deployLists", new DeployLists());
		return mav;
	}

deploy.jsp

<div class="well clearfix">
	<div class="accordion" id="accordion2">
		<form:form method="POST" commandName="deployLists" action="/login/deploy/result" >
		<div class="accordion-group">
			<div class="accordion-heading">
				<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
					ApexClass
				</a>
			</div>
			<div id="collapseOne" class="accordion-body collapse in">
				<div class="accordion-inner">
					<form:checkboxes element="li" path="deployList" items="${deployList}"></form:checkboxes></ul>
				</div>
			</div>
		</div>

		</div><br/>
		<button type="submit" class="btn btn-primary">Deploy</button>
		</form:form>
	</div>
</div>

result.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<jsp:include page="header.jsp"/>
		<section class="row-fluid" id="why-adminflare">
			<h3 class="box-header"><i class="icon-fire" style="color: #cd522c"></i>Result</h3>
			<div class=" box well ">
				<c:forEach items="${deployLists.deployList}" var="dl" varStatus="index">
						${dl}
				</c:forEach>
			</div>
		</section>
<jsp:include page="footer.jsp"/>

Spring MVC form with multiple submit buttons

<div class="codeContainer">
	<form method="post" action="/login/apex/save/${apexType}/${currentId}">
		<textarea name="code" id="code">${body}</textarea><br/>
		<div class="btn-group">
			<input type="submit" value="Save" name="save" class="btn btn-primary">
			<input type="submit" value="Share" name="share" class="btn btn-primary">
		</div>
	</form>
</div>
	@SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, value = "/save/{type}/{id}")
    public String updateClassDetail(@PathVariable("id") String id, @PathVariable("type") String type,
                    @RequestParam("code") String code, Map<String, Object> map,
                    @RequestParam(required=false, value="save") String save,
                    @RequestParam(required=false, value="share") String share){

  if (save!=null){
    ....
  } else if (share!=null){
    ...
  } 
}

Spring Data MongoDB with Spring MVC

Below is the steps to create a Spring MVC application with MongoDB
1. Create MongoDB Entity
2. Define MongoDB DataSource
3. Define MongoDBTemplate
4. Create MongoDB Repository interface
5. Implement MongoDB Repository interface
6. Define your MongoDB Controller
7. Test MongoDB DataSource
8. Test MongoDBTemplate
9. Test MongoDB Repository

Create MongoDB Entity

package com.example.model;

import java.math.BigInteger;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name="CustomerActivity")
public class CustomerActivity implements java.io.Serializable {
	
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="id", nullable=false, unique=true)
	private BigInteger id;
	
	@Column(name="customerId", nullable=false)
	private String customerId;
	
	@Column(name="activityDescription") 
	private String activityDescription;
	
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="activityTime")
	private Date activityTime;
	
	@Column(name="activityType")
	private String activityType; //ActivityType
	
	@Column(name="systemName")
	private String systemName;
	
	@Column(name="systemUrl")
	private String systemUrl;

	public CustomerActivity(String customerId, String activityDescription, Date activityTime, String activityType, String systemName, String systemUrl) {
		this.customerId = customerId;
		this.activityDescription = activityDescription;
		this.activityTime = activityTime;
		this.activityType = activityType;
		this.systemName = systemName;
		this.systemUrl = systemUrl;
	}

	public BigInteger getId() {
		return id;
	}

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

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getActivityDescription() {
		return activityDescription;
	}

	public void setActivityDescription(String activityDescription) {
		this.activityDescription = activityDescription;
	}

	public Date getActivityTime() {
		return activityTime;
	}

	public void setActivityTime(Date activityTime) {
		this.activityTime = activityTime;
	}

	public String getActivityType() {
		return activityType;
	}

	public void setActivityType(String activityType) {
		this.activityType = activityType;
	}

	public String getSystemName() {
		return systemName;
	}

	public void setSystemName(String systemName) {
		this.systemName = systemName;
	}

	public String getSystemUrl() {
		return systemUrl;
	}

	public void setSystemUrl(String systemUrl) {
		this.systemUrl = systemUrl;
	}
}

Define MongoDB DataSource

package com.example.config;

import javax.inject.Inject;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;

@PropertySource("classpath:services.properties")
@Configuration
@Profile("default")
public class MongoDataSourceConfiguration {
	
	    @Inject Environment environment;
	    
	    @Bean(name="local")
	    public MongoDbFactory mongoDbFactoryLocal() throws Exception {
	        String dbName = environment.getProperty("mongo.db");
	        String host = environment.getProperty("mongo.host");
	        Mongo mongo = new Mongo(host);
	        return new SimpleMongoDbFactory(mongo, dbName);
	    }
}

Define MongoDBTemplate

package com.example.mongo;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.context.annotation.*;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.example.config.MongoDataSourceConfiguration;

/**
 * @author Thys Michels
 */
@Configuration
@Import( { MongoDataSourceConfiguration.class })
@EnableMongoRepositories
public class MongoRepositoryConfiguration {
	
    @Inject @Named("local") private MongoDbFactory mongoDbFactoryLocal;
	
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactoryLocal);
    }

    @Bean
    public GridFsTemplate gridFsTemplate(MongoDbFactory mongoDbFactory, MongoTemplate mongoTemplate) throws Exception {
        return new GridFsTemplate(mongoDbFactory, mongoTemplate.getConverter());
    }
}

Create MongoDB Repository interface

package com.example.service;

import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.example.model.CustomerActivity;

public interface CustomerActivityRepository {
	void updateCustomerActivity(BigInteger id, String customerId, String activityDescription, String activityType, String systemName, String systemUrl);
    void updateCustomerActivities(List<CustomerActivity> customersToUpdate);
    CustomerActivity getCustomerActivityById(BigInteger customerId);
    Collection<CustomerActivity> getAllCustomerActivities();
    void createCustomerActivity(String customerId, String activityDescription, Date activityTime, String activityType, String systemName, String systemUrl);
    void deleteCustomerActivity(BigInteger customerId);
    void createCustomerActivity(CustomerActivity newCustomer);
    void bulkCreateCustomerActivity(List<CustomerActivity> customers);
    List<CustomerActivity> findCustomerActivityByQuery(String query);
    void deleteCustomerActivities(List<CustomerActivity> customerToDelete);
    List<CustomerActivity> getPaginatedCustomerActivities(Integer currentPage, Integer totalPerPage);
    int getTotalRecords();
	List<String> getPaginationSequence();
	List<CustomerActivity> findCustomerActivityByCustomerId(String customerid);
}

Implement MongoDB Repository interface

package com.example.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.model.CustomerActivity;
import com.example.mongo.MongoRepositoryConfiguration;

@Repository
@Import( { MongoRepositoryConfiguration.class })
@Qualifier("mongoRepository")
public class CustomerActivityRepositoryImpl implements CustomerActivityRepository{	
	
	@Inject MongoTemplate mongoTemplate;
	
	Class<CustomerActivity> entityClass = CustomerActivity.class;
	
	Collection<CustomerActivity> customerActivity = new ArrayList<CustomerActivity>();
	
	@Override
	public void updateCustomerActivity(BigInteger id, String customerId, String activityDescription,  String activityType, String systemName, String systemUrl) {
		CustomerActivity updateCustomerActivity = this.getCustomerActivityById(id);
		updateCustomerActivity.setCustomerId(customerId);
		updateCustomerActivity.setActivityDescription(activityDescription);
		
		updateCustomerActivity.setActivityType(activityType);
		updateCustomerActivity.setSystemName(systemName);
		updateCustomerActivity.setSystemUrl(systemUrl);
		mongoTemplate.save(updateCustomerActivity);
	}

	@Override
	public void updateCustomerActivities(List<CustomerActivity> customerActivitiesToUpdate) {
		for (CustomerActivity customerActivity : customerActivitiesToUpdate){
			Update updateCustomerActivity = new Update();
			updateCustomerActivity.push("customerId", customerActivity.getCustomerId());
			updateCustomerActivity.push("activityDescription", customerActivity.getActivityDescription());
			updateCustomerActivity.push("activityTime", customerActivity.getActivityTime());
			updateCustomerActivity.push("activityType", customerActivity.getActivityType());
			updateCustomerActivity.push("systemName", customerActivity.getSystemName());
			updateCustomerActivity.push("systemUrl", customerActivity.getSystemUrl());
			mongoTemplate.updateFirst(new Query(Criteria.where("Id").is(customerActivity.getId())), updateCustomerActivity, CustomerActivity.class);
		}
	}

	@Override
	public CustomerActivity getCustomerActivityById(BigInteger id) {
		return mongoTemplate.findById(id, CustomerActivity.class);
	}

	@Override
	public Collection<CustomerActivity> getAllCustomerActivities() {
		try {
			 List<CustomerActivity> allCustomers = mongoTemplate.findAll(entityClass);
			 return allCustomers;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public void createCustomerActivity(String customerId, String activityDescription, Date activityTime, String activityType, String systemName, String systemUrl) {
		try {
			customerActivity.add(new CustomerActivity(customerId, activityDescription, activityTime, activityType, systemName, systemUrl));
			mongoTemplate.insert(customerActivity, entityClass);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public BigInteger findLastIdInCollection(){
		return mongoTemplate.findOne(new Query().with(new Sort(Direction.DESC,"id")), CustomerActivity.class).getId();
	}
	
	@Override
	public void deleteCustomerActivity(BigInteger customerId) {
		mongoTemplate.remove(this.getCustomerActivityById(customerId));
	}
	

	@Override
	public void createCustomerActivity(CustomerActivity newCustomer) {
		customerActivity.add(newCustomer);
		mongoTemplate.insert(customerActivity, entityClass);
	}


	@Override
	public void bulkCreateCustomerActivity(List<CustomerActivity> customerActivities) {
		for (CustomerActivity newcustomerActivity : customerActivities){
			customerActivity.add(new CustomerActivity(newcustomerActivity.getCustomerId(), newcustomerActivity.getActivityDescription(), newcustomerActivity.getActivityTime(), newcustomerActivity.getActivityType(), newcustomerActivity.getSystemName(), newcustomerActivity.getSystemUrl()));
		}
		mongoTemplate.insert(customerActivity, entityClass);
	}

	@Override
	public List<CustomerActivity> findCustomerActivityByQuery(String query) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@Transactional
	public void deleteCustomerActivities(List<CustomerActivity> customerActivitiesToDelete) {
		for (CustomerActivity customerActivityToDelete : customerActivitiesToDelete){
			mongoTemplate.remove(new Query(Criteria.where("customerId").is(customerActivityToDelete.getCustomerId().toString())), CustomerActivity.class);
		}
	}

	@Override
	public List<CustomerActivity> getPaginatedCustomerActivities(Integer currentPage, Integer totalPerPage) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getTotalRecords() {
		return getAllCustomerActivities().size();
	}

	@Override
	public List<String> getPaginationSequence() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CustomerActivity> findCustomerActivityByCustomerId(String customerId) {
		return mongoTemplate.find(new Query(Criteria.where("customerId").is(new Long(customerId).toString())), CustomerActivity.class);
	}
}

Define your MongoDB Controller

package com.example.controller;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.model.CustomerActivity;
import com.example.service.CustomerActivityRepositoryImpl;

@Controller
@RequestMapping("/activity")
public class MongoController {

	@Autowired
	@Qualifier("mongoRepository")
	CustomerActivityRepositoryImpl mongoCustomerService;
 	
	@RequestMapping("")
	public String returnMongoView(Map<String, Object> map){
		map.put("mongoCustomerList", mongoCustomerService.getAllCustomerActivities());
		return "mongo";
	}
	
	@RequestMapping(value="/insert")
	public String insertCustomersView(){
		return "insertmongo";
	}
	
	@RequestMapping(value="/insert", method=RequestMethod.POST)
	public String insertCustomers(@RequestParam("customerId") String customerId, 
			@RequestParam("activityDescription") String activityDescription,
			@RequestParam("activityTime") String activityTime,
			@RequestParam("activityType") String activityType, 
			@RequestParam("systemName") String systemName,
			@RequestParam("systemUrl") String systemUrl) {
		mongoCustomerService.createCustomerActivity(customerId, activityDescription, new Date(), activityType, systemName, systemUrl);
		return "mongo";
	}
	
	@RequestMapping(value="/delete/{id}", method=RequestMethod.POST)
	public String deleteCustomer(@PathVariable("id") String id, Map<String, Object> map){
		mongoCustomerService.deleteCustomerActivity(new BigInteger(id));
		return "mongo";
	}
	
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String viewUpdateCustomer(@PathVariable("id") String id, Map<String, Object> map){
		List<CustomerActivity> customer = Arrays.asList(mongoCustomerService.getCustomerActivityById(new BigInteger(id)));
		map.put("mongoList", customer);
		return "updatemongo";
	}
	
	@RequestMapping(value="/update/{id}", method=RequestMethod.POST)
	public String updateCustomer(@PathVariable("id") String id, 
			@RequestParam("customerId") String customerId, 
			@RequestParam("activityDescription") String activityDescription,
			@RequestParam("activityType") String activityType, 
			@RequestParam("systemName") String systemName,
			@RequestParam("systemUrl") String systemUrl) {
		mongoCustomerService.updateCustomerActivity(new BigInteger(id), customerId, activityDescription, activityType, systemName,systemUrl);
		return "mongo";
	}
}

Test MongoDB DataSource

package com.example.mongo;

import static org.junit.Assert.*;

import javax.inject.Inject;
import javax.inject.Named;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import com.example.config.MongoDataSourceConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={MongoDataSourceConfiguration.class})
public class LocalMongoConfigurationTest {

	@Inject MongoDbFactory mongoDbFactory;
	
	@Test
	public void testMongoDbFactoryConnection() {
		assertTrue(mongoDbFactory.getDb().getMongo().getConnector().isOpen());
	}
}

Test MongoDB Template

package com.example.mongo;

import static org.junit.Assert.*;

import javax.inject.Inject;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={MongoRepositoryConfiguration.class})
public class MongoTemplateTest {

	@Inject MongoTemplate mongTemplate;
	
	@Test
	public void testMongoTemplate() {
		assertEquals(mongTemplate.getCollection("lc-activity-service").getName(), "lc-activity-service");
	}
}

Test MongoDB Repository

package com.example.service;

import static org.junit.Assert.*;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import com.example.model.CustomerActivity;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={CustomerActivityRepositoryImpl.class})
public class CustomerActivityServiceTest {

	@Inject CustomerActivityRepository customerActivityService;
	
	@Test
	public void testCreateCustomerActivity() {
		Calendar cal = Calendar.getInstance();
		customerActivityService.createCustomerActivity("123", "Email Sent For Customer", cal.getTime(), "Email Received", "Salesforce", "http://salesforce.com/123213");
		assertNotNull(customerActivityService.findCustomerActivityByCustomerId("123"));
	}
	
	@Test
	public void testUpdateCustomerActivity(){
		List<CustomerActivity> updatecas = new ArrayList<CustomerActivity>();
		List<CustomerActivity> cas = customerActivityService.findCustomerActivityByCustomerId("123");
		for (CustomerActivity ca :cas){
			ca.setActivityDescription("SMS Sent from Customer");
			updatecas.add(ca);
		}
		customerActivityService.updateCustomerActivities(updatecas);
	}
	
	@Test
	public void deleteAllCustomerActivity(){
		customerActivityService.deleteCustomerActivity(new BigInteger("123"));
	}
	
	@Test
	public void testGetAllCustomerActivities(){
		for (CustomerActivity customerActivities : customerActivityService.getAllCustomerActivities()){
			System.out.println(customerActivities.getId() + " | " + customerActivities.getCustomerId()
			+ " | " +  customerActivities.getActivityDescription() + " | " +  customerActivities.getActivityTime()
			+ " | " + customerActivities.getActivityType() + " | " + customerActivities.getSystemName() + " | " +
			customerActivities.getSystemUrl());
		}
		assertTrue(customerActivityService.getAllCustomerActivities().size()>=0);
	}
}

Salesforce Streaming Api using Spring MVC

Check out my Salesforce Streaming Spring MVC project
http://cloudsole-streaming.herokuapp.com/

Find the code here:
https://github.com/thysmichels/cloudsole-force.com-streaming-web

Using Salesforce Streaming in Java project:
Push Topic Factory

package com.example.service;

import com.force.sdk.streaming.client.ForceBayeuxClient;
import com.force.sdk.streaming.client.ForceStreamingClientModule;
import com.force.sdk.streaming.client.PushTopicManager;
import com.force.sdk.streaming.exception.ForceStreamingException;
import com.force.sdk.streaming.model.PushTopic;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class PushTopicFactory {

	public Injector createInjector(){
		Injector injector = Guice.createInjector(new ForceStreamingClientModule());
		return injector;
	}

	public ForceBayeuxClient createClient(Injector injector){
		  ForceBayeuxClient client = injector.getInstance(ForceBayeuxClient.class);
		  return client;
	}
	
	public PushTopicManager createPushTopManager(Injector injector){
		PushTopicManager pushTopicManager = injector.getInstance(PushTopicManager.class);
		return pushTopicManager;
	}
	
	public PushTopic getTopicByName(PushTopicManager pushTopicManager, String topicName) throws ForceStreamingException{
		PushTopic topic = pushTopicManager.getTopicByName(topicName);
		return topic;
	}
	
	public PushTopic createPushTopic(PushTopicManager pushTopicManager, String name, Double apiVersion, String query, String description){
		PushTopic createTopic = pushTopicManager.createPushTopic(new PushTopic(name, apiVersion, query, description));
		return createTopic;
	}
	
	public PushTopic pushTopicFactory(String topicName) throws ForceStreamingException{
		PushTopicFactory pushTopicFactory = new PushTopicFactory();
		Injector injector = pushTopicFactory.createInjector();
		pushTopicFactory.createClient(injector);
		PushTopicManager publicTopicManager = pushTopicFactory.createPushTopManager(injector);
		
		return pushTopicFactory.getTopicByName(publicTopicManager, topicName); 
	}
	
	public ForceBayeuxClient createPushTopicClientFactory(){
		PushTopicFactory pushTopicClientFactory = new PushTopicFactory();
		ForceBayeuxClient fbClient = pushTopicClientFactory.createClient(pushTopicClientFactory.createInjector());
		return fbClient;
	}	
}

Streaming Service

package com.example.service;

import java.io.IOException;

import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.eclipse.jetty.util.log.Log;

import com.example.service.PushTopicFactory;
import com.force.sdk.streaming.client.ForceBayeuxClient;
import com.force.sdk.streaming.client.PushTopicManager;
import com.force.sdk.streaming.exception.ForceStreamingException;
import com.force.sdk.streaming.model.PushTopic;
import com.google.inject.Injector;

public class StreamingService {
	
	public void pushTopicSubScriber(){

		PushTopicFactory pushTopicFactory = new PushTopicFactory();
		Injector injector = pushTopicFactory.createInjector();
		ForceBayeuxClient client = pushTopicFactory.createClient(injector);
		PushTopicManager publicTopicManager = pushTopicFactory.createPushTopManager(injector);
		PushTopic createTopic = pushTopicFactory.createPushTopic(publicTopicManager, "NewAccountPushTopic", 27.0, "select Id, Name from Account", "New Push Topic");

		PushTopic topic = null;
		try {
			topic = pushTopicFactory.getTopicByName(publicTopicManager, createTopic.getName());
		} catch (ForceStreamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		try {
			client.subscribeTo(topic, new ClientSessionChannel.MessageListener() 
			{   
				public void onMessage(ClientSessionChannel channel, Message message) 
				{
					Log.info(message.getJSON());
				}
			});
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}