public String normalizeRequestUrl() {
   label0:
   {
     Object obj = new URI(request.getRequestUrl());
     String s2 = ((URI) (obj)).getScheme().toLowerCase();
     String s1 = ((URI) (obj)).getAuthority().toLowerCase();
     String s;
     int i;
     if (s2.equals("http") && ((URI) (obj)).getPort() == 80
         || s2.equals("https") && ((URI) (obj)).getPort() == 443) {
       i = 1;
     } else {
       i = 0;
     }
     s = s1;
     if (i != 0) {
       i = s1.lastIndexOf(":");
       s = s1;
       if (i >= 0) {
         s = s1.substring(0, i);
       }
     }
     obj = ((URI) (obj)).getRawPath();
     if (obj != null) {
       s1 = ((String) (obj));
       if (((String) (obj)).length() > 0) {
         break label0;
       }
     }
     s1 = "/";
   }
   return (new StringBuilder()).append(s2).append("://").append(s).append(s1).toString();
 }
Beispiel #2
0
 public JSONObject getEventsObject(EventSearchCriteria c) throws Exception {
   HttpURLConnection conn = createConnection(EVENTS, c.getParameterMap());
   HttpRequest req = sign(conn);
   System.out.println(req.getRequestUrl());
   conn.connect();
   int resp = conn.getResponseCode();
   Type type = new TypeToken<MeetupResponse<Event>>() {}.getType();
   StringBuilder b = new StringBuilder();
   String line = null;
   BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   while ((line = r.readLine()) != null) {
     b.append(line);
     b.append("\n");
   }
   return new JSONObject(b.toString());
 }
Beispiel #3
0
 public MeetupResponse<Group> getGroups(GroupSearchCriteria c) throws Exception {
   HttpURLConnection conn = createConnection(GROUPS, c.getParameterMap());
   HttpRequest req = sign(conn);
   System.out.println(req.getRequestUrl());
   conn.connect();
   int resp = conn.getResponseCode();
   Type type = new TypeToken<MeetupResponse<Group>>() {}.getType();
   //		StringBuilder b = new StringBuilder();
   //		String line = null;
   //		BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   //		while((line = r.readLine())!=null) {
   //			b.append(line);
   //			b.append("\n");
   //		}
   //		System.out.println(b.toString());
   MeetupResponse<Group> groups =
       gson.fromJson(new InputStreamReader(conn.getInputStream()), type);
   return groups;
 }
