Dropbox OAuth 2.0 Scribe Java Example

Dropbox OAuthServiceConfig and OAuthServiceProvider Bean

<bean id="dropboxServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx" />
		<constructor-arg value="xxx"/>
		<constructor-arg value="https://www.example.com/oauth/dropbox"/>
		<constructor-arg value="com.example.oauth.DropBoxApi20"/>
	</bean>
	
	<bean id="dropboxServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="dropboxServiceConfig" />
	</bean>

Dropbox OAuth Spring MVC 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;

@Controller
@RequestMapping("/oauth/dropbox")
public class DropboxController {
	
	@Autowired
	@Qualifier("dropboxServiceProvider")
	private OAuthServiceProvider dropboxServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;
	
	@RequestMapping(value = "/login-dropbox", method = RequestMethod.GET)
	public String loginToDropBox(Map<String, Object> map, WebRequest request) {
		OAuthService service = dropboxServiceProvider.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 = dropboxServiceProvider.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";
	}
}

DropBoxApi20 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 DropBoxApi20 extends DefaultApi20 {

	@Override
	public String getAccessTokenEndpoint() {
		return "https://api.dropbox.com/1/oauth2/token?grant_type=authorization_code";
	}

	@Override
	public String getAuthorizationUrl(OAuthConfig config) {
		// TODO Auto-generated method stub
		return String.format("https://www.dropbox.com/1/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s", config.getApiKey(), config.getCallback());
	}

	 @Override
	 public Verb getAccessTokenVerb(){
	       return Verb.POST;
	 }
	 
	@Override
    public AccessTokenExtractor getAccessTokenExtractor() {
        return new JsonTokenExtractor();
    }
}

Google OAuth 2.0 Scribe Java Example

Google OAuthServiceConfig and OAuthServiceProvider Bean

<bean id="gdServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx.apps.googleusercontent.com" />
		<constructor-arg value="xxx"/>
		<constructor-arg value="https://www.example.com/oauth/gd"/>
		<!-- <constructor-arg value="openid profile email https://www.googleapis.com/auth/drive.file"/> -->
		<constructor-arg value="com.example.oauth.GoogleDriveOauthApi"/>
	</bean>
	<bean id="gdServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="gdServiceConfig" />
	</bean>
</bean>

Google OAuth Spring MVC 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;

@Controller
@RequestMapping("/oauth/gd")
public class GoogleDriveController {

	@Autowired
	@Qualifier("gdServiceProvider")
	private OAuthServiceProvider gdServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;
	
	@RequestMapping(value = "/login-gd", method = RequestMethod.GET)
	public String loginToGoogleDrive(Map<String, Object> map, WebRequest request) {
		OAuthService service = gdServiceProvider.getService();
		String auth = service.getAuthorizationUrl(EMPTY_TOKEN);
		System.out.println("RequestToken: " + auth);
		return "redirect:" + auth;
	}
	
	@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 = gdServiceProvider.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";
	}
}

Google OAuth extends DefaultApi20

package com.example.oauth;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Verb;
import org.scribe.exceptions.OAuthException;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuth20ServiceImpl;
import org.scribe.oauth.OAuthService;
import org.scribe.utils.OAuthEncoder;
import org.scribe.utils.Preconditions;

public class GoogleDriveOauthApi extends DefaultApi20{

	  private static final String AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%s&redirect_uri=%s";
	    private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
	 
	    @Override
	    public String getAccessTokenEndpoint() {
	        return "https://accounts.google.com/o/oauth2/token";
	    }
	    
	    @Override
	    public AccessTokenExtractor getAccessTokenExtractor() {
	        return new AccessTokenExtractor() {
	            
	            @Override
	            public Token extract(String response) {
	                Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
	 
	                Matcher matcher = Pattern.compile("\"access_token\" : \"([^&\"]+)\"").matcher(response);
	                if (matcher.find())
	                {
	                  String token = OAuthEncoder.decode(matcher.group(1));
	                  return new Token(token, "", response);
	                } 
	                else
	                {
	                  throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
	                }
	            }
	        };
	    }
	 
	    @Override
	    public String getAuthorizationUrl(OAuthConfig config) {
            return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(),
                    OAuthEncoder.encode(config.getCallback()),
                    OAuthEncoder.encode("openid profile email https://www.googleapis.com/auth/drive.file"));
	    }
	    
	    @Override
	    public Verb getAccessTokenVerb() {
	        return Verb.POST;
	    }
	    
	    @Override
	    public OAuthService createService(OAuthConfig config) {
	        return new GoogleOAuth2Service(this, config);
	    }
	    
	    private class GoogleOAuth2Service extends OAuth20ServiceImpl {
	 
	        private static final String GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code";
	        private static final String GRANT_TYPE = "grant_type";
	        private DefaultApi20 api;
	        private OAuthConfig config;
	 
	        public GoogleOAuth2Service(DefaultApi20 api, OAuthConfig config) {
	            super(api, config);
	            this.api = api;
	            this.config = config;
	        }
	        
	        @Override
	        public Token getAccessToken(Token requestToken, Verifier verifier) {
	            OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
	            switch (api.getAccessTokenVerb()) {
	            case POST:
	                request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
	                request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
	                request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
	                request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
	                request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
	                break;
	            case GET:
	            default:
	                request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
	                request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
	                request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
	                request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
	                if(config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, "openid profile email https://www.googleapis.com/auth/drive.file");
	            }
	            Response response = request.send();
	            return api.getAccessTokenExtractor().extract(response.getBody());
	        }
	    }
}

