package com.ibm.form.samples; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.codec.binary.Base64; public class FEBUtility { public int responseCode = 0; public String responseMsg = ""; /** * Generic function that can be used to communicate with the FEB REST API. * * @param url - The FEB REST URL to query * @param SSLProtocol - If the server is https, then protocol to use i.e. SSL, SSL_TLS, TLSv1.2, etc * @param method - The request method i.e. GET, POST, PUT, DELETE * @param returnFormat - The format to be used valid values are "application/json" and "application/atom+xml" * @param isSecure - boolean, set to true if the url is using https otherwise false * @param user - The login id of the user to use. If the user does not have access then the request may return empty results. * @param pwd - The password of the user. * @param doInput - Required only for CREATE and UPDATE operations * @param content - The content being posted for CREATE and UPDATE operations * @param cookieVal - The value to be used for the "freedomIdentifyKey" the value passed here should match what you added to the URL. i.e. "1" * @return */ public InputStream getOutputStreamForURL(String url, String SSLProtocol, String method, String returnFormat, boolean isSecure, String user, String pwd, boolean doInput, String content, String cookieVal) { BufferedReader br = null; FileReader fr = null; HttpURLConnection urlConnection = null; HttpsURLConnection secureUrlConnection = null; InputStream output = null; try { if(isSecure) { secureUrlConnection = establishSecureURLConnection(url); secureUrlConnection.setSSLSocketFactory(getSSLContext(SSLProtocol).getSocketFactory()); secureUrlConnection.setHostnameVerifier(getHostNameVerifier()); secureUrlConnection.setRequestMethod(method); secureUrlConnection.setRequestProperty("Accept", returnFormat); secureUrlConnection.setRequestProperty("Content-Type", returnFormat); secureUrlConnection.setRequestProperty("Authorization", "Basic " + getEncodedString(user, pwd)); if(cookieVal != null) secureUrlConnection.setRequestProperty("Cookie", "feedomIdentifyKey=" + cookieVal); secureUrlConnection.setDoOutput(true); if(doInput && content != null) { secureUrlConnection.setDoInput(true); fr = new FileReader(content); br = new BufferedReader(fr); DataOutputStream dos = new DataOutputStream(secureUrlConnection.getOutputStream()); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { dos.writeBytes(sCurrentLine); } dos.flush(); dos.close(); } output = secureUrlConnection.getInputStream(); this.responseCode = secureUrlConnection.getResponseCode(); this.responseMsg = secureUrlConnection.getResponseMessage(); } else { urlConnection = establishURLConnection(url); urlConnection.setRequestMethod(method); urlConnection.setRequestProperty("Accept", returnFormat); urlConnection.setRequestProperty("Content-Type", returnFormat); urlConnection.setRequestProperty("Authorization", "Basic " + getEncodedString(user, pwd)); urlConnection.setDoOutput(true); if(doInput && content != null) { urlConnection.setDoInput(true); fr = new FileReader(content); br = new BufferedReader(fr); DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream()); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { dos.writeBytes(sCurrentLine); } dos.flush(); dos.close(); } output = urlConnection.getInputStream(); this.responseCode = urlConnection.getResponseCode(); this.responseMsg = urlConnection.getResponseMessage(); } } catch(IOException ioe) { //printToLog("INFO", ioe.getMessage()); } catch(Exception e) { //printToLog("INFO", e.getMessage()); } finally { try { if (br != null) br.close(); if (fr != null) fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } return output; } private HttpURLConnection establishURLConnection(String server, String action) throws MalformedURLException, IOException { String webPage = server + "/forms-basic/secure/org/app" + action; //System.out.println(webPage); URL url = new URL(webPage); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); return conn; } /** * Returns HTTPConnection for the specified URL * * @param theUrl * @return * @throws MalformedURLException * @throws IOException */ private HttpURLConnection establishURLConnection(String theUrl) throws MalformedURLException, IOException { //String webPage = "http://" + server + "/forms-basic/secure/org/app" + action; //System.out.println(webPage); URL url = new URL(theUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); return conn; } /** * Returns HTTPSConnection for the specified URL * * @param theUrl * @return * @throws MalformedURLException * @throws IOException */ private HttpsURLConnection establishSecureURLConnection(String theUrl) throws MalformedURLException, IOException { //String webPage = "http://" + server + "/forms-basic/secure/org/app" + action; //System.out.println(webPage); URL url = new URL(theUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); return conn; } /** * Returns the base64 encoded string with your username and password for inserting into the request header * @param name * @param pwd * @return The base64 encoded username and password */ private String getEncodedString(String name, String pwd) { String authString = name + ":" + pwd; //System.out.println("auth string: " + authString); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); //System.out.println("Base64 encoded auth string: " + authStringEnc); return authStringEnc; } /** * * @param is * @return * @throws IOException */ public String printStreamToString(InputStream is) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer sb = new StringBuffer(); while((line = rd.readLine()) != null) { sb.append(line); sb.append('\r'); } rd.close(); return sb.toString(); } /** * * @param is * @param filePath * @throws IOException */ public void printStreamToFile(InputStream is, String filePath) throws IOException { OutputStream os = new FileOutputStream (new File(filePath)); int read = 0; byte[] bytes = new byte[1024]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } if (os != null) { try { os.close(); } catch (Exception e) { //throw new Exception(e.getMessage(), e); } } } /** * Returns the SSLContext for use in HTTPS connections * @return * @throws Exception */ private SSLContext getSSLContext(String commType) throws Exception { /*** * http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/ * * Change all HttpURLCOnnection to HttpsURLConnection * */ // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance(commType); //SSL_TLS sc.init(null, trustAllCerts, new java.security.SecureRandom()); return sc; } /** * Returns a HostNameVerifier for use in HTTPS connections. * @return */ private HostnameVerifier getHostNameVerifier() { // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; return allHostsValid; } }