Cloud - Upload Template using Java via API

This example shows how to upload a template to the cloud using Java.  It calls the Docmosis REST API to upload a local template file to the cloud.

The sample code includes the instructions to get started. You will need a Free Trial and then plug your Docmosis Cloud access key into the code below, then run.

Note: This code sample is written to specifically work with DWS4.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * This sample code implements a template upload request by constructing the HTTP request 
 * to the Docmosis Cloud Service manually.  Typically a HTTP client library would make 
 * multipart form posting easier.
 * 
 * There are several constants at the top of this file which you can modify to
 * suit your test. You need to set:
 * 
 * ACCESS_KEY - this key is your unique access to the Docmosis services (keep it
 * safe). You can see your access key in your Account Settings in the Cloud area
 * Docmosis web site.
 * UPLOAD_FILE - the template to upload
 * 
 * If you have troubles connecting, it is likely because you have a proxy server
 * you need to configure. See the PROXY_* settings below to enable it.
 * 
 * Copyright Docmosis 2019
 * 
 */
public class UploadTemplateExample {

	// Set your region here.
	// End-point in the USA
	private static final String DWS_URL = "https://us1.dws4.docmosis.com/api/uploadTemplate";
	// End-point in the EU
	//private static final String DWS_URL = "https://eu1.dws4.docmosis.com/api/uploadTemplate";
	// End-point in AUS
	//private static final String DWS_URL = "https://au1.dws4.docmosis.com/api/uploadTemplate";

	// Set your access key here. This is visible in your cloud account in the
	// Docmosis Web Site.
	// It is your key to accessing your service - keep it private and safe.
	private static final String ACCESS_KEY = "XXX";
	
	// The file to upload to the Docmosis cloud service
	private static final String UPLOAD_FILE = "templates/myTemplate.docx";

	// Proxy settings if needed to reach the internet
	private static final String PROXY_HOST = "";
	private static final String PROXY_PORT = "";
	private static final String PROXY_USER = "";
	private static final String PROXY_PASSWD = "";

	private static final String LINE_END = "\r\n";

	/*
	 * Get a connection to the Docmosis upload template service
	 */
	private static HttpURLConnection getConnection(String boundary)
			throws MalformedURLException, IOException {

		HttpURLConnection conn = (HttpURLConnection) new URL(DWS_URL)
				.openConnection();

		// PROXY Setup
		// if you have a proxy, set the values here to make sure you can reach
		// the internet
		if (!"".equals(PROXY_HOST)) {
			System.setProperty("proxyHost", PROXY_HOST);
			System.setProperty("proxyPort", PROXY_PORT);
			System.setProperty("proxySet", "true");

			if (!"".equals(PROXY_USER)) {
				// set username and password for PROXY access
				String auth = Base64Helper
						.toBase64((PROXY_USER + ":" + PROXY_PASSWD).getBytes());
				conn.setRequestProperty("Proxy-Authorization", auth);
			}

			System.out.println("connecting [via proxy] to " + DWS_URL);
		} else {
			System.out.println("Connecting [directly] to " + DWS_URL);
		}

		// set connection parameters
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestProperty("Connection", "Keep-Alive");

		conn.setRequestProperty("Content-Type",
				"multipart/form-data; charset=utf-8");
		conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="
				+ boundary);

		conn.connect();
		System.out.println("Connected");

