Salesforce data access via Java portal

Java portal to Access Salesforce Data

I am going to explain to access salesforce data through java portal via heroku. The following steps to consider before start work.
  1. The salesforce need to provide out side server access. Then only we can get salesforce data through Rest Api.
  2. In Java application what kind of service going to use whether WSDL lib or you can write your own login handshake code.
  3. Should know how to push and deploy in Heroku using  java application.
In this example i am going to use my own custom login in example code. That will explain you how to log in using rest in java application. Before write java application, you should know which Http client lib you are going to use.
In this example i am used the following libs,
  1. Maven 3.3.1
  2. Java 1.7
  3. Jersey rest
  4. Apache http client
  5. Jackson- json
The first step to get salesforce gateway to allow us to connect with them. First create a salesforce account. Now i am using my developer account and explain you. How the salesforce want to allow our java application to connect with them. Use the below steps,

Step1: Login salesforce account and go to setup page. See the below screen shot,



Step 2: Then goto Create and click Apps. It display like below image 


Step 3: Then click new in connected Apps .

After that you can write java code or any other language to develop you r application.

Note : your application must be run on the above given call back url.

The below sample java code used to handshake with salesforce and make generic GET and POST call. 

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package com.aspigrow.salesforce;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.PartBase;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.json.JSONObject;
import org.json.JSONTokener;

import pl.jsolve.templ4docx.core.Docx;
import pl.jsolve.templ4docx.core.VariablePattern;
import pl.jsolve.templ4docx.variable.TextVariable;
import pl.jsolve.templ4docx.variable.Variables;

import com.aspigrow.salesforce.model.OAuth;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Class provide the salesforce util to performce the CRUD operation
 * and it return perform login utility to validate the appropriate user
 * 
 * @author ramachandran
 */
public class SalesforceUtil {
 
 private static final String OAUTH2LOGINURL = "https://login.salesforce.com/services/oauth2/token";
 
 private static final String CLIENT_ID = "**********************************************8";
 
 private static final String CLIENT_SECRET = "************************";
 
 private static final String S_USERNAME = "**************";
 
 private static final String S_PASSWORD = "************************";
 
 private static final String LOGIN_GRANT_TYPE = "password";
 
 private static final ObjectMapper objectMapper = new ObjectMapper();
 
 private static final HttpClient httpClient = new HttpClient();
 
 /**
  * Function used to get the salesforce access token
  * for further operation to access the salesforce object data
  * 
  * @return
  */
 public static final OAuth getOauth2Token() {
  OAuth oauth= null;
  PostMethod post = new PostMethod(OAUTH2LOGINURL);
  try{
   String postUrlBody = "grant_type="+LOGIN_GRANT_TYPE+"&client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&username="+
          S_USERNAME+"&password="+S_PASSWORD;
   post.setRequestBody(postUrlBody);
   post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   post.setRequestHeader("Accept", "application/json");
   httpClient.executeMethod(post);
   if(post.getStatusCode() == HttpStatus.SC_OK){
    JSONObject response = new JSONObject(
                     new JSONTokener(new InputStreamReader(
                             post.getResponseBodyAsStream())));
            oauth = (OAuth) objectMapper.readValue(response.toString(2), OAuth.class);
            oauth.setLoggedIn(true);
            return oauth;
   } else {
    oauth = new OAuth();
    oauth.setLoggedIn(false);
    return oauth;
   }
  } catch(Exception ex) {
   System.out.println("Exception Whle salesforce Login duo to "+ ex.getMessage());
   ex.printStackTrace();
   oauth = new OAuth();
   oauth.setLoggedIn(false);
   return oauth;
  } finally {
   post.releaseConnection();
  }
 }
 
 /**
  * Function used to make post call to access salesforce instance 
  * 
  * @param request
  * @return
  */
 public static final JSONObject makePostCall(Request request) {
  PostMethod post = new PostMethod(request.getUrl());
  try{
   if(request == null || request.getUrl() == null)
    return null;
   post.setRequestBody(request.getBody());
   for(String key : request.getHeaders().keySet()) {
    post.setRequestHeader(key, request.getHeaders().get(key));
   }
   httpClient.executeMethod(post);
   if(post.getStatusCode() == HttpStatus.SC_OK)
    return new JSONObject( new JSONTokener(new InputStreamReader(
     post.getResponseBodyAsStream())));
   return null;
  } catch(Exception ex) {
   System.out.println("Exception occured while make post call : "+ex.getMessage());
   return null;
  } finally {
   post.releaseConnection();
  }
 }
 
