import java.io.IOException; import java.net.URISyntaxException; import java.io.*; import com.ibm.misc.BASE64Encoder; import org.apache.http.client.methods.HttpPost; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.entity.StringEntity; import net.sf.json.JSONSerializer; import net.sf.json.JSONObject; public class MailboxAddClient { public static void main(String[] args) { final String DOC_URL = "http://1.1.1.1:10074/B2BAPIs/svc/documents"; final String MBX_URL = "http://1.1.1.1:10074/B2BAPIs/svc/mailboxmessages/"; final String MBX_PATH = "/KKIn"; final String FILE_PATH="/home/kkonda/index.html"; final String MESSAGE_NAME = "NewIndex.html"; final String authentication = "admin:password"; try { System.out.println("Initiating REST API call for Document Creation"); String documentID = new MailboxAddClient().createDocument(DOC_URL, authentication, FILE_PATH); if(documentID == null) System.exit(-1); System.out.println("Posting to mailbox through REST API call.."); new MailboxAddClient().addMessageToMailBox(MBX_URL, authentication, documentID, MBX_PATH, MESSAGE_NAME); System.out.println("Upload successful!"); } catch (IOException e) { e.printStackTrace(System.out); } catch (Exception e) { e.printStackTrace(System.out); } } public String createDocument(String URL, String authentication, String filePath) throws Exception{ CloseableHttpResponse response = null; String encAuth = new BASE64Encoder().encode(new String(authentication).getBytes()); //This will store the id of the document we're going to create String documentId = null; CloseableHttpClient httpclient = HttpClients.createDefault(); //Create JSON request body JSONObject docJson = new JSONObject(); String payload = new BASE64Encoder().encode(getPayload(filePath).getBytes()); docJson.put("payload",payload); String docJsonString = docJson.toString(); try { //Create and make request HttpRequestBase request = createPostRequest(URL, encAuth, docJsonString); response = httpclient.execute(request); //Parse created document id out of response JSON HttpEntity entity = response.getEntity(); int retCode = response.getStatusLine().getStatusCode(); System.out.println("retCode : "+ retCode); if(retCode==200 || retCode==201 || retCode==202){ String responseString = convertResponseToString(entity); System.out.println("responseString : " + responseString); JSONObject json = (JSONObject)JSONSerializer.toJSON(responseString); //Get created Location element from JSON String jsonLocation = (String) json.get("Location"); //Split the location and grab the last entry, the document id String[] jsonLocationSplit = jsonLocation.split("/"); documentId = jsonLocationSplit[jsonLocationSplit.length-1]; System.out.println("Created document id: " + documentId); }else{ throw new IOException("HTTP POST Request for createDocument failed: " + retCode); } } catch (IOException e) { throw new Exception("HTTP POST Request for CreateDocument failed: " + e); } finally { //Must close response if(response!=null) response.close(); } return documentId; } private String getPayload(String filePath) throws FileNotFoundException, IOException { BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)))); String s,fileContent = ""; while((s=r.readLine())!=null) fileContent +=s; System.out.println("Payload : " + filePath + " size : " + fileContent.length()); return fileContent; } public boolean addMessageToMailBox(String URL,String authentication,String documentID,String mailBoxPath,String msgName) throws Exception{ String encAuth = new BASE64Encoder().encode(new String(authentication).getBytes()); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; // // Create Message // //Create JSON request body JSONObject msgJson = new JSONObject(); msgJson.put("documentId", documentID); msgJson.put("extractableCount", 3); msgJson.put("mailboxPath", mailBoxPath); msgJson.put("name", msgName); String msgJsonString = msgJson.toString(); System.out.println("msgJsonString : " + msgJsonString); try { //Create and make request HttpRequestBase request = createPostRequest(URL, encAuth, msgJsonString); response = httpclient.execute(request); HttpEntity entity = response.getEntity(); int retCode = response.getStatusLine().getStatusCode(); if(retCode==200 || retCode==201 || retCode==202){ String responseString = convertResponseToString(entity); System.out.println(responseString); return true; }else{ throw new Exception("HTTP POST Request for Creating Mailbox Message failed: " + retCode); } } catch (IOException e) { //e.printStackTrace(); throw new Exception("HTTP POST Request for Creating Mailbox Message failed: " + e); } finally { //Must close response if(response!=null) response.close(); } } private static HttpRequestBase createPostRequest(String URL, String encAuth, String jsonString) throws UnsupportedEncodingException, URISyntaxException { HttpRequestBase httpRequest = null; httpRequest = new HttpPost(URL + "/"); ((HttpPost) httpRequest).setEntity(new StringEntity(jsonString)); httpRequest.addHeader("Authorization", "Basic " + encAuth); httpRequest.addHeader("content-type", "application/json"); httpRequest.addHeader("Accept","application/json"); return httpRequest; } private String convertResponseToString(HttpEntity entity) throws IOException{ ByteArrayOutputStream os = new ByteArrayOutputStream(); entity.writeTo(os); String jsonResponse = new String(os.toByteArray()); return jsonResponse; } } |