		return conn;
	}

	/*
	 * Something went wrong in the call to the service, tell the user about it
	 */
	private static void processError(HttpURLConnection conn, int status)
			throws IOException {
		System.err.println("Our call failed: status = " + status);
		System.err.println("message:" + conn.getResponseMessage());
		BufferedReader errorReader = new BufferedReader(new InputStreamReader(
				conn.getErrorStream()));
		String msg;
		while ((msg = errorReader.readLine()) != null) {
			System.err.println(msg);
		}
		errorReader = null;

	}

	private static volatile long COUNTER = 0;

	private static String createBoundary() {
		return "****" + (COUNTER++) + "*" + System.currentTimeMillis() + ""
				+ ((int) (Math.random() * 1000000.0) + "boundary****");
	}

	private static void writeData(String data, DataOutputStream dos)
			throws IOException {
		//System.out.print(data);
		dos.writeBytes(data);
	}

	private static void writeParam(String name, String value,
			DataOutputStream dos) throws IOException {
		writeData("Content-Disposition: form-data; name=\"" + name + "\";", dos);
		writeData(LINE_END, dos);
		writeData(LINE_END, dos);
		writeData(value, dos);
		writeData(LINE_END, dos);
	}


	private static void writeFile(String paramName, String fileName, File f,
			DataOutputStream dos) throws IOException {
		writeData("Content-Disposition: form-data; name=\"" + paramName
				+ "\"; filename=\"" + fileName + "\"", dos);
		writeData(LINE_END, dos);
		writeData("Content-Transfer-Encoding: binary", dos);
		writeData(LINE_END, dos);
		writeData(LINE_END, dos);

		final byte[] buffer = new byte[8192];
		int len;
		FileInputStream fin = null;

		try {
			fin = new FileInputStream(f);
			while ((len = fin.read(buffer, 0, buffer.length)) != -1) {
				dos.write(buffer, 0, len);
			}
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					// log here so as not to smother any source exceptions.
					e.printStackTrace();
				}
			}
		}
		writeData(LINE_END, dos);

	}

	/*
	 * Run this example
	 */
	public static void main(String[] args) throws MalformedURLException,
			IOException {
		if ("XXX".equals(ACCESS_KEY)) {
			System.err
					.println("Please set your private ACCESS_KEY at the top of this file from your Docmosis cloud account.");
			System.exit(1);
		}

		// create a random boundary delimiter
		final String boundary = createBoundary();

		HttpURLConnection conn = null;
		try {
			conn = getConnection(boundary);
		} catch (ConnectException e) {
			// can't make the connection
			System.err.println("Unable to connect to the docmosis cloud:"
					+ e.getMessage());
			System.err
					.println("If you have a proxy, configure proxy settings at the top of this example.");
			System.exit(2);
		}

		try {

			final File uploadFile = new File(UPLOAD_FILE);
			final String uploadFileName = uploadFile.getName(); // could
																// override to a
																// new name here
			if (!uploadFile.canRead()) {
				throw new IOException("cannot read file to upload: ["
						+ UPLOAD_FILE + "]");
			}
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

			writeData("--" + boundary + LINE_END, dos);
			writeParam("accessKey", ACCESS_KEY, dos);
			writeData("--" + boundary + LINE_END, dos);
			
			// optionally rename the template when uploading 
//			writeParam("templateName", "myOverrideName.doc", dos);
//			writeData("--" + boundary + LINE_END, dos);
			
			writeFile("templateFile", uploadFileName, uploadFile, dos);
			writeData("--" + boundary + "--" + LINE_END, dos);
			writeData(LINE_END, dos);

			dos.flush();

			int status = conn.getResponseCode();

			if (status == 200) {
				// successful upload
				System.out.println("Upload completed");
			} else {
				// something went wrong - tell the user
				processError(conn, status);
			}

		} finally {
			conn.disconnect();
		}

	}

	/**
	 * A helper for dealing with Base64 encoding. This is only needed if you are
	 * using a proxy to reach the internet and must authenticate with the proxy.
	 */
	private static class Base64Helper {
		private static final char[] B64_DIGIT = { 'A', 'B', 'C', 'D', 'E', 'F',
				'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
				'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
				'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
				'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
				'2', '3', '4', '5', '6', '7', '8', '9', '+', '-' };

		public static String toBase64(byte[] data) {
			int i = 0;
			int chunks = data.length / 3;
			StringBuilder sb = new StringBuilder(chunks * 4 + 2);
			for (int count = 0; count < chunks; count++, i += 3) {
				int buffer = ((data[i] & 0xFF) << 16)
						| ((data[i + 1] & 0xFF) << 8) | (data[i + 2] & 0xFF);
				sb.append(B64_DIGIT[(buffer & 0xFC0000) >> 18]);
				sb.append(B64_DIGIT[(buffer & 0x03F000) >> 12]);
				sb.append(B64_DIGIT[(buffer & 0x000FC0) >> 6]);
				sb.append(B64_DIGIT[(buffer & 0x00003F)]);
			}
			// padding
			int buffer;
			switch (data.length - i) {
			case 2:
				buffer = ((data[i] & 0xFF) << 16) | ((data[i + 1] & 0xFF) << 8);
				sb.append(B64_DIGIT[(buffer & 0xFC0000) >> 18]);
				sb.append(B64_DIGIT[(buffer & 0x03F000) >> 12]);
				sb.append(B64_DIGIT[(buffer & 0x000FC0) >> 6]);
				sb.append('=');
				break;
			case 1:
				buffer = ((data[i] & 0xFF) << 16);
				sb.append(B64_DIGIT[(buffer & 0xFC0000) >> 18]);
				sb.append(B64_DIGIT[(buffer & 0x03F000) >> 12]);
				sb.append("==");
				break;
			}
			return sb.toString();
		}
	}
}

Feedback

Invalid Input

Sorry, this field will only accept letters and numbers, and not special characters, to limit spam. Please also consider contacting support@docmosis.com if you need help with this article.

Sorry, this field will only accept letters and numbers, and not special characters, to limit spam.

Invalid Input

API Overview

Docmosis offers a high-performance, template-based PDF generation API. Suitable for use with custom software applications built using Java, C#/.Net, Python, Ruby and more. See a side-by-side comparison of the API for our SaaS and self-hosted products.