GitHub OAuth 2.0 Scribe Java Example

Github OAuth ServiceConfig and ServiceProvider Bean

<bean id="githubServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx" />
		<constructor-arg value="xxx"/>
		<constructor-arg value="https://www.example.com/oauth/github"/>
		<!--  <constructor-arg value="user,public_repo"/>-->
		<constructor-arg value="com.example.oauth.GithubOauthApi"/>
	</bean>
	<bean id="githubServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="githubServiceConfig" />
	</bean>

Github OAuth Spring MVC 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 org.springframework.web.servlet.ModelAndView;

import com.example.oauth.OAuthServiceProvider;

@Controller
@RequestMapping("/oauth/github")
public class GitHubController {
	
	@Autowired
	@Qualifier("githubServiceProvider")
	private OAuthServiceProvider githubServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;
	
	@RequestMapping(value = "/login-github", method = RequestMethod.GET)
	public String loginToGithub(Map<String, Object> map, WebRequest request) {
		OAuthService service = githubServiceProvider.getService();
		String auth = service.getAuthorizationUrl(EMPTY_TOKEN);
		System.out.println("RequestToken: " + auth);
		return "redirect:" + auth;
	}

	@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) {

		// getting request token
		OAuthService service = githubServiceProvider.getService();
		Token requestToken = (Token) request.getAttribute("oauthRequestToken",
				SCOPE_SESSION);

		// getting access token
		Verifier verifier = new Verifier(oauthVerifier);
		Token accessToken = service.getAccessToken(requestToken, 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
																	
		session.setAttribute("accessToken", accessToken);

		return "settings";
	}
}

GithubOauthApi extends DefaultApi20

package com.example.oauth;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;

public class GithubOauthApi extends DefaultApi20{

	private static final String ACCESSTOKEN="https://github.com/login/oauth/access_token";
	
	@Override
	public String getAccessTokenEndpoint() {
		// TODO Auto-generated method stub
		return ACCESSTOKEN;
	}

	@Override
	public String getAuthorizationUrl(OAuthConfig config) {
		// TODO Auto-generated method stub
		return String.format("https://github.com/login/oauth/authorize?client_id=%s&scope=%s&redirect_uri=%s", config.getApiKey(), config.getScope(), config.getCallback());
	}
}

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();
	 }
}

Force.com OAuth 2.0 Scribe Java Example

OAuthServiceConfig and OAuthServiceProvider Bean in ApplicationContext

<bean id="salesforceServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx" />
		<constructor-arg value="xxxx"/>
		<constructor-arg value="https://www.example.com/oauth/salesforce"/>
		<constructor-arg value="com.example.oauth.SalesforceOauthApi"/>
	</bean>
	<bean id="salesforceServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="salesforceServiceConfig" />
	</bean>

SalesforceOauthApi 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 SalesforceOauthApi extends DefaultApi20{

	private static final String ACCESSTOKEN = "https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code";
	
	@Override
	public String getAccessTokenEndpoint() {
		return ACCESSTOKEN;
	}

	@Override
	public String getAuthorizationUrl(OAuthConfig config) {
		return String.format("https://login.salesforce.com/services/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s&display=popup&scope=%s", config.getApiKey(), config.getCallback(), "full refresh_token");
	}
	
	 @Override
	 public Verb getAccessTokenVerb(){
	       return Verb.POST;
	 }
	
	@Override
	 public AccessTokenExtractor getAccessTokenExtractor() {
	    return new JsonTokenExtractor();
	 }
}

Spring MVC SalesforceController for requesting access token

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;

@Controller
@RequestMapping("/oauth/salesforce")
public class SalesforceController {

	@Autowired
	@Qualifier("salesforceServiceProvider")
	private OAuthServiceProvider salesforceServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;

	@RequestMapping(value = "/login-salesforce", method = RequestMethod.GET)
	public String loginToSalesforce(Map<String, Object> map, WebRequest request) {
		OAuthService service = salesforceServiceProvider.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 = salesforceServiceProvider.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";
	}
}

Heroku Elastic Search Example

Elastic search configuration

package com.example.elasticsearch;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.ClientConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JestConfiguration {

	@Bean
	public JestClient jestClient(){
		// Configuration
		ClientConfig clientConfig = new ClientConfig.Builder(System.getenv("SEARCHBOX_URL"))
		.multiThreaded(true).build();

		// Construct a new Jest client according to configuration via factory
		JestClientFactory factory = new JestClientFactory();
		factory.setClientConfig(clientConfig);
		JestClient client = factory.getObject();
		return client;
	}
}

Elastic search service

package com.example.elasticsearch;

import java.util.List;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.IndicesExists;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import com.example.jpa.JpaCustomerService;
import com.example.model.Customer;
import com.example.service.CustomerService;

