play.libs.WS.HttpResponse - java examples

Here are the examples of the java api play.libs.WS.HttpResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

12 Examples 7

19 View Complete Implementation : OAuth2.java
Copyright Apache License 2.0
Author : eBay
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("redirect_uri", callbackURL);
    params.put("code", accessCode);
    HttpResponse response = WS.url(accessTokenURL).params(params).get();
    return new Response(response);
}

19 View Complete Implementation : NodeBackend.java
Copyright GNU General Public License v3.0
Author : openseedbox
public void cleanup() {
    HttpResponse res = node.getWebService("/backend/cleanup").get();
    getResponseBodyOrError(res);
}

19 View Complete Implementation : NodeBackend.java
Copyright GNU General Public License v3.0
Author : openseedbox
public void start() {
    HttpResponse res = node.getWebService("/backend/start").get();
    getResponseBodyOrError(res);
}

19 View Complete Implementation : NodeBackend.java
Copyright GNU General Public License v3.0
Author : openseedbox
public void stop() {
    HttpResponse res = node.getWebService("/backend/stop").get();
    getResponseBodyOrError(res);
}

19 View Complete Implementation : NodeBackend.java
Copyright GNU General Public License v3.0
Author : openseedbox
public void restart() {
    HttpResponse res = node.getWebService("/backend/restart").get();
    getResponseBodyOrError(res);
}

19 View Complete Implementation : NodeBackend.java
Copyright GNU General Public License v3.0
Author : openseedbox
private JsonElement getResponseBodyOrError(HttpResponse res) {
    return this.node.handleWebServiceResponse(res);
/*
		if (res.success()) {
			try {
				JsonObject ob = res.getJson().getAsJsonObject();
				if (ob.has("error")) {
					throw new MessageException(ob.get("error").getreplacedtring());
				}
				return ob.get("data");
			} catch (Exception ex) {
				throw new MessageException(ex.getMessage());
			}
		}
		throw new MessageException(res.getStatusText());*/
}

18 View Complete Implementation : OpenID.java
Copyright Apache License 2.0
Author : eBay
public boolean verify() {
    try {
        // Normalize
        String claimedId = normalize(id);
        String server = null;
        String delegate = null;
        // Discover
        HttpResponse response = WS.url(claimedId).get();
        // Try HTML (I know it's bad)
        String html = response.getString();
        server = discoverServer(html);
        if (server == null) {
            // Try YADIS
            Doreplacedent xrds = null;
            if (response.getContentType().contains("application/xrds+xml")) {
                xrds = response.getXml();
            } else if (response.getHeader("X-XRDS-Location") != null) {
                xrds = WS.url(response.getHeader("X-XRDS-Location")).get().getXml();
            } else {
                return false;
            }
            // Ok we have the XRDS file
            server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/server']/following-sibling::URI/text()", xrds);
            claimedId = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::LocalID/text()", xrds);
            if (claimedId == null) {
                claimedId = "http://specs.openid.net/auth/2.0/identifier_select";
            } else {
                server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::URI/text()", xrds);
            }
            if (server == null) {
                return false;
            }
        } else {
            // Delegate
            Matcher openid2Localid = Pattern.compile("<link[^>]+openid2[.]local_id[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html);
            Matcher openidDelegate = Pattern.compile("<link[^>]+openid[.]delegate[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html);
            if (openid2Localid.find()) {
                delegate = extractHref(openid2Localid.group());
            } else if (openidDelegate.find()) {
                delegate = extractHref(openidDelegate.group());
            }
        }
        // Redirect
        String url = server;
        if (!server.contains("?")) {
            url += "?";
        }
        if (!url.endsWith("?") && !url.endsWith("&")) {
            url += "&";
        }
        url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8");
        url += "&openid.mode=checkid_setup";
        url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8");
        url += "&openid.idenreplacedy=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8");
        if (returnAction != null && (returnAction.startsWith("http://") || returnAction.startsWith("https://"))) {
            url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8");
        } else {
            url += "&openid.return_to=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(returnAction), "utf8");
        }
        if (realmAction != null && (realmAction.startsWith("http://") || realmAction.startsWith("https://"))) {
            url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8");
        } else {
            url += "&openid.realm=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(realmAction), "utf8");
        }
        if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) {
            url += "&openid.ns.sreg=" + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8");
        }
        String sregO = "";
        for (String a : sregOptional) {
            sregO += URLEncoder.encode(a, "UTF-8") + ",";
        }
        if (!StringUtils.isEmpty(sregO)) {
            url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1);
        }
        String sregR = "";
        for (String a : sregRequired) {
            sregR += URLEncoder.encode(a, "UTF-8") + ",";
        }
        if (!StringUtils.isEmpty(sregR)) {
            url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1);
        }
        if (!axRequired.isEmpty() || !axOptional.isEmpty()) {
            url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0";
            url += "&openid.ax.mode=fetch_request";
            for (String a : axOptional.keySet()) {
                url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8");
            }
            for (String a : axRequired.keySet()) {
                url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8");
            }
            if (!axRequired.isEmpty()) {
                String r = "";
                for (String a : axRequired.keySet()) {
                    r += "," + a;
                }
                r = r.substring(1);
                url += "&openid.ax.required=" + r;
            }
            if (!axOptional.isEmpty()) {
                String r = "";
                for (String a : axOptional.keySet()) {
                    r += "," + a;
                }
                r = r.substring(1);
                url += "&openid.ax.if_available=" + r;
            }
        }
        if (Logger.isTraceEnabled()) {
            // Debug
            Logger.trace("Send request %s", url);
        }
        throw new Redirect(url);
    } catch (Redirect e) {
        throw e;
    } catch (PlayException e) {
        throw e;
    } catch (Exception e) {
        return false;
    }
}