 /**
  * Make generic get call to saleforce instance
  * 
  * @param request
  * @return
  * @throws Exception
  */
 public static final JSONObject makeGetCall(Request request) throws Exception {
  GetMethod get = new GetMethod(request.getUrl());
  try{
   if(request == null || request.getUrl() == null)
    return null;
   for(String key : request.getHeaders().keySet()) {
    get.setRequestHeader(key, request.getHeaders().get(key));
   }
   httpClient.executeMethod(get);
   if(get.getStatusCode() == HttpStatus.SC_OK)
    return new JSONObject( new JSONTokener(new InputStreamReader(
     get.getResponseBodyAsStream())));
   return null;
  } catch(Exception ex) {
   System.out.println("Exception occured while make get call : "+ex.getMessage());
   return null;
  } finally {
   get.releaseConnection();
  }
 }
 
 /**
  * Download the file from salesforce instance and write back in local server
  * 
  * @param request
  * @param fileName
  * @return
  * @throws Exception
  */
 public static final String downloadDocument(Request request, String fileName) throws Exception {
  GetMethod get = new GetMethod(request.getUrl());
  try{
   if(request == null || request.getUrl() == null)
    return null;
   for(String key : request.getHeaders().keySet()) {
    get.setRequestHeader(key, request.getHeaders().get(key));
   }
   httpClient.executeMethod(get);
   if(get.getStatusCode() == HttpStatus.SC_OK) {
    byte[] contents = get.getResponseBody();
    XWPFDocument doc = new XWPFDocument();
    File f = new File(fileName);
    if(f.exists())
     f.deleteOnExit();
    FileOutputStream out = new FileOutputStream(f);
    out.write(contents);
    doc.setTrackRevisions(true);
       doc.write(out);
       out.close();
       doc.close();
       return "1";
   }
   return null;
  } catch(Exception ex) {
   ex.printStackTrace();
   System.out.println("Exception occured while make get call : "+ex.getMessage());
   return null;
  } finally {
   get.releaseConnection();
  }
 }
 
 /**
  * Attachment the document file to salesforce instance object
  * 
  * @param request
  * @param params
  * @param fileName
  * @return
  */
 public static final boolean attachFile(Request request, String params, String fileName) {
  PostMethod post = new PostMethod(request.getUrl());
  try{
   File attachmentFile = new File(fileName);
   Part[] parts = new Part[] {
      new JsonPart("Json", params) ,
              new FilePart("Body", attachmentFile)
       };
   for(String key : request.getHeaders().keySet()) {
    post.setRequestHeader(key, request.getHeaders().get(key));
   }
   post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
   int status = httpClient.executeMethod(post); 
           // String response = post.getResponseBodyAsString();
   System.out.println(" status : " + status);          
       //  System.out.println("Response Content Length : " + post.getResponseContentLength());         
        // System.out.println("response : " + response);            
       //  System.out.println(" getStatusCode " + post.getStatusCode() + " getStatusText : " + post.getStatusText());
   if (post.getStatusCode() == HttpStatus.SC_CREATED) {
                return true;
            } 
  } catch(Exception ex){
   ex.printStackTrace();
  } finally {
         post.releaseConnection();
     }
  return false;
 }

 /**
  * Class to provide the json part params
  * 
  * @author ramachandran
  */
    private static class JsonPart extends PartBase {

        private byte[] bytes;

        public JsonPart(String name, String json) throws IOException {
            super(name, "application/json", "UTF-8", null);
            this.bytes = json.getBytes("UTF-8");
        }

        @Override
        protected void sendData(OutputStream os) throws IOException {
            os.write(bytes);
        }

        @Override
        protected long lengthOfData() throws IOException {
            return bytes.length;
        }
    }
}

getOauth2Token to get salesforce oauth2 token.Using this oauth2 token to make further call to salesforce and get the need data from the salesforce.

attachFile function used to upload the attachment document to any standard ort custom object in salesforce.
downloadDocument function download the document from salesforce.It receive the document as binary format. we can save it as our wish format. I am used apache poi to save this as word document.
Other two functions used to make the post or get call to salesforce.

I will continue to next post java application in heroku.
 

Comments

Popular posts from this blog

Pyhton auto post to blogger using Google blogger API

Connect VPN via Python

Salesforce Missing Organization Feature: CommonPortal null