示例#1
0
 /**
  * Computes RFC 2104-compliant HMAC signature.
  *
  * @param data the data to be signed
  * @param token the token
  * @return signature
  * @see <a href="http://oauth.net/core/1.0a/#rfc.section.9.2.1">OAuth Core - 9.2.1. Generating
  *     Signature</a>
  */
 /* package */ String generateSignature(final String data, final OAuthToken token) {
   byte[] byteHMAC = null;
   try {
     final Mac mac = Mac.getInstance(HMAC_SHA1);
     SecretKeySpec spec;
     if (null == token) {
       final String oauthSignature = HttpParameter.encode(consumerSecret) + "&";
       spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
     } else {
       spec = token.getSecretKeySpec();
       if (null == spec) {
         final String oauthSignature =
             HttpParameter.encode(consumerSecret)
                 + "&"
                 + HttpParameter.encode(token.getTokenSecret());
         spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1);
         token.setSecretKeySpec(spec);
       }
     }
     mac.init(spec);
     byteHMAC = mac.doFinal(data.getBytes());
   } catch (final InvalidKeyException ike) {
     logger.error("Failed initialize \"Message Authentication Code\" (MAC)", ike);
     throw new AssertionError(ike);
   } catch (final NoSuchAlgorithmException nsae) {
     logger.error("Failed to get HmacSHA1 \"Message Authentication Code\" (MAC)", nsae);
     throw new AssertionError(nsae);
   }
   return BASE64Encoder.encode(byteHMAC);
 }
示例#2
0
  public List<HttpParameter> generateOAuthSignatureHttpParams(
      final String method, final String sign_url) {
    final long timestamp = System.currentTimeMillis() / 1000;
    final long nonce = timestamp + RAND.nextInt();

    final List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5);
    oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", consumerKey));
    oauthHeaderParams.add(OAUTH_SIGNATURE_METHOD);
    oauthHeaderParams.add(new HttpParameter("oauth_timestamp", timestamp));
    oauthHeaderParams.add(new HttpParameter("oauth_nonce", nonce));
    oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0"));
    if (oauthToken != null) {
      oauthHeaderParams.add(new HttpParameter("oauth_token", oauthToken.getToken()));
    }

    final List<HttpParameter> signatureBaseParams =
        new ArrayList<HttpParameter>(oauthHeaderParams.size());
    signatureBaseParams.addAll(oauthHeaderParams);
    parseGetParameters(sign_url, signatureBaseParams);

    final StringBuffer base =
        new StringBuffer(method)
            .append("&")
            .append(HttpParameter.encode(constructRequestURL(sign_url)))
            .append("&");
    base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams)));

    final String oauthBaseString = base.toString();
    final String signature = generateSignature(oauthBaseString, oauthToken);

    oauthHeaderParams.add(new HttpParameter("oauth_signature", signature));

    return oauthHeaderParams;
  }
示例#3
0
 /* package */
 static boolean containsFile(final List<HttpParameter> params) {
   boolean containsFile = false;
   for (final HttpParameter param : params) {
     if (param.isFile()) {
       containsFile = true;
       break;
     }
   }
   return containsFile;
 }
示例#4
0
 public static boolean containsFile(final HttpParameter[] params) {
   boolean containsFile = false;
   if (null == params) return false;
   for (final HttpParameter param : params) {
     if (param.isFile()) {
       containsFile = true;
       break;
     }
   }
   return containsFile;
 }
示例#5
0
  /* package */ String generateAuthorizationHeader(
      final String method,
      final String url,
      HttpParameter[] params,
      final String nonce,
      final String timestamp,
      final OAuthToken otoken) {
    if (null == params) {
      params = new HttpParameter[0];
    }
    final List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5);
    oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", consumerKey));
    oauthHeaderParams.add(OAUTH_SIGNATURE_METHOD);
    oauthHeaderParams.add(new HttpParameter("oauth_timestamp", timestamp));
    oauthHeaderParams.add(new HttpParameter("oauth_nonce", nonce));
    oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0"));
    if (otoken != null) {
      oauthHeaderParams.add(new HttpParameter("oauth_token", otoken.getToken()));
    }
    final List<HttpParameter> signatureBaseParams =
        new ArrayList<HttpParameter>(oauthHeaderParams.size() + params.length);
    signatureBaseParams.addAll(oauthHeaderParams);
    if (!HttpParameter.containsFile(params)) {
      signatureBaseParams.addAll(toParamList(params));
    }
    parseGetParameters(url, signatureBaseParams);
    final StringBuffer base =
        new StringBuffer(method)
            .append("&")
            .append(HttpParameter.encode(constructRequestURL(url)))
            .append("&");
    base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams)));
    final String oauthBaseString = base.toString();
    logger.debug("OAuth base string: ", oauthBaseString);
    final String signature = generateSignature(oauthBaseString, otoken);
    logger.debug("OAuth signature: ", signature);

    oauthHeaderParams.add(new HttpParameter("oauth_signature", signature));

    // http://oauth.net/core/1.0/#rfc.section.9.1.1
    if (realm != null) {
      oauthHeaderParams.add(new HttpParameter("realm", realm));
    }
    return "OAuth " + encodeParameters(oauthHeaderParams, ",", true);
  }
