Java Source Code: org.aspcfs.utils.HTTPUtils


   1: /**
   2:  * Centric Team Elements
   3:  * Copyright(c) 2007 Centric CRM, Inc.
   4:  * http://www.centriccrm.com
   5:  *
   6:  * Licensed under the Open Software License version 3.0;
   7:  * you may not use this file except in compliance with the License.
   8:  * Read the LICENSE.txt which must be included with this software.
   9:  *
  10:  * This software is OSI Certified Open Source Software.
  11:  * OSI Certified is a certification mark of the Open Source Initiative.
  12:  *
  13:  * Unless required by applicable law or agreed to in writing, software
  14:  * distributed under the License is distributed on an "AS IS" BASIS,
  15:  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16:  * See the License for the specific language governing permissions and
  17:  * limitations under the License.
  18:  *
  19:  * Attribution Notice: Centric Team Elements is an Original Work of
  20:  * software created by Centric CRM Inc.
  21:  */
  22: 
  23: package org.aspcfs.utils;
  24: 
  25: import com.zeroio.controller.ApplicationPrefs;
  26: 
  27: import javax.net.ssl.*;
  28: import javax.servlet.http.HttpServletRequest;
  29: import java.io.*;
  30: import java.net.HttpURLConnection;
  31: import java.net.URL;
  32: import java.net.URLConnection;
  33: import java.net.URLEncoder;
  34: import java.util.HashMap;
  35: import java.util.Iterator;
  36: import java.util.Map;
  37: 
  38: /**
  39:  *  Utilities for working with HTTP
  40:  *
  41:  * @author     matt rajkowski
  42:  * @version    $Id: HTTPUtils.java,v 1.2.20.1 2002/12/06 21:37:00 mrajkowski Exp
  43:  *      $
  44:  * @created    August 29, 2002
  45:  */
  46:	  public class HTTPUtils {
  47:
  48:  final static int BUFF_SIZE = 1024;
  49:  final static byte[] buffer = new byte[BUFF_SIZE];
  50:
  51:  /**
  52:   *  Generates acceptable html text when displaying in HTML, especially useful
  53:   *  within a table cell because a cell should not be left empty
  54:   *
  55:   * @param  s  Description of the Parameter
  56:   * @return    Description of the Return Value
  57:   */
  58:	    public static String toHtml(String s) {
  59:	      if (s != null) {
  60:	        if (s.trim().equals("")) {
  61:        return (" ");
  62:      } else {
  63:        return toHtmlValue(s);
  64:      }
  65:    } else {
  66:      return (" ");
  67:    }
  68:  }
  69:
  70:
  71:  /**
  72:   *  Generates acceptable default html text when using an input field on an
  73:   *  html form
  74:   *
  75:   * @param  s  Description of the Parameter
  76:   * @return    Description of the Return Value
  77:   */
  78:	    public static String toHtmlValue(String s) {
  79:	      if (s != null) {
  80:      String htmlReady = s.trim();
  81:      htmlReady = StringUtils.replace(htmlReady, "\"", """);
  82:      htmlReady = StringUtils.replace(htmlReady, "<", "&lt;");
  83:      htmlReady = StringUtils.replace(htmlReady, ">", "&gt;");
  84:      htmlReady = StringUtils.replace(htmlReady, "\r\n", "<br>");
  85:      htmlReady = StringUtils.replace(htmlReady, "\n\r", "<br>");
  86:      htmlReady = StringUtils.replace(htmlReady, "\n", "<br>");
  87:      htmlReady = StringUtils.replace(htmlReady, "\r", "<br>");
  88:      return (htmlReady);
  89:    } else {
  90:      return ("");
  91:    }
  92:  }
  93:
  94:
  95:  /**
  96:   *  Description of the Method
  97:   *
  98:   * @param  address               Description of the Parameter
  99:   * @param  xmlPacket             Description of the Parameter
 100:   * @return                       Description of the Return Value
 101:   * @throws  java.io.IOException  Description of the Exception
 102:   */
 103:	    public static String sendPacket(String address, String xmlPacket) throws IOException {
 104:    return sendPacket(address, xmlPacket, null);
 105:  }
 106:
 107:
 108:  /**
 109:   *  Sends a string to the specified URL, intended for communicating with web
 110:   *  servers. Use the SSLMessage for secure communication with a server
 111:   *  application.
 112:   *
 113:   * @param  address               Description of the Parameter
 114:   * @param  xmlPacket             Description of the Parameter
 115:   * @param  headers               Description of the Parameter
 116:   * @return                       Description of the Return Value
 117:   * @throws  java.io.IOException  Description of the Exception
 118:   */
 119:	    public static String sendPacket(String address, String xmlPacket, HashMap headers) throws IOException {
 120:    Exception errorMessage = null;
 121:	      try {
 122:      //The default factory requires a trusted certificate
 123:      //Accept any certificate using the custom TrustManager
 124:      X509TrustManager xtm = new HttpsTrustManager();
 125:      TrustManager mytm[] = {xtm};
 126:      SSLContext ctx = SSLContext.getInstance("SSL");
 127:      ctx.init(null, mytm, null);
 128:      SSLSocketFactory factory = ctx.getSocketFactory();
 129:      //Get a connection
 130:      URL url = new URL(address);
 131:      URLConnection conn = url.openConnection();
 132:      //Override the default certificates
 133:	        if (conn instanceof HttpsURLConnection) {
 134:        ((HttpsURLConnection) conn).setSSLSocketFactory(factory);
 135:        ((HttpsURLConnection) conn).setHostnameVerifier(
 136:            new HttpsHostnameVerifier());
 137:      }
 138:      ((HttpURLConnection) conn).setRequestMethod("POST");
 139:      conn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
 140:	        if (headers != null && headers.size() > 0) {
 141:        Iterator i = headers.keySet().iterator();
 142:	          while (i.hasNext()) {
 143:          String header = (String) i.next();
 144:          String value = (String) headers.get(header);
 145:          conn.setRequestProperty(header, value);
 146:        }
 147:      }
 148:      conn.setDoInput(true);
 149:      conn.setDoOutput(true);
 150:      OutputStreamWriter out = new OutputStreamWriter(
 151:          conn.getOutputStream(), "UTF8");
 152:      out.write(xmlPacket);
 153:      out.close();
 154:      return (retrieveHtml(conn));
 155:    } catch (MalformedURLException e) {
 156:      errorMessage = e;
 157:    } catch (IOException e) {
 158:      errorMessage = e;
 159:    } catch (KeyManagementException e) {
 160:      errorMessage = e;
 161:    } catch (NoSuchAlgorithmException e) {
 162:      errorMessage = e;
 163:    } catch (NullPointerException e) {
 164:      e.printStackTrace(System.out);
 165:      errorMessage = e;
 166:    }
 167:	      if (errorMessage != null) {
 168:	        if (System.getProperty("DEBUG") != null) {
 169:        System.out.println("HTTPUtils-> sendPacket error: " + errorMessage.getMessage());
 170:      }
 171:      throw new java.io.IOException(errorMessage.toString());
 172:    }
 173:    return null;
 174:  }
 175:
 176:
 177:  /**
 178:   *  Returns the text received from a web post
 179:   *
 180:   * @param  http                  Description of the Parameter
 181:   * @return                       Description of the Return Value
 182:   * @throws  java.io.IOException  Description of the Exception
 183:   */
 184:	    public static String retrieveHtml(URLConnection http) throws IOException {
 185:    StringBuffer htmlOutput = new StringBuffer();
 186:    InputStreamReader input = new InputStreamReader(http.getInputStream());
 187:    BufferedReader inStream = new BufferedReader(input);
 188:    String inputLine;
 189:	      while ((inputLine = inStream.readLine()) != null) {
 190:      htmlOutput.append(inputLine + System.getProperty("line.separator"));
 191:    }
 192:    inStream.close();
 193:    return htmlOutput.toString();
 194:  }
 195:
 196:
 197:  /**
 198:   *  Downloads a URL into a postscript file. Currently uses html2ps, but for
 199:   *  Windows compatibility may need to use htmldoc after testing.
 200:   *
 201:   * @param  url           Description of the Parameter
 202:   * @param  baseFilename  Description of the Parameter
 203:   * @return               Description of the Return Value
 204:   */
 205:	    public static int convertUrlToPostscriptFile(String url, String baseFilename) {
 206:    Process process;
 207:    Runtime runtime;
 208:    String command[] = null;
 209:    File osCheckFile = new File("/bin/sh");
 210:	      if (osCheckFile.exists()) {
 211:      //Linux
 212:	        command = new String[]{"/bin/sh", "-c", "/usr/bin/htmldoc --quiet " +
 213:          "-f " + baseFilename + ".ps " +
 214:          "--webpage " +
 215:          "-t ps " +
 216:          "--header ... " +
 217:          "--footer ... " +
 218:          url};
 219:    } else {
 220:      //Windows
 221:	        command = new String[]{"htmldoc", "--quiet " +
 222:          "-f " + baseFilename + ".ps " +
 223:          "--webpage " +
 224:          "-t ps3 " +
 225:          "--header ... " +
 226:          "--footer ... " +
 227:          url};
 228:    }
 229:    runtime = Runtime.getRuntime();
 230:	      try {
 231:      process = runtime.exec(command);
 232:      return (process.waitFor());
 233:    } catch (Exception e) {
 234:      System.err.println(
 235:          "HTTPUtils-> urlToPostscriptFile error: " + e.toString());
 236:      return (1);
 237:    }
 238:  }
 239:
 240:
 241:    /**
 242:   *  Returns the server's url that was specified in the request, excluding the
 243:   *  scheme
 244:   *
 245:   *@param  prefs  Description of the Parameter
 246:   *@param  request  Description of the Parameter
 247:   *@return          The serverURL value
 248:   */
 249:	    public static String getServerUrl(ApplicationPrefs prefs, HttpServletRequest request) {
 250:    String serverName = request.getServerName();
 251:	      if (prefs.has("URL")) {
 252:      serverName = prefs.get("URL");
 253:    }
 254:    int port = request.getServerPort();
 255:    return (serverName + (port != 80 && port != 443 ? ":" + String.valueOf(port) : "") + request.getContextPath());
 256:  }
 257:
 258:
 259:	    public static String getServerUrl(HttpServletRequest request) {
 260:    String serverName = request.getServerName();
 261:    int port = request.getServerPort();
 262:    return (serverName + (port != 80 && port != 443 ? ":" + String.valueOf(port) : "") + request.getContextPath());
 263:  }
 264:
 265:
 266:  /**
 267:   *  Connects to a web server and gets the Server header field
 268:   *
 269:   * @param  address  Description of the Parameter
 270:   * @return          The serverName value
 271:   */
 272:	    public static String getServerName(String address) {
 273:	      try {
 274:      //The default factory requires a trusted certificate
 275:      //Accept any certificate using the custom TrustManager
 276:      X509TrustManager xtm = new HttpsTrustManager();
 277:      TrustManager mytm[] = {xtm};
 278:      SSLContext ctx = SSLContext.getInstance("SSL");
 279:      ctx.init(null, mytm, null);
 280:      SSLSocketFactory factory = ctx.getSocketFactory();
 281:      //Get a connection
 282:      URL url = new URL(address);
 283:      URLConnection conn = url.openConnection();
 284:      //Override the default certificates
 285:	        if (conn instanceof HttpsURLConnection) {
 286:        ((HttpsURLConnection) conn).setSSLSocketFactory(factory);
 287:        ((HttpsURLConnection) conn).setHostnameVerifier(
 288:            new HttpsHostnameVerifier());
 289:      }
 290:	        if (conn instanceof HttpURLConnection) {
 291:        HttpURLConnection httpConnection = (HttpURLConnection) conn;
 292:        httpConnection.setRequestMethod("HEAD");
 293:        httpConnection.connect();
 294:        return httpConnection.getHeaderField("Server");
 295:      }
 296:    } catch (Exception e) {
 297:      System.out.println("HTTPUtils-> getServerName error: " + e.getMessage());
 298:	        if (System.getProperty("DEBUG") != null) {
 299:        e.printStackTrace(System.out);
 300:      }
 301:    }
 302:    return null;
 303:  }
 304:
 305:	    private static void writeParam(String name, String value, DataOutputStream out, String boundary) {
 306:	      try {
 307:      out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
 308:      out.writeBytes(value);
 309:      out.writeBytes("\r\n" + "--" + boundary + "\r\n");
 310:    } catch (Exception e) {
 311:      System.out.println(e.toString());
 312:    }
 313:  }
 314:
 315:
 316:  /**
 317:   *  Description of the Method
 318:   *
 319:   *@param  name      Description of the Parameter
 320:   *@param  filePath  Description of the Parameter
 321:   *@param  out       Description of the Parameter
 322:   *@param  boundary  Description of the Parameter
 323:   */
 324:	    private static void writeFile(String name, String filePath, DataOutputStream out, String boundary) {
 325:	      try {
 326:      out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
 327:           + filePath + "\"\r\n");
 328:      out.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
 329:      FileInputStream fis = new FileInputStream(filePath);
 330:	        while (true) {
 331:	          synchronized (buffer) {
 332:          int amountRead = fis.read(buffer);
 333:	            if (amountRead == -1) {
 334:            break;
 335:          }
 336:          out.write(buffer, 0, amountRead);
 337:        }
 338:      }
 339:      fis.close();
 340:      out.writeBytes("\r\n" + "--" + boundary + "\r\n");
 341:    } catch (Exception e) {
 342:      System.out.println(e.toString());
 343:    }
 344:  }
 345:
 346:	      public static String post(String address, Map parameters, Map fileMap) {
 347:	      try {
 348:      String boundary = "---------------------------7d226f700d0";
 349:      URL url = new URL(address);
 350:      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 351:      conn.setDoOutput(true);
 352:      conn.setDoInput(true);
 353:      conn.setUseCaches(false);
 354:      conn.setRequestMethod("POST");
 355:      conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
 356:      //conn.setRequestProperty("Referer", "http://127.0.0.1/index.jsp");
 357:      //conn.setRequestProperty("Cache-Control", "no-cache");
 358:
 359:      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
 360:      out.writeBytes("--" + boundary + "\r\n");
 361:      Iterator keys = parameters.keySet().iterator();
 362:	        while (keys.hasNext()) {
 363:        String param = (String) keys.next();
 364:        String value = (String) parameters.get(param);
 365:        writeParam(param, value, out, boundary);
 366:      }
 367:      Iterator files = fileMap.keySet().iterator();
 368:	        while (files.hasNext()) {
 369:        String thisFile = (String) files.next();
 370:        String filePath = (String) fileMap.get(thisFile);
 371:	          if (System.getProperty("DEBUG") != null) {
 372:          System.out.println("HTTPUtils-> POST File: " + thisFile);
 373:        }
 374:        writeFile(thisFile, filePath, out, boundary);
 375:      }
 376:      out.flush();
 377:      out.close();
 378:      return (retrieveHtml(conn));
 379:    } catch (Exception e) {
 380:      System.out.println(e.toString());
 381:    }
 382:    return null;
 383:  }
 384:
 385:	    public static String post(String address, Map parameters) {
 386:	      try {
 387:      // Prepare the content
 388:      StringBuffer content = new StringBuffer();
 389:      Iterator keys = parameters.keySet().iterator();
 390:	        while (keys.hasNext()) {
 391:        String param = (String) keys.next();
 392:        String value = (String) parameters.get(param);
 393:	          if (content.length() > 0) {
 394:          content.append("&");
 395:        }
 396:        content.append(param);
 397:        content.append("=");
 398:        content.append(URLEncoder.encode(value, "UTF-8"));
 399:      }
 400:      // Post the data
 401:      URL url = new URL(address);
 402:      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 403:      conn.setDoOutput(true);
 404:      conn.setDoInput(true);
 405:      conn.setUseCaches(false);
 406:      conn.setRequestMethod("POST");
 407:      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 408:      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
 409:      out.writeBytes(content.toString());
 410:      out.flush();
 411:      out.close();
 412:      return (retrieveHtml(conn));
 413:    } catch (Exception e) {
 414:      System.out.println(e.toString());
 415:    }
 416:    return null;
 417:  }
 418:}