• neelam moore
  • NEWBIE
  • 10 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 3
    Replies
Hi Everyone,

I am trying to invoke  an apex  from a java class which takes in a parameter using the salesforce REST api . I already have the logic to retrive the access token via oAuth but not sure  but i m not  sure how i should pass the parameters value via the REST call and also invoke the execute() .

I execute this APEX in the Salesforce developer console (Anonymous Window) as follows : 

ApexClass apexClass = new ApexClass('param', false); 
Database.executeBatch(apexClass, 100);

Now I need to execute the same block form my java code.

Any help is highly appreciated!
 
Hi All,

I m trying to delete a content version record from my java code using REST api using HTTPDelete :

HttpDelete delete = new HttpDelete(baseUri+"/sobjects/ContentVersion/"+v);
where delete.getURI() = https:// xxx.my.salesforce.com/services/data/v35.0/sobjects/ContentVersion/06824000000aAqlAAE

HttpResponse  response = htttpCient.execute(delete);

but i get a status 401 on delete. This same URI works if if i delete a Account object without an issue. Can anyone please help ? I would really appriciate it!

Thank you!
Hi,

I wanted to test the REST connectivity from a stand alone java code. Since the couldnt find an example online i modified the current rest demo available in the salesforce api to use SOAP login instead of oAuth login. I read somewhere in this forum that we can use the soap login to obtain the user sessionId which can be used to make rest api.  So I tried to modify the rest demo code as shown below . I was able to connect successfully to salesforc test environmet and get the session id. I m i using this session id in place of the the accesstoken to set the get method's request header. But now i m getting a connection time out error .  I  did set the proxy host and port correctly so I doubt it can be a proxy issue as i was also able to connecti using the SOAP Enterprise connection. I m not sure i m doing this the right way can someone please guide me or point out any mistakes i made ? 

Code :

package com.cww.salesforce.restapi;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.Header;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class DemoREST extends HttpServlet {
 private static final long serialVersionUID = 1L;
 public DemoREST(){
   
 }
 static EnterpriseConnection connection;
 static String sessionId;
 //Header oauthHeader;
 //Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
 
 private void showAccounts(String instanceUrl, String accessToken,
  PrintWriter writer) throws ServletException, IOException {
  HttpClient httpclient = new HttpClient();
  //HttpHost proxy = new HttpHost("" ,8080);
  //httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
  GetMethod get = new GetMethod(instanceUrl+ "/services/data/v36.0/query");
  // set the token in the header
  get.setRequestHeader("Authorization", "OAuth " + accessToken);
  NameValuePair[] params = new NameValuePair[1];
  params[0] = new NameValuePair("q",
    "SELECT Name, Id from Account LIMIT 100");
  get.setQueryString(params);
  try {
   httpclient.executeMethod(get);
   if (get.getStatusCode() == HttpStatus.SC_OK) {
    // Now lets use the standard java json classes to work with the
    // results
    try {
     JSONObject response = new JSONObject(
       new JSONTokener(new InputStreamReader(
         get.getResponseBodyAsStream())));
     System.out.println("Query response: "
       + response.toString(2));
     writer.write(response.getString("totalSize")
       + " record(s) returned\n\n");
     JSONArray results = response.getJSONArray("records");
     for (int i = 0; i < results.length(); i++) {
      writer.write(results.getJSONObject(i).getString("Id")
        + ", "
        + results.getJSONObject(i).getString("Name")
        + "\n");
     }
     writer.write("\n");
    } catch (JSONException e) {
     e.printStackTrace();
     throw new ServletException(e);
    }
   }
  } finally {
   get.releaseConnection();
  }
 }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 
 public static void main(String[] args) throws ServletException, IOException  {
     
    
  DemoREST dmt = new DemoREST();
      boolean sucess = dmt.login();
      if(sucess){
      
      PrintWriter writer = new PrintWriter("C:/temp_plabon/SalesforceFiles/OutPut.txt");
      String accessToken = sessionId;
      String instanceUrl = "https://test.salesforce.com";
      if (accessToken == null) {
       writer.write("Error - no access token");
       return;
      }
      writer.write("We have an access token: " + accessToken + "\n"
        + "Using instance " + instanceUrl + "\n\n");
      dmt.showAccounts(instanceUrl, accessToken, writer);
    }
 private boolean login(){
  boolean success = false;
  try {
   
         ConnectorConfig config = new ConnectorConfig();
  Properties props = new Properties();  // template properties
  InputStream is = null;
         String authEndpoint ="https://test.salesforce.com/services/Soap/c/36.0";        
         config.setProxy("proxyhost" ,porxyPort);;
  config.setUsername("username");
  config.setPassword("Password");
         config.setAuthEndpoint(authEndpoint);
  Connection = new EnterpriseConnection(config);
  sessionId = connection.getSessionHeader().getSessionId();
  success = true;
  } catch (ConnectionException ce) {
   ce.printStackTrace();
  } //catch (IOException fe){
  // fe.printStackTrace();
  //}
  return success;
  
 }
}


===============Exception :=================

Mar 31, 2016 5:48:46 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Mar 31, 2016 5:48:46 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Mar 31, 2016 5:49:07 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Mar 31, 2016 5:49:07 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Mar 31, 2016 5:49:28 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Mar 31, 2016 5:49:28 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:381)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:243)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:230)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:377)
at java.net.Socket.connect(Socket.java:539)
at com.ibm.jsse2.SSLSocketImpl.connect(SSLSocketImpl.java:340)
at com.ibm.jsse2.SSLSocketImpl.<init>(SSLSocketImpl.java:68)
at com.ibm.jsse2.SSLSocketFactoryImpl.createSocket(SSLSocketFactoryImpl.java:5)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:81)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:126)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
at com.cww.salesforce.restapi.DemoREST.showAccounts(DemoREST.java:71)
at com.cww.salesforce.restapi.DemoREST.main(DemoREST.java:281)

 
Hi All,