示例#6
0
 public static String encodeParameters(
     final List<HttpParameter> httpParams, final String splitter, final boolean quot) {
   final StringBuffer buf = new StringBuffer();
   for (final HttpParameter param : httpParams) {
     if (!param.isFile()) {
       if (buf.length() != 0) {
         if (quot) {
           buf.append("\"");
         }
         buf.append(splitter);
       }
       buf.append(HttpParameter.encode(param.getName())).append("=");
       if (quot) {
         buf.append("\"");
       }
       buf.append(HttpParameter.encode(param.getValue()));
     }
   }
   if (buf.length() != 0) {
     if (quot) {
       buf.append("\"");
     }
   }
   return buf.toString();
 }
示例#7
0
  @Override
  public HttpResponse request(final HttpRequest req) throws MoefouException {
    int retriedCount;
    final int retry = CONF.getHttpRetryCount() + 1;
    HttpResponse res = null;
    for (retriedCount = 0; retriedCount < retry; retriedCount++) {
      int responseCode = -1;
      try {
        HttpURLConnection con;
        OutputStream os = null;
        try {
          con = getConnection(req.getURL());
          con.setDoInput(true);
          setHeaders(req, con);
          con.setRequestMethod(req.getMethod().name());
          if (req.getMethod() == POST) {
            if (HttpParameter.containsFile(req.getParameters())) {
              String boundary = "----Twitter4J-upload" + System.currentTimeMillis();
              con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
              boundary = "--" + boundary;
              con.setDoOutput(true);
              os = con.getOutputStream();
              final DataOutputStream out = new DataOutputStream(os);
              for (final HttpParameter param : req.getParameters()) {
                if (param.isFile()) {
                  write(out, boundary + "\r\n");
                  write(
                      out,
                      "Content-Disposition: form-data; name=\""
                          + param.getName()
                          + "\"; filename=\""
                          + param.getFile().getName()
                          + "\"\r\n");
                  write(out, "Content-Type: " + param.getContentType() + "\r\n\r\n");
                  final BufferedInputStream in =
                      new BufferedInputStream(
                          param.hasFileBody()
                              ? param.getFileBody()
                              : new FileInputStream(param.getFile()));
                  int buff;
                  while ((buff = in.read()) != -1) {
                    out.write(buff);
                  }
                  write(out, "\r\n");
                  in.close();
                } else {
                  write(out, boundary + "\r\n");
                  write(
                      out, "Content-Disposition: form-data; name=\"" + param.getName() + "\"\r\n");
                  write(out, "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
                  logger.debug(param.getValue());
                  out.write(param.getValue().getBytes("UTF-8"));
                  write(out, "\r\n");
                }
              }
              write(out, boundary + "--\r\n");
              write(out, "\r\n");

            } else {
              con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              final String postParam = HttpParameter.encodeParameters(req.getParameters());
              logger.debug("Post Params: ", postParam);
              final byte[] bytes = postParam.getBytes("UTF-8");
              con.setRequestProperty("Content-Length", Integer.toString(bytes.length));
              con.setDoOutput(true);
              os = con.getOutputStream();
              os.write(bytes);
            }
            os.flush();
            os.close();
          }
          res = new HttpResponseImpl(con, CONF);
          responseCode = con.getResponseCode();
          if (logger.isDebugEnabled()) {
            logger.debug("Response: ");
            final Map<String, List<String>> responseHeaders = con.getHeaderFields();
            for (final String key : responseHeaders.keySet()) {
              final List<String> values = responseHeaders.get(key);
              for (final String value : values) {
                if (key != null) {
                  logger.debug(key + ": " + value);
                } else {
                  logger.debug(value);
                }
              }
            }
          }
          if (responseCode < OK || responseCode != FOUND && MULTIPLE_CHOICES <= responseCode) {
            if (responseCode == ENHANCE_YOUR_CLAIM
                || responseCode == BAD_REQUEST
                || responseCode < INTERNAL_SERVER_ERROR
                || retriedCount == CONF.getHttpRetryCount())
              throw new MoefouException(res.asString(), req, res);
          } else {
            break;
          }
        } finally {
          try {
            os.close();
          } catch (final Exception ignore) {
          }
        }
      } catch (final IOException ioe) {
        // connection timeout or read timeout
        if (retriedCount == CONF.getHttpRetryCount())
          // throw new TwitterException(ioe.getMessage(), ioe,
          // responseCode);
          throw new MoefouException(ioe.getMessage(), req, res);
      } catch (final NullPointerException e) {
        // This exception will be thown when URL is invalid.
        throw new MoefouException("The URL requested is invalid.", e);
      } catch (final OutOfMemoryError e) {
        throw new MoefouException(e.getMessage(), e);
      }
      try {
        if (logger.isDebugEnabled() && res != null) {
          res.asString();
        }
        logger.debug(
            "Sleeping " + CONF.getHttpRetryIntervalSeconds() + " seconds until the next retry.");
        Thread.sleep(CONF.getHttpRetryIntervalSeconds() * 1000);
      } catch (final InterruptedException ignore) {
        // nothing to do
      }
    }
    return res;
  }