Posting a comment along with an attachment to salesforce chatter using java

717 Views Asked by At

I had to post a message to a chatter group within our organization when a user submits his application for grants. I was searching through the web and found that there are many postings but nobody talked about all the steps required to post a comment to chatter group. Through this post I want to help some other users who are looking for similar solution.

First and foremost one has to create a salesforce developer account.

1) login to salesforce developer account and click on setup -> Build -> Create -> Apps scroll down and click on new in a Connected Apps section and create a connected app by entering basic Information and click Enable OAuth Settings to open the API section

2) Obtain the consumer key and secret. Here is the URL explaining about this process (Scroll down to topic 'Configuring OAuth 2.0 Access for your Application')

https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com

3) Now click on logged in user name-> My Settings-> Personal-> Reset My Security Token once you click this, an email will be sent to your registered email account with security token.

4) Create a group in Chatter and click on the group name and copy the group id(g=0F9FXXX) from browser bar (https://na1x.salesforce.com/...../GroupProfilePage?g=0F9Fxxxxxxxxxxxxxf) into your file and keep it.

5) Once we are done with chatter let us move to Java application to post comment to a group

Here is the java helper class I used to post a comment along with an attachment. Both commons-httpclient-3.1 and httpclient-4.3.jar are required along with jsonxxxx.jar

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

public class ChatterHelper
{
  public static void postOnChatterGroup()
 {
 public static final String SALESFORCE_USERNAME = "[email protected]";
 public static final String SALESFORCE_PASSWORD = "password+securityToken";
 public static final String SALESFORCE_CONSUMER_KEY="3MVG9JZ_r.Qzxxx.xxx.xxxx.xxx.xx1";
 public static final String SALESFORCE_SECRET = "345345345345345345";
 public static final String SALESFORCE_CHATTER_GROUP = "0F9xxxxxxxxxxx";
try
{
  StringBuffer sbf = new StringBuffer();
  RequestConfig requestConfig =    RequestConfig.custom().setSocketTimeout(30000).
  setConnectTimeout(30000).build();
  CloseableHttpClient httpClient = HttpClients.createDefault();
  String baseUrl =  "https://na1.salesforce.com/services/oauth2/token";
  // Send a post request to the OAuth URL.
  HttpPost oauthPost = new HttpPost(baseUrl);
  oauthPost.setConfig(requestConfig);
  List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
  // keep this as it is
  parametersBody.add(new BasicNameValuePair("grant_type", "password"));
  parametersBody.add(new BasicNameValuePair("username", SALESFORCE_USERNAME));
  parametersBody.add(new BasicNameValuePair("password", SALESFORCE_PASSWORD));
  parametersBody.add(new BasicNameValuePair("client_id", SALESFORCE_CONSUMER_KEY));
  parametersBody.add(new BasicNameValuePair("client_secret", SALESFORCE_SECRET));
  oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody));
  // Execute the request.
  HttpResponse response = httpClient.execute(oauthPost);
  HttpEntity entity = response.getEntity();
  if (entity != null)
  {
   BufferedReader rd = new BufferedReader(new InputStreamReader(
   entity.getContent(), "UTF-8"));
    String line = "";
    while ((line = rd.readLine()) != null)
    {
      sbf.append(line);
    }
  }
  JSONObject jObj = new JSONObject(sbf.toString());
  String accessToken = jObj.get("access_token").toString();
  String instanceUrl = jObj.get("instance_url").toString();
  String textMsg = "Here is the comment";
  File contentFile = new File("c:/xyz/abc.pdf");
  String desc = "This file is uploaded by xyz user";
  String fileName = "View PDF";
  final PostMethod postMethod = new PostMethod(instanceUrl +
  "/services/data/v23.0/chatter/feeds/record/" + 
  SALESFORCE_CHATTER_GROUP + "/feed-items");
  Part[] parts = {
      new StringPart("desc", desc),
      new StringPart("fileName", fileName),
      new StringPart("text", textMsg),
      new FilePart("feedItemFileUpload", contentFile),
  };
  postMethod.setRequestEntity(new MultipartRequestEntity(parts,  
  postMethod.getParams()));
  postMethod.setRequestHeader("Authorization", "OAuth " + accessToken);
  postMethod.addRequestHeader("X-PrettyPrint", "1");
  HttpClient client = new HttpClient();
  client.getParams().setSoTimeout(Constant.URL_SOCKET_TIMEOUT);
  client.executeMethod(postMethod);
}
catch (Exception e)
{
  e.printStackTrace();
}
 }
}

6) Go back to chatter and you should see a message along with abc.pdf.

Hope it helps some one.

0

There are 0 best solutions below