Now we need to make an http callout method and authenticate with the session ID from the WSC call. For this you will need the Apache commons HTTP client (with logging and codec).
Here are the files that I imported:
- commons-httpclient-3.0.1.jar
- commons-logging-1.1.1.jar
- commons-codec-1.6.jar
With these added to the build path configuration as an external jar, we are now ready to create a new class named SFDCGetApexPDF. Create the class and add the following code to it:
package com.test;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import java.io.*;
public class SFDCGetApexPDF {
public boolean DownloadApexPageAsPDF(String PageURL, String OutputFileName, String accessToken) {
boolean returnvalue = false;
if (accessToken != null && PageURL != null & OutputFileName != null) {
try {
HttpClient client = new HttpClient();
GetMethod PageGet = new GetMethod(PageURL);
PageGet.setRequestHeader("Authorization", "Bearer " + accessToken);
int code = client.executeMethod(PageGet);
System.out.println("HTTP Code: " + String.valueOf(code));
if (String.valueOf(code).contains("200"))
{
System.out.println(">>>> Response was 200!");
OutputStream FileOut = new FileOutputStream(OutputFileName);
ByteArrayOutputStream o = new ByteArrayOutputStream();
o.write(PageGet.getResponseBody(),0,PageGet.getResponseBody().length);
o.writeTo(FileOut);
o.flush();
o.close();
returnvalue = true;
} // look for 200 status code
} catch (Exception e) {
e.printStackTrace();
} // try catch
} // check for null strings
return returnvalue;
} // DownloadApexPageAsPDF
} // end class SFDCGetApexPDF
Now change your main class to look like this (changing the username,password, etc):
package com.test;
import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Opportunity;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class Main {
static EnterpriseConnection connection;
private static QueryResult RecordsToProcess;
private static String SessionID;
public static void main(String[] args) {
boolean ReturnStatus;
String username = "<<<<>>>>";
String password = "<<<<>>>>";
String securityToken = "<<<<>>>>";
String basePageURL = "https://c.na4.visual.force.com/apex/MyPage?id=";
ReturnStatus = APILoginToSalesforce(username,password + securityToken);
System.out.println("Logged in = " + ReturnStatus);
if (ReturnStatus == true) {
RecordsToProcess = RunSOQLQuery("SELECT ID, Name FROM Opportunity LIMIT 10");
if (RecordsToProcess.getSize() > 0) {
SFDCGetApexPDF SFDownloader = new SFDCGetApexPDF();
for (int i=0;i<RecordsToProcess.getRecords().length;i++) {
// cast to Opportunity
Opportunity O = (Opportunity)RecordsToProcess.getRecords()[i];
System.out.println("Processing ID: " + O.getId());
String FileToMake = "C:\\temp\\ApexPage" + i + ".pdf";
String URLToGet = basePageURL + O.getId().toString();
SFDownloader.DownloadApexPageAsPDF(URLToGet,FileToMake, SessionID);
} // loop thru RecordsToProcess
} // RecordsToProcess.getSize() > 0
} // ReturnStatus == true
} // void main
private static QueryResult RunSOQLQuery(String SOQLQueryString) {
QueryResult queryResults = new QueryResult();
try {
queryResults = connection.query(SOQLQueryString);
System.out.println("Found " + queryResults.getSize() + " records");
} catch (Exception e) {
e.printStackTrace();
}
return queryResults;
}
private static boolean APILoginToSalesforce(String USERNAME, String PASSWORD) {
boolean blnAPILoginToSalesforce = false;
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
config.setPassword(PASSWORD);
//config.setTraceMessage(true);
try {
connection = Connector.newConnection(config);
// display some current settings
System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
System.out.println("Service EndPoint: "+config.getServiceEndpoint());
System.out.println("Username: "+config.getUsername());
System.out.println("SessionId: "+config.getSessionId());
SessionID = config.getSessionId();
blnAPILoginToSalesforce = true;
} catch (ConnectionException e1) {
e1.printStackTrace();
}
return blnAPILoginToSalesforce;
} // APILoginToSalesforce
}
Assuming you have the visualforce page in the example and have set the correct options (username, password, etc), you should now get 10 random opportunity's PDF files in C:\temp.
Of course this is just a proof of concept and you will want to remove the hard coding of the user name, password, token, path, etc and replace them with a GUI.
Hello, I wrote an equivalent code using java's URL class. However this is the page I get so the session Id is not correctly registered. However I do set the headers using:
ReplyDeleteurl.openConnection().addRequestProperty("Authorization", "Bearer " + accessToken);
=====
HTTP Code: 200
if (window.location.replace){
window.location.replace('https://login.salesforce.com/?ec=302&startURL=%2Fvisualforce%2Fsession%3Furl%3Dhttps%253A%252F%252Fc.na14.visual.force.com%252Fapex%252FReportPrintOut%253Fid%253D');
} else {;
window.location.href ='https://login.salesforce.com/?ec=302&startURL=%2Fvisualforce%2Fsession%3Furl%3Dhttps%253A%252F%252Fc.na14.visual.force.com%252Fapex%252FReportPrintOut%253Fid%253D';
}
Here is the code:
ReplyDeleteURL url = new URL(PageURL);
url.openConnection().addRequestProperty("Authorization", "Bearer " + config.getSessionId());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
System.out.println("HTTP Code: " + String.valueOf(connection.getResponseCode()));
BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Alexandre,
ReplyDeleteWhy are you not using the Salesforce JDK's connector to setup your initial session?
Thanks