Beispiel #4
0
 public MeetupResponse<Member> getSelf() throws Exception {
   HttpURLConnection conn =
       createConnection(MEMBERS, Collections.singletonMap("member_id", "self"));
   HttpRequest req = sign(conn);
   System.out.println(req.getRequestUrl());
   conn.connect();
   int resp = conn.getResponseCode();
   Type type = new TypeToken<MeetupResponse<Member>>() {}.getType();
   //		StringBuilder b = new StringBuilder();
   //		String line = null;
   //		BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   //		while((line = r.readLine())!=null) {
   //			b.append(line);
   //			b.append("\n");
   //		}
   //		System.out.println(b.toString());
   MeetupResponse<Member> members =
       gson.fromJson(new InputStreamReader(conn.getInputStream()), type);
   return members;
 }
  /**
   * Builds the signature base string from the data this instance was configured with.
   *
   * @return the signature base string
   * @throws OAuthMessageSignerException
   */
  public String generate() throws OAuthMessageSignerException {

    try {
      String normalizedUrl = normalizeRequestUrl();
      String normalizedParams = normalizeRequestParameters();

      String erm =
          request.getMethod()
              + '&'
              + OAuth.percentEncode(normalizedUrl)
              + '&'
              + OAuth.percentEncode(normalizedParams);
      return erm;
    } catch (Exception e) {
      throw new OAuthMessageSignerException(e);
    }
  }
 public String generate() {
   String s;
   try {
     s = normalizeRequestUrl();
     String s1 = normalizeRequestParameters();
     s =
         (new StringBuilder())
             .append(request.getMethod())
             .append('&')
             .append(OAuth.percentEncode(s))
             .append('&')
             .append(OAuth.percentEncode(s1))
             .toString();
   } catch (Exception exception) {
     throw new OAuthMessageSignerException(exception);
   }
   return s;
 }
 /* (non-Javadoc)
  * This method is overridden in order to write the optional recordId|carenetId to the request output.
  *
  * @see oauth.signpost.basic.DefaultOAuthProvider#sendRequest(oauth.signpost.http.HttpRequest)
  */
 protected HttpResponse sendRequest(HttpRequest request) throws IOException {
   HttpURLConnection connection = (HttpURLConnection) request.unwrap();
   // if a shared recordId is defined, it has to be written in the request output
   if (this.sharedRecordId != null) {
     // write the recordId to the request output
     String indivoRecordId;
     if (this.sharedRecordId.isCarenet()) indivoRecordId = PARAM_INDIVO_CARENET_ID;
     else indivoRecordId = PARAM_INDIVO_RECORD_ID;
     indivoRecordId += "=" + this.sharedRecordId.getId();
     connection.setRequestProperty(
         TransportManager.PROPERTY_CONTENT_TYPE, TransportManager.CONTENT_TYPE_TEXT_PLAIN);
     connection.setDoOutput(true);
     OutputStream os = connection.getOutputStream();
     os.write(indivoRecordId.getBytes());
     os.close();
   }
   connection.connect();
   return new HttpURLConnectionResponseAdapter(connection);
 }
 public String normalizeRequestUrl() throws URISyntaxException {
   URI uri = new URI(request.getRequestUrl());
   String scheme = uri.getScheme().toLowerCase();
   String authority = uri.getAuthority().toLowerCase();
   boolean dropPort =
       (scheme.equals("http") && uri.getPort() == 80)
           || (scheme.equals("https") && uri.getPort() == 443);
   if (dropPort) {
     // find the last : in the authority
     int index = authority.lastIndexOf(":");
     if (index >= 0) {
       authority = authority.substring(0, index);
     }
   }
   String path = uri.getRawPath();
   if (path == null || path.length() <= 0) {
     path = "/"; // conforms to RFC 2616 section 3.2.2
   }
   // we know that there is no query and no fragment here.
   return scheme + "://" + authority + path;
 }
  /**
   * Implemented by subclasses. The responsibility of this method is to contact the service provider
   * at the given endpoint URL and fetch a request or access token. What kind of token is retrieved
   * solely depends on the URL being used.
   *
   * <p>Correct implementations of this method must guarantee the following post-conditions:
   *
   * <ul>
   *   <li>the {@link OAuthConsumer} passed to this method must have a valid {@link
   *       OAuth#OAUTH_TOKEN} and {@link OAuth#OAUTH_TOKEN_SECRET} set by calling {@link
   *       OAuthConsumer#setTokenWithSecret(String, String)}
   *   <li>{@link #getResponseParameters()} must return the set of query parameters served by the
   *       service provider in the token response, with all OAuth specific parameters being removed
   * </ul>
   *
   * @param consumer the {@link OAuthConsumer} that should be used to sign the request
   * @param endpointUrl the URL at which the service provider serves the OAuth token that is to be
   *     fetched
   * @param additionalParameters you can pass parameters here (typically OAuth parameters such as
   *     oauth_callback or oauth_verifier) which will go directly into the signer, i.e. you don't
   *     have to put them into the request first, just so the consumer pull them out again. Pass
   *     them sequentially in key/value order.
   * @throws OAuthMessageSignerException if signing the token request fails
   * @throws OAuthCommunicationException if a network communication error occurs
   * @throws OAuthNotAuthorizedException if the server replies 401 - Unauthorized
   * @throws OAuthExpectationFailedException if an expectation has failed, e.g. because the server
   *     didn't reply in the expected format
   */
  protected void retrieveToken(
      OAuthConsumer consumer, String endpointUrl, String... additionalParameters)
      throws OAuthMessageSignerException, OAuthCommunicationException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException {
    Map<String, String> defaultHeaders = getRequestHeaders();

    if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) {
      throw new OAuthExpectationFailedException("Consumer key or secret not set");
    }

    HttpRequest request = null;
    HttpResponse response = null;
    try {
      request = createRequest(endpointUrl);
      for (String header : defaultHeaders.keySet()) {
        request.setHeader(header, defaultHeaders.get(header));
      }
      if (additionalParameters != null) {
        HttpParameters httpParams = new HttpParameters();
        httpParams.putAll(additionalParameters, true);
        consumer.setAdditionalParameters(httpParams);
      }

      if (this.listener != null) {
        this.listener.prepareRequest(request);
      }

      consumer.sign(request);

      if (this.listener != null) {
        this.listener.prepareSubmission(request);
      }

      response = sendRequest(request);
      int statusCode = response.getStatusCode();

      boolean requestHandled = false;
      if (this.listener != null) {
        requestHandled = this.listener.onResponseReceived(request, response);
      }
      if (requestHandled) {
        return;
      }

      if (statusCode >= 300) {
        handleUnexpectedResponse(statusCode, response);
      }

      HttpParameters responseParams = OAuth.decodeForm(response.getContent());

      String token = responseParams.getFirst(OAuth.OAUTH_TOKEN);
      String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET);
      responseParams.remove(OAuth.OAUTH_TOKEN);
      responseParams.remove(OAuth.OAUTH_TOKEN_SECRET);

      setResponseParameters(responseParams);

      if (token == null || secret == null) {
        throw new OAuthExpectationFailedException(
            "Request token or token secret not set in server reply. "
                + "The service provider you use is probably buggy.");
      }

      consumer.setTokenWithSecret(token, secret);

    } catch (OAuthNotAuthorizedException e) {
      throw e;
    } catch (OAuthExpectationFailedException e) {
      throw e;
    } catch (Exception e) {
      throw new OAuthCommunicationException(e);
    } finally {
      try {
        closeConnection(request, response);
      } catch (Exception e) {
        throw new OAuthCommunicationException(e);
      }
    }
  }
 @Override
 protected HttpResponse sendRequest(HttpRequest request) throws Exception {
   Response response = okHttpClient.newCall((Request) request.unwrap()).execute();
   return new OkHttpResponseAdapter(response);
 }