Skip to content

Instantly share code, notes, and snippets.

@Ergin008
Last active October 13, 2015 08:08
Show Gist options
  • Save Ergin008/4165715 to your computer and use it in GitHub Desktop.
Save Ergin008/4165715 to your computer and use it in GitHub Desktop.
Get Envelope Documents
// DocuSign API Walkthrough 06 in Java - Get Envelope Document List and Download Documents
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
public class getEnvelopeDocuments
{
public static void main(String[] args) throws Exception
{
//------------------------------------------------------------------------------------
// ENTER VALUES FOR THE FOLLOWING 4 VARIABLES:
//------------------------------------------------------------------------------------
String integratorKey = "***"; // integrator key (found on Preferences -> API page)
String username = "***"; // account email (or your API userId)
String password = "***"; // account password
String envelopeId = "***"; // enter envelopeId of an envelope in your account
//------------------------------------------------------------------------------------
// construct the DocuSign authentication header
String authenticationHeader =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
// additional variable declarations
String baseURL = ""; // we will retrieve this through the Login API call
String accountId = ""; // we will retrieve this through the Login API call
String url = ""; // end-point for each api call
String body = ""; // request body
String response = ""; // response body
int status; // response status
HttpURLConnection conn = null; // connection object used for each request
//============================================================================
// STEP 1 - Make the Login API call to retrieve your baseUrl and accountId
//============================================================================
url = "https://demo.docusign.net/restapi/v2/login_information";
body = ""; // no request body for the login call
// create connection object, set request method, add request headers
conn = InitializeRequest(url, "GET", body, authenticationHeader);
// send the request
System.out.println("Step 1: Sending Login request...\n");
status = conn.getResponseCode();
if( status != 200 ) // 200 = OK
{
errorParse(conn, status);
return;
}
// obtain baseUrl and accountId values from response body
response = getResponseBody(conn);
baseURL = parseXMLBody(response, "baseUrl");
accountId = parseXMLBody(response, "accountId");
System.out.println("-- Login response --\n\n" + prettyFormat(response, 2) + "\n");
//============================================================================
// STEP 2 - Get Envelope Document List
//============================================================================
// append "/envelopes/{envelopeId}/documents" to baseUrl and use in request
url = baseURL + "/envelopes/" + envelopeId + "/documents";
body = ""; // no request body for this call
// re-use connection object for second request...
conn = InitializeRequest(url, "GET", body, authenticationHeader);
System.out.println("Step 2: Retrieving document information for envelope " + envelopeId + ".\n");
status = conn.getResponseCode(); // triggers the request
if( status != 200 ) // 200 = OK
{
errorParse(conn, status);
return;
}
// display results
response = getResponseBody(conn);
System.out.println("-- Get Documents List response --\n\n" + prettyFormat(response, 2));
//============================================================================
// STEP 3 - Download Envelope Documents
//============================================================================
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[1]/*[local-name()='envelopeDocument']");
Object result = expr.evaluate(new InputSource(new StringReader(response.toString())), XPathConstants.NODESET);
// read document list response, parse URIs, count number of documents
int cnt = -1;
NodeList documents = (NodeList) result;
String[] docNames = new String[documents.getLength()];
String[] docURIs = new String[documents.getLength()];
for (int i = 0; i < documents.getLength(); i++)
{
Node node = documents.item( i );
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
NodeList docNodes = node.getChildNodes();
for (int j = 0; j < docNodes.getLength(); j++)
{
if( docNodes.item(j).getLocalName().equals("name"))
{
// store each document name and increment running counter
docNames[++cnt] = docNodes.item(j).getTextContent();
}
if( docNodes.item(j).getLocalName().equals("uri"))
{
// store each document uri as well
docURIs[cnt] = docNodes.item(j).getTextContent();
}
}
}
}
for( int i = 0; i < docURIs.length; i++)
{
url = baseURL + docURIs[i]; // each document has its own unique uri
body = ""; // no request body for this call
conn = InitializeRequest(url, "GET", body, authenticationHeader);
// envelope documents are always converted to PDFs in the DocuSign platform
conn.setRequestProperty("Accept", "application/pdf");
System.out.println("Retrieving envelope document \"" + docNames[i] + "\"...\n");
status = conn.getResponseCode(); // triggers the request
if( status != 200 ) // 200 = OK
{
errorParse(conn, status);
return;
}
// request body is a byte array of PDF data, write to a local file...
writePDFBytesToFile(conn, docNames[i]);
}
System.out.println("\nDone downloading document(s)!");
} //end main()
//***********************************************************************************************
//***********************************************************************************************
// --- HELPER FUNCTIONS ---
//***********************************************************************************************
//***********************************************************************************************
public static HttpURLConnection InitializeRequest(String url, String method, String body, String httpAuthHeader) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("X-DocuSign-Authentication", httpAuthHeader);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
if (method.equalsIgnoreCase("POST"))
{
conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
conn.setDoOutput(true);
// write body of the POST request
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(body); dos.flush(); dos.close();
}
return conn;
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static String parseXMLBody(String body, String searchToken) {
String xPathExpression;
try {
// we use xPath to parse the XML formatted response body
xPathExpression = String.format("//*[1]/*[local-name()='%s']", searchToken);
XPath xPath = XPathFactory.newInstance().newXPath();
return (xPath.evaluate(xPathExpression, new InputSource(new StringReader(body))));
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static String getResponseBody(HttpURLConnection conn) {
BufferedReader br = null;
StringBuilder body = null;
String line = "";
try {
// we use xPath to get the baseUrl and accountId from the XML response body
br = new BufferedReader(new InputStreamReader( conn.getInputStream()));
body = new StringBuilder();
while ( (line = br.readLine()) != null)
body.append(line);
return body.toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static void writePDFBytesToFile(HttpURLConnection conn, String docName) {
FileOutputStream fop = null;
File file;
try {
file = new File(docName);
fop = new FileOutputStream(file);
byte[] buffer = new byte[1024 /* we write the pdf in chunks of 1024 */];
int numRead;
while((numRead = conn.getInputStream().read(buffer)) > 0) {
fop.write(buffer, 0, numRead);
}
fop.flush();
fop.close();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static void errorParse(HttpURLConnection conn, int status) {
BufferedReader br;
String line;
StringBuilder responseError;
try {
System.out.print("API call failed, status returned was: " + status);
InputStreamReader isr = new InputStreamReader( conn.getErrorStream() );
br = new BufferedReader(isr);
responseError = new StringBuilder();
line = null;
while ( (line = br.readLine()) != null)
responseError.append(line);
System.out.println("\nError description: \n" + prettyFormat(responseError.toString(), 2));
return;
}
catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
} // end class
@suganyadevi88
Copy link

Hi I am tried this code, the document is downloaded successfully but the downloaded document is to be opened then the following message will be occured, the message is, could not open document_o.pdf because it is either not a supported file type or because the file has been demaged (for example, it was sent as an email attachements and wasn't correctly decoded). any solutions. thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment