public static void quotes() throws DOMException, InterruptedException, ExecutionException {
    Promise<HttpResponse> promise2 =
        WS.url("http://www.iheartquotes.com/api/v1/random?format=json").getAsync();
    Promise<HttpResponse> promise1 =
        WS.url("http://jamocreations.com/widgets/travel-quotes/get.php").getAsync();
    Map map = new HashMap<String, String>();

    // code here, preferably long running like db queries...
    List<HttpResponse> resps = Promise.waitAll(promise1, promise2).get();
    if (resps.get(0) != null) {
      map.put(
          "first",
          resps
              .get(0)
              .getXml()
              .getElementsByTagName("quote")
              .item(0)
              .getChildNodes()
              .item(1)
              .getTextContent());
    }
    if (resps.get(1) != null) {
      map.put("second", ((JsonObject) resps.get(1).getJson()).get("quote").getAsString());
    }
    renderJSON(map);
  }
Пример #2
0
  // TODO:  Make this more decoupled and unit testable
  public static void resolveHerdDependency(Long id, String name, String version)
      throws IOException {
    models.Upload upload = getUpload(id);

    HerdDependency hd = getHerdDependency(upload, name, version);
    // check that we didn't already resolve it from Herd
    if (hd != null) {
      Validation.addError(null, "Module already resolved from Herd");
      prepareForErrorRedirect();
      view(id);
    }

    String url = "http://modules.ceylon-lang.org/modules/" + name + "/" + version;

    Logger.info("Looking up module in Herd at: %s", url);
    HttpResponse response = WS.url(url).head();
    if (response.getStatus() == HttpURLConnection.HTTP_OK) {
      hd = new HerdDependency(name, version, upload);
      hd.create();
      flash("message", "Found in Herd");
    } else if (response.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
      flash("message", "Module could not be found in Herd");
    } else {
      flash(
          "message",
          "Module could not be found in Herd: "
              + response.getStatus()
              + ": "
              + response.getString());
    }

    view(id);
  }
Пример #3
0
  public static void resolveMavenDependency(Long id, String name, String version)
      throws IOException {
    models.Upload upload = getUpload(id);

    MavenDependency md = getMavenDependency(upload, name, version);
    // check that we didn't already resolve it from Maven
    if (md != null) {
      Validation.addError(null, "Module already resolved from Maven");
      prepareForErrorRedirect();
      view(id);
    }

    // check if the module in question is really in maven
    // ex: http://repo1.maven.org/maven2/io/vertx/vertx-core/2.0.0-beta5/vertx-core-2.0.0-beta5.jar
    int idSep = name.lastIndexOf(':');
    if (idSep == -1) idSep = name.lastIndexOf('.');
    if (idSep == -1) {
      Validation.addError(
          null,
          "Module name does not contain any ':' or '.' (used to separate the artifact group and ID)");
      prepareForErrorRedirect();
      view(id);
    }
    String mavenUrl = Play.configuration.getProperty("maven.url", "http://repo1.maven.org/maven2");
    String groupId = name.substring(0, idSep);
    String groupIdPath = groupId.replace('.', '/');
    String artifactId = name.substring(idSep + 1);
    String url =
        mavenUrl
            + "/"
            + groupIdPath
            + "/"
            + artifactId
            + "/"
            + version
            + "/"
            + artifactId
            + "-"
            + version
            + ".jar";

    Logger.info("Looking up module in Maven Central at: %s", url);
    HttpResponse response = WS.url(url).head();
    if (response.getStatus() == HttpURLConnection.HTTP_OK) {
      md = new MavenDependency(name, version, upload);
      md.create();
      flash("message", "Found in Maven central");
    } else if (response.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
      flash("message", "Module could not be found in Maven central");
    } else {
      flash(
          "message",
          "Module could not be found in Maven central: "
              + response.getStatus()
              + ": "
              + response.getString());
    }

    view(id);
  }
