Esempio n. 1
1
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
Esempio n. 2
0
  private int invokeServlet(String url, String method, String user, StringBuffer output)
      throws Exception {
    String httpMethod = "GET";
    if ((method != null) && (method.length() > 0)) httpMethod = method;
    System.out.println("Invoking servlet with HTTP method: " + httpMethod);
    URL u = new URL(url);
    HttpURLConnection c1 = (HttpURLConnection) u.openConnection();
    c1.setRequestMethod(httpMethod);
    if ((user != null) && (user.length() > 0)) {
      // Add BASIC header for authentication
      String auth = user + ":" + password;
      String authEncoded = new sun.misc.BASE64Encoder().encode(auth.getBytes());
      c1.setRequestProperty("Authorization", "Basic " + authEncoded);
    }
    c1.setUseCaches(false);

    // Connect and get the response code and/or output to verify
    c1.connect();
    int code = c1.getResponseCode();
    if (code == HttpURLConnection.HTTP_OK) {
      InputStream is = null;
      BufferedReader input = null;
      String line = null;
      try {
        is = c1.getInputStream();
        input = new BufferedReader(new InputStreamReader(is));
        while ((line = input.readLine()) != null) {
          output.append(line);
          // System.out.println(line);
        }
      } finally {
        try {
          if (is != null) is.close();
        } catch (Exception exc) {
        }
        try {
          if (input != null) input.close();
        } catch (Exception exc) {
        }
      }
    } else if (code == HttpURLConnection.HTTP_MOVED_TEMP) {
      URL redir = new URL(c1.getHeaderField("Location"));
      String line = "Servlet redirected to: " + redir.toString();
      output.append(line);
      System.out.println(line);
    }
    return code;
  }
Esempio n. 3
0
  /**
   * 发起查询处理结果请求
   *
   * @param params 请求参数
   * @return 请求结果
   * @throws IOException
   */
  public Result getResult(Map<String, Object> params) throws IOException {
    InputStream is = null;
    HttpURLConnection conn;

    StringBuilder sb = new StringBuilder(HOST + "result");
    sb.append("?");
    for (Map.Entry<String, Object> mapping : params.entrySet()) {
      sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&");
    }
    URL url = new URL(sb.toString().substring(0, sb.length() - 1));

    conn = (HttpURLConnection) url.openConnection();

    // 设置必要参数
    conn.setConnectTimeout(timeout);
    conn.setRequestMethod("GET");
    conn.setUseCaches(false);
    conn.setDoOutput(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("User-Agent", UpYunUtils.VERSION);

    // 设置时间
    conn.setRequestProperty(DATE, getGMTDate());
    // 设置签名
    conn.setRequestProperty(AUTHORIZATION, sign(params));

    // 创建链接
    conn.connect();

    // 获取返回的信息
    Result result = getResp(conn);

    if (is != null) {
      is.close();
    }
    if (conn != null) {
      conn.disconnect();
    }
    return result;
  }
Esempio n. 4
0
  /**
   * When you call this, you post the data, after which it is gone. The post is synchronous. The
   * function returns after posting and receiving a reply. Get a new data stream with
   * startDataStream() to make a new post. (You could hold on to the writer, but using it will have
   * no effect after calling this method.)
   *
   * @return HTTP response code, 200 means successful.
   */
  public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException {
    cdbId = -1;
    if (dataWriter == null) {
      throw new IllegalStateException("call startDataStream() and write something first");
    }
    HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dataWriter.flush();
    String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8");
    dataWriter = null;

    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();
    wasSuccessful = (200 == responseCode);
    InputStream response;
    if (wasSuccessful) {
      response = connection.getInputStream();
    } else {
      response = connection.getErrorStream();
    }
    if (response != null) processResponse(response);
    connection.disconnect();

    return responseCode;
  }
Esempio n. 5
0
  SOAPMessage doGet(URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      /// Is https GET allowed??
      if (endPoint.getProtocol().equals("https")) initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("GET");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setFollowRedirects(true);

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0012.p2p.get.failed");
      throw new SOAPExceptionImpl("Get failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());
        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        // java SE 6 documentation says :
        // available() : an estimate of the number of bytes that can be read
        // (or skipped over) from this input stream without blocking
        // or 0 when it reaches the end of the input stream.
        if ((httpIn == null)
            || (httpConnection.getContentLength() == 0)
            || (httpIn.available() == 0)) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          response = messageFactory.createMessage(headers, httpIn);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
Esempio n. 6
0
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
Esempio n. 7
0
  public static String httpPost(String urlAddress, String[] params) {
    URL url = null;
    HttpURLConnection conn = null;
    BufferedReader in = null;
    StringBuffer sb = new StringBuffer();

    try {
      url = new URL(urlAddress);
      conn = (HttpURLConnection) url.openConnection(); // 建立连接
      // 设置通用的请求属性
      /*
       * conn.setRequestProperty("user-agent",
       * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
       */
      conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
      conn.setRequestProperty("Accept", "*/*");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      conn.setUseCaches(false);
      conn.setDoInput(true);
      // conn.setConnectTimeout(5 * 1000);
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      String paramsTemp = "";
      for (String param : params) {
        if (param != null && !"".equals(param)) {
          if (params.length > 1) {
            paramsTemp += "&" + param;
          } else if (params.length == 1) {
            paramsTemp = params[0];
          }
        }
      }

      byte[] b = paramsTemp.getBytes();
      System.out.println("btye length:" + b.length);
      // conn.setRequestProperty("Content-Length",
      // String.valueOf(b.length));
      conn.getOutputStream().write(b, 0, b.length);
      conn.getOutputStream().flush();
      conn.getOutputStream().close();
      int count = conn.getResponseCode();
      if (200 == count) {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求
      } else {
        System.out.println("错误类型:" + count);
        return "server no start-up";
      }

      while (true) {
        String line = in.readLine();
        if (line == null) {
          break;
        } else {
          sb.append(line);
        }
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("error ioexception:" + e.getMessage());
      e.printStackTrace();
      return "server no start-up";
    } finally {
      try {
        if (in != null) {
          in.close();
        }
        if (conn != null) {
          conn.disconnect();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return sb.toString();
  }