private void handleExceptions(Response response) throws N0ticeException {
   log.error(
       "Exception during n0tice api call: " + response.getCode() + ", " + response.getBody());
   if (response.getCode() == 404) {
     throw new NotFoundException("Not found");
   }
   if (response.getCode() == 403) {
     throw new NotAllowedException();
   }
   if (response.getCode() == 401) {
     throw new AuthorisationException(response.getBody());
   }
   if (response.getCode() == 400) {
     throw new BadRequestException(response.getBody());
   }
 }
  public AccessToken authUser(
      String consumerKey, String username, String password, String consumerSecret)
      throws N0ticeException {
    log.info(
        "Attempting to auth user: "******", "
            + username
            + ", "
            + password
            + ", "
            + consumerSecret);
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/auth");
    addBodyParameter(request, "consumerkey", consumerKey);
    addBodyParameter(request, "username", username);
    addBodyParameter(request, "password", password);

    // Manually sign this request using the consumer secret rather than the access key/access
    // secret.
    addBodyParameter(request, "oauth_signature_method", "HMAC-SHA1");
    addBodyParameter(request, "oauth_version", "1.0");
    addBodyParameter(request, "oauth_timestamp", Long.toString(DateTimeUtils.currentTimeMillis()));
    final String effectiveUrl = request.getCompleteUrl() + "?" + request.getBodyContents();
    addBodyParameter(request, "oauth_signature", sign(effectiveUrl, consumerSecret));

    final Response response = request.send();
    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return new UserParser().parseAuthUserResponse(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public User updateUserDetails(String username, String displayName, String bio, MediaFile image)
      throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/" + username);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (displayName != null) {
      addStringPart(entity, "displayName", displayName);
    }
    if (bio != null) {
      addStringPart(entity, "bio", bio);
    }
    if (image != null) {
      entity.addPart("image", new ByteArrayBody(image.getData(), image.getFilename()));
    }

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String repsonseBody = response.getBody();
    if (response.getCode() == 200) {
      return new UserParser().parseUserProfile(repsonseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
Пример #4
0
 @Override
 protected FacebookProfile retrieveUserProfileFromToken(final Token accessToken) {
   String body = sendRequestForData(accessToken, getProfileUrl(accessToken));
   if (body == null) {
     throw new HttpCommunicationException("Not data found for accessToken : " + accessToken);
   }
   final FacebookProfile profile = extractUserProfile(body);
   addAccessTokenToProfile(profile, accessToken);
   if (profile != null && this.requiresExtendedToken) {
     String url =
         CommonHelper.addParameter(EXCHANGE_TOKEN_URL, OAuthConstants.CLIENT_ID, this.key);
     url = CommonHelper.addParameter(url, OAuthConstants.CLIENT_SECRET, this.secret);
     url = addExchangeToken(url, accessToken);
     final ProxyOAuthRequest request = createProxyRequest(url);
     final long t0 = System.currentTimeMillis();
     final Response response = request.send();
     final int code = response.getCode();
     body = response.getBody();
     final long t1 = System.currentTimeMillis();
     logger.debug("Request took : " + (t1 - t0) + " ms for : " + url);
     logger.debug("response code : {} / response body : {}", code, body);
     if (code == 200) {
       logger.debug("Retrieve extended token from : {}", body);
       final Token extendedAccessToken = this.api20.getAccessTokenExtractor().extract(body);
       logger.debug("Extended token : {}", extendedAccessToken);
       addAccessTokenToProfile(profile, extendedAccessToken);
     } else {
       logger.error("Cannot get extended token : {} / {}", code, body);
     }
   }
   return profile;
 }
Пример #5
0
  protected void remoteProcessAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, getServerPortletURL());

    setRequestParameters(actionRequest, actionResponse, oAuthRequest);

    addOAuthParameter(oAuthRequest, "p_p_lifecycle", "1");
    addOAuthParameter(oAuthRequest, "p_p_state", WindowState.NORMAL.toString());

    Response response = getResponse(themeDisplay.getUser(), oAuthRequest);

    if (response.getCode() == HttpServletResponse.SC_FOUND) {
      String redirectLocation = response.getHeader(HttpHeaders.LOCATION);

      actionResponse.sendRedirect(redirectLocation);
    } else {
      HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse);

      httpServletResponse.setContentType(response.getHeader(HttpHeaders.CONTENT_TYPE));

      ServletResponseUtil.write(httpServletResponse, response.getStream());
    }
  }
  public Noticeboard editNoticeboard(
      String domain,
      String name,
      String description,
      Boolean moderated,
      Boolean featured,
      MediaFile cover)
      throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, urlBuilder.noticeBoard(domain));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    addEntityPartParameter(entity, "name", name);
    addEntityPartParameter(entity, "description", description);
    addEntityPartParameter(
        entity, "moderated", moderated != null ? Boolean.toString(moderated) : null);
    addEntityPartParameter(
        entity, "featured", featured != null ? Boolean.toString(featured) : null);
    if (cover != null) {
      entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename()));
    }

    // TODO implement
    /*
    if (endDate != null) {
    	addEntityPartParameter(entity, "endDate", ISODateTimeFormat.dateTimeNoMillis().print(new DateTime(endDate)));
    }
    if (cover != null) {
    	entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename()));
    }

    StringBuilder supportedMediaTypesValue = new StringBuilder();
    Iterator<MediaType> supportedMediaTypesIterator = supportedMediaTypes.iterator();
    while(supportedMediaTypesIterator.hasNext()) {
    	supportedMediaTypesValue.append(supportedMediaTypesIterator.next());
    	if (supportedMediaTypesIterator.hasNext()) {
    		supportedMediaTypesValue.append(COMMA);
    	}
    }
    addEntityPartParameter(entity, "supportedMediaTypes", supportedMediaTypesValue.toString());

    if (group != null) {
    	addEntityPartParameter(entity, "group", group);
    }
    */

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return noticeboardParser.parseNoticeboardResult(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public void closeNoticeboard(String domain) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, urlBuilder.closeNoticeboard(domain));
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public Content authedGet(String id) throws N0ticeException {
    final OAuthRequest request = createOauthRequest(Verb.GET, urlBuilder.get(id));
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return searchParser.parseReport(response.getBody());
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public List<ModerationComplaint> getModerationComplaints(String id) throws N0ticeException {
    final OAuthRequest request = createOauthRequest(Verb.GET, urlBuilder.get(id) + "/flags");
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return moderationComplaintParser.parse(response.getBody());
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public int interestingVotes(String id) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.GET, apiUrl + "/" + id + "/votes/interesting");

    final Response response = request.send();

    if (response.getCode() == 200) {
      return searchParser.parseVotes(response.getBody());
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public boolean voteInteresting(String id) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/" + id + "/vote/interesting");
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return true;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public boolean followUser(String username) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/" + username + "/follow");
    oauthSignRequest(request);

    final Response response = request.send();

    if (response.getCode() == 200) {
      return true;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public void closeModerationComplaint(String contentId, int flagId) throws N0ticeException {
    final OAuthRequest request =
        createOauthRequest(Verb.POST, urlBuilder.closeModerationComplaint(contentId, flagId));
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public List<String> notifications(String username) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.GET, urlBuilder.userNotifications(username));
    oauthSignRequest(request);

    final Response response = request.send();

    if (response.getCode() == 200) {
      return searchParser.parseNotifications(response.getBody());
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public boolean deleteReport(String id) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.DELETE, apiUrl + "/" + id);
    oauthSignRequest(request);

    final Response response = request.send();

    if (response.getCode() == 200) {
      return true;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public boolean moderate(String id, String notes, String action) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/" + id + "/moderate/" + action);
    addBodyParameter(request, "notes", notes);
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return true;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public Map<String, Map<String, String>> imageExif(String id) throws N0ticeException {
    final OAuthRequest request =
        createOauthRequest(Verb.GET, urlBuilder.get("image/" + id + "/exif"));
    oauthSignRequest(request);

    final Response response = request.send();
    if (response.getCode() == 200) {
      return exifParser.parse(response.getBody());
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public boolean unfollowNoticeboard(String noticeboard) throws N0ticeException {
    OAuthRequest request =
        createOauthRequest(Verb.POST, apiUrl + "/noticeboard/" + noticeboard + "/unfollow");
    oauthSignRequest(request);

    final Response response = request.send();

    if (response.getCode() == 200) {
      return true;
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public ResultSet authedSearch(SearchQuery searchQuery) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.GET, searchUrlBuilder.toUrl(searchQuery));
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return searchParser.parseSearchResults(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public User verify() throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.GET, apiUrl + "/verify"); // TODO most be a POST
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return userParser.parseUserProfile(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public static void main(String[] args) {

    String apiKey = "your_app_id";
    String apiSecret = "your_api_secret";

    OAuthService service =
        new ServiceBuilder() //
            .provider(BitlyApi.class) //
            .apiKey(apiKey) //
            .apiSecret(apiSecret) //
            .callback("http://localhost:8080/oauth_callback") //
            .debug() //
            .build();
    Scanner in = new Scanner(System.in);

    System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
    System.out.println();

    // Obtain the Authorization URL
    System.out.println("Fetching the Authorization URL...");
    String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
    System.out.println("Got the Authorization URL!");
    System.out.println("Now go and authorize Scribe here:");
    System.out.println(authorizationUrl);
    System.out.println("And paste the authorization code here");
    System.out.print(">>");
    Verifier verifier = new Verifier(in.nextLine());
    System.out.println();

    // Trade the Request Token and Verfier for the Access Token
    System.out.println("Trading the Request Token for an Access Token...");
    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
    System.out.println("Got the Access Token!");
    System.out.println("(if your curious it looks like this: " + accessToken + " )");
    System.out.println();

    // Now let's go and ask for a protected resource!
    System.out.println("Now we're going to access a protected resource...");
    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
    service.signRequest(accessToken, request);
    Response response = request.send();
    System.out.println("Got it! Lets see what we found...");
    System.out.println();
    System.out.println(response.getCode());
    System.out.println(response.getBody());

    System.out.println();
    System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
  }
  public Content updateReport(String id, String headline, String body) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/" + id);
    addBodyParameter(request, "headline", headline);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return searchParser.parseReport(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
Пример #23
0
  public static void main(String[] args) {
    // Replace these with your client id and secret
    final String clientId = "your client id";
    final String clientSecret = "your client secret";
    final OAuthService service =
        new ServiceBuilder()
            .provider(TutByApi.class)
            .apiKey(clientId)
            .apiSecret(clientSecret)
            .grantType("authorization_code")
            .callback("http://www.example.com/oauth_callback/")
            .build();
    final Scanner in = new Scanner(System.in, "UTF-8");

    System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
    System.out.println();

    System.out.println("Fetching the Authorization URL...");
    final String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
    System.out.println("Got the Authorization URL!");
    System.out.println("Now go and authorize SubScribe here:");
    System.out.println(authorizationUrl);
    System.out.println("And paste the authorization code here");
    System.out.print(">>");
    final Verifier verifier = new Verifier(in.nextLine());
    System.out.println();

    // Trade the Request Token and Verfier for the Access Token
    System.out.println("Trading the Request Token for an Access Token...");
    final Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
    System.out.println("Got the Access Token!");
    System.out.println("(if your curious it looks like this: " + accessToken + " )");
    System.out.println();

    // Now let's go and ask for a protected resource!
    System.out.println("Now we're going to access a protected resource...");
    final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
    service.signRequest(accessToken, request);
    final Response response = request.send();
    System.out.println("Got it! Lets see what we found...");
    System.out.println();
    System.out.println(response.getCode());
    System.out.println(response.getBody());

    System.out.println();
    System.out.println("Thats it man! Go and build something awesome with SubScribe! :)");
  }
Пример #24
0
  public static void main(String[] args) {
    String apiKey = "357304594324208";
    String apiSecret = "8eca9a549d5c3631752c4d472a5814c1";
    OAuthService service =
        new ServiceBuilder()
            .provider(FacebookApi.class)
            .apiKey(apiKey)
            .apiSecret(apiSecret)
            .callback("https://sharp-night-6938.herokuapp.com/oauth_callback/")
            .build();
    Scanner in = new Scanner(System.in);

    System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
    System.out.println();

    // Obtain the Authorization URL
    System.out.println("Fetching the Authorization URL...");
    String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
    System.out.println("Got the Authorization URL!");
    System.out.println("Now go and authorize Scribe here:");
    System.out.println(authorizationUrl);
    System.out.println("And paste the authorization code here");
    System.out.print(">>");
    Verifier verifier = new Verifier(in.nextLine());
    System.out.println();

    // Trade the Request Token and Verfier for the Access Token
    System.out.println("Trading the Request Token for an Access Token...");
    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
    System.out.println("Got the Access Token!");
    System.out.println("(if your curious it looks like this: " + accessToken + " )");
    System.out.println();

    // Now let's go and ask for a protected resource!
    System.out.println("Now we're going to access a protected resource...");
    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
    service.signRequest(accessToken, request);
    Response response = request.send();
    System.out.println("Got it! Lets see what we found...");
    System.out.println();
    System.out.println(response.getCode());
    System.out.println(response.getBody());

    System.out.println();
  }
  public Content postReport(
      String headline,
      Double latitude,
      Double longitude,
      String body,
      String link,
      MediaFile image,
      VideoAttachment video,
      String noticeboard,
      DateTime date)
      throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/report/new");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (headline != null) {
      addStringPart(entity, "headline", headline);
    }
    if (noticeboard != null) {
      addStringPart(entity, "noticeboard", noticeboard);
    }

    if (latitude != null && longitude != null) {
      addStringPart(entity, "latitude", Double.toString(latitude));
      addStringPart(entity, "longitude", Double.toString(longitude));
    }

    populateUpdateFields(body, link, image, video, entity);

    if (date != null) {
      addStringPart(entity, "date", date.toString(ZULE_TIME_FORMAT));
    }

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return searchParser.parseReport(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
 /**
  * Makes a request to get the profile of the authenticated user for this provider.
  *
  * @param accessToken
  * @param profileUrl
  * @return
  */
 protected String sendRequestForProfile(Token accessToken, String profileUrl) {
   logger.debug("accessToken : {} / profileUrl : {}", accessToken, profileUrl);
   OAuthRequest request = new OAuthRequest(Verb.GET, profileUrl);
   service.signRequest(accessToken, request);
   // for Google
   if (this instanceof GoogleProvider) {
     request.addHeader("GData-Version", "3.0");
   }
   Response response = request.send();
   int code = response.getCode();
   String body = response.getBody();
   logger.debug("response code : {} / response body : {}", code, body);
   if (code != 200) {
     logger.error("Get the user profile failed, code : " + code + " / body : " + body);
     return null;
   }
   return body;
 }
  public NewUserResponse createUser(
      String consumerKey, String username, String password, String email) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/new");
    addBodyParameter(request, "consumerkey", consumerKey);
    addBodyParameter(request, "username", username);
    addBodyParameter(request, "password", password);
    addBodyParameter(request, "email", email);

    final Response response = request.send();

    final String repsonseBody = response.getBody();
    if (response.getCode() == 200) {
      return new UserParser().parseNewUserResponse(repsonseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public Content postEvent(
      String headline,
      double latitude,
      double longitude,
      String body,
      String link,
      MediaFile image,
      VideoAttachment video,
      String noticeboard,
      LocalDateTime startDate,
      LocalDateTime endDate,
      Reoccurence reoccurence,
      LocalDateTime reoccursTo)
      throws N0ticeException {
    final OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/event/new");

    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    addEntityPartParameter(entity, "headline", headline);
    addEntityPartParameter(entity, "noticeboard", noticeboard);
    addEntityPartParameter(entity, "latitude", Double.toString(latitude));
    addEntityPartParameter(entity, "longitude", Double.toString(longitude));
    populateUpdateFields(body, link, image, video, entity);

    addEntityPartParameter(entity, "startDate", startDate.toString(LOCAL_DATE_TIME_FORMAT));
    addEntityPartParameter(entity, "endDate", endDate.toString(LOCAL_DATE_TIME_FORMAT));
    if (reoccurence != null && reoccursTo != null) {
      addEntityPartParameter(entity, "reoccurs", reoccurence.toString());
      addEntityPartParameter(entity, "reoccursTo", reoccursTo.toString(LOCAL_DATE_TIME_FORMAT));
    }

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return searchParser.parseReport(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public Group createGroup(String name) throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/groups/new");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    addEntityPartParameter(entity, "name", name);

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return searchParser.parseGroupResult(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public Token getRequestToken(RequestTuner tuner) {
    config.log("obtaining request token from " + api.getRequestTokenEndpoint());
    OAuthRequest request =
        new OAuthRequest(api.getRequestTokenVerb(), api.getRequestTokenEndpoint());

    config.log("setting oauth_callback to " + config.getCallback());
    request.addOAuthParameter(OAuthConstants.CALLBACK, config.getCallback());

    addOAuthParams(request, OAuthConstants.EMPTY_TOKEN);
    appendSignature(request);

    config.log("sending request...");
    Response response = request.send(tuner);
    String body = response.getBody();

    config.log("response status code: " + response.getCode());
    config.log("response body: " + body);
    return api.getRequestTokenExtractor().extract(body);
  }