Пример #4
0
 public Response retrieveAccessToken(String callbackURL) {
   String accessCode = Params.current().get("code");
   Map<String, Object> params = new HashMap<String, Object>();
   params.put("client_id", clientid);
   params.put("client_secret", secret);
   params.put("grant_type", "authorization_code");
   params.put("redirect_uri", callbackURL);
   params.put("code", accessCode);
   HttpResponse response = WS.url(accessTokenURL).params(params).post();
   return new Response(response);
 }
Пример #5
0
 /**
  * Calls the API with the given parameters and returns a response.
  *
  * @param url API url to call
  * @param queryParams A String array with the query parameters
  * @param headers A String Array with the headers
  * @return The response of the service call
  */
 private WS.Response callApi(
     final String url, final String[] queryParams, final String[] headers) {
   WSRequestHolder result = WS.url(SERVER_URL + url);
   if (queryParams != null)
     for (int i = 0; i + 1 < queryParams.length; i += 2) {
       result.setQueryParameter(queryParams[i], queryParams[i + 1]);
     }
   if (headers != null)
     for (int i = 0; i + 1 < headers.length; i += 2) {
       result.setHeader(headers[i], headers[i + 1]);
     }
   return result.get().get(10000);
 }
  private String getRequestToken(final Request request) throws AuthException {
    final Configuration c = getConfiguration();
    final List<NameValuePair> params = getRequestTokenParams(request, c);
    final Response r =
        WS.url(c.getString(SettingKeys.REQUEST_TOKEN_URL))
            .setHeader("Content-Type", "application/json")
            .setHeader("X-Accept", "application/json")
            .post(encodeParamsAsJson(params))
            .get(getTimeout());

    if (r.getStatus() >= 400) {
      throw new AuthException(r.asJson().asText());
    } else {
      return r.asJson().get(PocketConstants.CODE).asText();
    }
  }
Пример #7
0
 private static List<Talk> getTalks(String day) throws IOException {
   List<Map<String, Object>> talks =
       new Gson()
           .fromJson(
               WS.url("https://cfp.devoxx.com/rest/v1/events/7/schedule/day/%s", day)
                   .get()
                   .getString(),
               List.class);
   return validTalks(
       transform(
           talks,
           new Function<Map<String, Object>, Talk>() {
             @Override
             public Talk apply(Map<String, Object> talkAsMap) {
               return new Talk(talkAsMap);
             }
           }));
 }
  public void unsubscribe(String user, String repository, String type) {
    WSRequest request = WS.url("https://api.github.com/hub");
    request.authenticate(username, password);

    request.setParameter("hub.mode", "unsubscribe");
    request.setParameter(
        "hub.topic", String.format("https://github.com/%s/%s/events/%s", user, repository, type));

    play.libs.WS.HttpResponse response = request.post();

    Logger.info("Response status : " + response.getStatus());
    Logger.info("Response body : " + response.getString());

    if (response.getStatus() == 204) {

    } else {
      // TODO
    }
  }
Пример #9
0
  private Customer(String id) {
    if (id != null) {
      authenticate();
      String url = API_URL + "/customers/" + id;
      try {
        // Send request
        F.Promise<WS.Response> promise =
            WS.url(url)
                .setContentType("application/x-www-form-urlencoded")
                .setQueryParameter("access_token", access_token)
                .get();

        // Read request
        response = Json.parse(promise.get().getBody());
      } catch (Exception e) {
        play.Logger.error("Error on requesting customer");
      }
    }
  }
Пример #10
0
 public static Promise<Response> createCacheableUrlFetchPromise(
     String getUrl, Map<String, String> getParams) {
   final String key =
       "http-cache-" + getUrl + ":" + new TreeMap<String, String>(getParams).toString();
   final Response cached = (Response) Cache.get(key);
   if (cached == null) {
     WSRequestHolder holder = WS.url(getUrl);
     for (String k : getParams.keySet()) holder.setQueryParameter(k, getParams.get(k));
     Promise<Response> promise = holder.get();
     return promise.map(
         new Function<Response, Response>() {
           @Override
           public Response apply(Response res) throws Throwable {
             Cache.set(key, res);
             synchronized (cachedSet) {
               cachedSet.insert(key);
             }
             return res;
           }
         });
   } else {
     return Promise.pure(cached);
   }
 }