I m trying to delete a content version record from my java code using REST api using HTTPDelete :

HttpDelete delete = new HttpDelete(baseUri+"/sobjects/ContentVersion/"+v);
where delete.getURI() = https:// xxx.my.salesforce.com/services/data/v35.0/sobjects/ContentVersion/06824000000aAqlAAE

HttpResponse  response = htttpCient.execute(delete);

but i get a status 401 on delete. This same URI works if if i delete a Account object without an issue. Can anyone please help ? I would really appriciate it!

Thank you!
I am getting an error when trying a file into Chatter via RestAPI.

[{"errorCode":"POST_BODY_PARSE_ERROR","message":"Binary data included but file attachment information is missing. If providing rich JSON/XML input in multipart REST, make sure to include Content-Type header in the part."}]

Here is a snippet of my code, what am I missing?
 
DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost;
        MultipartEntity reqEntity;
        httppost = new HttpPost(RES_URL);
        reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        File imageFile = new File(
                "/salesforce/wsdl/test.txt");
        FileBody bin = new FileBody(imageFile);
        reqEntity.addPart("feedItemFileUpload", bin);
        String fileName = "test.txt";
        // file name can be text plain only, though using text/html doesn't breaks
        reqEntity.addPart("fileName", new StringBody(fileName, "text/plain",
                Charset.defaultCharset()));

        httppost.setEntity(reqEntity);

        httppost.setHeader("Authorization",         "OAuth " + logon());

        String response = EntityUtils.toString(httpclient.execute(httppost)
                .getEntity(), "UTF-8");

        System.out.println(response);

 

Hi all,

 

I have tried to find some sample code on developer.force.com for how to upload to Content via API, unsuccessfully unfortunately. I would basically like to automate the batch-upload of a set of files, creating a new item in Content for each file. 

Does anyone have a link with some sample code in Java that I could use to get started?

 

Kind regards,

Martin