18 View Complete Implementation : NodeBackend.java
Copyright GNU General Public License v3.0
Author : openseedbox
private ITorrent add(File file, String urlOrMagnet) {
    WSRequest req = node.getWebService("/torrents/add");
    // some torrents can take ages to add due to the encryption and having to be allocated
    req.timeout("1min");
    HttpResponse res;
    if (file != null) {
        FileParam fp = new FileParam(file, "torrent");
        req.files(fp);
        res = req.post();
    } else {
        req.setParameter("url", urlOrMagnet);
        res = req.get();
    }
    JsonObject ob = getResponseBodyOrError(res).getAsJsonObject();
    return Util.getGson().fromJson(ob.get("torrent"), NodeTorrent.clreplaced);
}

18 View Complete Implementation : Node.java
Copyright GNU General Public License v3.0
Author : openseedbox
public JsonElement handleWebServiceResponse(HttpResponse res) {
    try {
        if (res.success()) {
            JsonObject fullResponse = res.getJson().getAsJsonObject();
            if (!fullResponse.get("success").getAsBoolean()) {
                String error = fullResponse.get("error").getreplacedtring();
                throw new MessageException(error);
            }
            return fullResponse.get("data");
        }
        throw new MessageException("Unsuccessful webservice call, status: " + res.getStatusText());
    } catch (Exception ex) {
        if (ex.getMessage().contains("Connection refused")) {
            throw new MessageException("Connection refused");
        } else if (ex.getMessage().contains("No route to host")) {
            throw new MessageException("Unable to contact node at all! No route to host.");
        }
        throw new MessageException(Util.getStackTrace(ex));
    }
}

18 View Complete Implementation : Node.java
Copyright GNU General Public License v3.0
Author : openseedbox
public INodeStatus getNodeStatus(boolean fromDb) {
    if (fromDb) {
        return status;
    }
    HttpResponse res = getWebService("/status").get();
    if (res.success()) {
        JsonObject fullResponse = handleWebServiceResponse(res).getAsJsonObject();
        status = Util.getGson().fromJson(fullResponse, EmbeddableNodeStatus.clreplaced);
        new Job() {

            @Override
            public void doJob() throws Exception {
                update();
            }
        }.now();
        return status;
    } else {
        throw new MessageException("Node returned status: " + res.getStatus() + ". Probably java isnt running.");
    }
}

17 View Complete Implementation : IsohuntSearchPlugin.java
Copyright GNU General Public License v3.0
Author : openseedbox
@Override
public List<PluginSearchResult> doSearch(String terms) {
    List<PluginSearchResult> ret = new ArrayList<PluginSearchResult>();
    HttpResponse res = WS.url("http://ca.isohunt.com/js/json.php?ihq=%s&rows=20&sort=seeds", terms).get();
    if (res.getJson() != null) {
        JsonObject itemsObject = res.getJson().getAsJsonObject().getAsJsonObject("items");
        if (itemsObject != null) {
            JsonArray items = itemsObject.getAsJsonArray("list");
            for (JsonElement i : items) {
                JsonObject it = i.getAsJsonObject();
                PluginSearchResult psr = new PluginSearchResult();
                psr.setTorrentName(Util.stripHtml(it.get("replacedle").getreplacedtring()));
                psr.setTorrentUrl(it.get("enclosure_url").getreplacedtring());
                psr.setCurrentPeers(it.get("leechers").getreplacedtring());
                psr.setCurrentSeeders(it.get("Seeds").getreplacedtring());
                psr.setFileSize(Util.getBestRate(it.get("length").getAsLong()));
                ret.add(psr);
            }
        }
    }
    return ret;
}

17 View Complete Implementation : Auth.java
Copyright GNU General Public License v3.0
Author : openseedbox
public static void authenticate(String id_token) throws Exception {
    HttpResponse googleResponse = WS.url(GOOGLE_TOKEN_ENDPOINT).setParameter("id_token", id_token).getAsync().get();
    JsonObject body = googleResponse.getJson().getAsJsonObject();
    if (body.has("email")) {
        String emailAddress = body.get("email").getreplacedtring();
        User u = User.findByEmailAddress(emailAddress);
        if (u == null) {
            // create new user
            u = new User();
            u.setEmailAddress(emailAddress);
            // also set displayname, as it's required (fixes /admin/edituser)
            u.setDisplayName(emailAddress);
            u.setAvatarUrl(String.format("https://www.gravatar.com/avatar/%s", DigestUtils.md5Hex(u.getEmailAddress())));
            u.setLastAccess(new Date());
            // if this is the very first user, set them as admin
            boolean isFirstUser = User.count() == 0;
            u.setAdmin(isFirstUser);
            u.save();
            // reload user and signin automatically
            u = User.findByEmailAddress(emailAddress);
            session.put("currentUserId", u.getId());
        } else {
            // login user
            u.setLastAccess(new Date());
            u.save();
            session.put("currentUserId", u.getId());
        }
        redirect("/client");
    } else if (body.has("error")) {
        String errorreplacedtring = body.get("error").getreplacedtring();
        Logger.warn("Got error from Google! Error: %s, token: %s", errorreplacedtring, id_token);
        logoutWithMessage(String.format("Something wrong in the Google response: %s", errorreplacedtring), Level.WARNING);
    } else {
        Logger.info("No email, no error! What next?!");
        logoutWithMessage("Please grant the \"email\" OAuth scope to the application and try again!", Level.WARNING);
    }
}