@Service
@Import(JpaCustomerService.class)
public class JestService {

	@Autowired @Qualifier("jpaRepository") CustomerService jpaCustomerService;
	
	@Autowired JestClient jestClient;
	
    @Autowired
	public void createCustomerIndex(){
		try {
			IndicesExists indicesExists = new IndicesExists.Builder().build();
	        JestResult result = jestClient.execute(indicesExists);

            if (!result.isSucceeded()) {
                // Create customer index
                CreateIndex createIndex = new CreateIndex.Builder("customers").build();
                jestClient.execute(createIndex);
            }
      
            Bulk bulk = new Bulk.Builder()
		 	.addAction(new Index.Builder(jpaCustomerService.getAllCustomers()).index("customer").type("customer").build())
		    .build();

            result = jestClient.execute(bulk);

            System.out.println(result.getJsonString());
	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<Customer> searchCustomers(String customerQuery){
		try {
			SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
	        searchSourceBuilder.query(QueryBuilders.queryString(customerQuery));
	        
	        Search search = new Search.Builder(searchSourceBuilder.toString())
	        .addIndex("customer")
	        .addType("customer")
	        .build();
	
	        JestResult result = jestClient.execute(search);
			return result.getSourceAsObjectList(Customer.class);
		        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return null;
	}
}

Spring JPA Embeddable Id example

Embeddable Entity

package com.sforce.model;

import java.io.Serializable;
import javax.persistence.*;

@Embeddable
public class MonthlyPK implements Serializable {
	
	private static final long serialVersionUID = 1L;

	@Column(name="AID")
	private long aid;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="N_DATE")
	private java.util.Date nDate;

	public MonthlyPK() {
	}
	public long getAid() {
		return this.aid;
	}
	public void setAid(long aid) {
		this.aid = aid;
	}
	public java.util.Date getNDate() {
		return this.nDate;
	}
	public void setNDate(java.util.Date nDate) {
		this.nDate = nDate;
	}

	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (!(other instanceof MonthlyPK)) {
			return false;
		}
		MonthlyPK castOther = (MonthlyPK)other;
		return 
			(this.aid == castOther.aid)
			&& this.nDate.equals(castOther.nDate);
	}

	public int hashCode() {
		final int prime = 31;
		int hash = 17;
		hash = hash * prime + ((int) (this.aid ^ (this.aid >>> 32)));
		hash = hash * prime + this.nDate.hashCode();
		
		return hash;
	}
}

Embeddable Id as @Id

package com.sforce.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.io.Serializable;

import java.math.BigDecimal;
import java.util.Date;

@Entity 
@Table(name="DEV$MONTHLY")
public class DevMonthly implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private MonthlyNarPK monthlyNarPK;
	
	@Column(name="AID", insertable=false, updatable=false)
	private Long id;

	@Column(name="CHNG_STATUS")
	private BigDecimal chngStatus;

	@Column(name="NAR")
	private BigDecimal nar;

	@Column(name="SF_AMID")
	private String sfAmid;
	
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="NAR_DATE", insertable=false, updatable=false)
	private Date narDate;

	public DevMonthly() {}
	
	public DevMonthly(String sfAmid){
		this.sfAmid = sfAmid;
	}
	
	public DevMonthly(Long id, String sfAmid, Date narDate) {
		this.id = id;
		this.sfAmid = sfAmid;
		this.narDate = narDate;
	}

	public Long getId() {
		return this.id;
	}

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

	public BigDecimal getChngStatus() {
		return this.chngStatus;
	}

	public void setChngStatus(BigDecimal chngStatus) {
		this.chngStatus = chngStatus;
	}

	public BigDecimal getNar() {
		return this.nar;
	}

	public void setNar(BigDecimal nar) {
		this.nar = nar;
	}

	public String getSfAmid() {
		return this.sfAmid;
	}

	public void setSfAmid(String sfAmid) {
		this.sfAmid = sfAmid;
	}

	public Date getNarDate() {
		return narDate;
	}

	public void setNarDate(Date narDate) {
		this.narDate = narDate;
	}
}

Apex Trigger Before Update Before Insert Example

trigger addSalesRepToLCR on LawyerConnectionRequest__c (before insert, before update) 
{       
    if (Trigger.isUpdate || Trigger.isInsert)
    {
        Set<Id> contactIds = new Set<Id>();
        for (LawyerConnectionRequest__c lcrToGetContactIds : Trigger.New)
        {
            contactIds.add(lcrToGetContactIds.Client__c);
        }

        Map<Id, Contact> mapOfUsers = new Map<Id, Contact>([select Id, Owner.Id, Owner.Profile.Name from Contact where Id In :contactIds]);
        for (LawyerConnectionRequest__c lcr : Trigger.New)
        {
            if (lcr.Client__c != null)
            {
                Contact newUser = mapOfUsers.get(lcr.Client__c);
                if (newUser.Owner.Profile.Name == 'Rocket Lawyer Sales')
                {
                    lcr.Sales_Rep__c = newUser.Owner.Id;
                }
            }
        }       
    }
}