Example usage for java.net URI toString

List of usage examples for java.net URI toString

Introduction

In this page you can find the example usage for java.net URI toString.

Prototype

public String toString() 

Source Link

Document

Returns the content of this URI as a string.

Usage

From source file:com.shareplaylearn.OauthPasswordFlow.java

public static LoginInfo googleLogin(String username, String password, String clientId, String callbackUri)
        throws URISyntaxException, IOException, AuthorizationException, UnauthorizedException {

    CloseableHttpClient httpClient = HttpClients.custom().build();
    String oAuthQuery = "client_id=" + clientId + "&";
    oAuthQuery += "response_type=code&";
    oAuthQuery += "scope=openid email&";
    oAuthQuery += "redirect_uri=" + callbackUri;
    URI oAuthUrl = new URI("https", null, "accounts.google.com", 443, "/o/oauth2/auth", oAuthQuery, null);
    Connection oauthGetCoonnection = Jsoup.connect(oAuthUrl.toString());
    Connection.Response oauthResponse = oauthGetCoonnection.method(Connection.Method.GET).execute();
    if (oauthResponse.statusCode() != 200) {
        String errorMessage = "Error contacting Google's oauth endpoint: " + oauthResponse.statusCode() + " / "
                + oauthResponse.statusMessage();
        if (oauthResponse.body() != null) {
            errorMessage += oauthResponse.body();
        }//from   w ww .jav  a 2s .  c  o m
        throw new AuthorizationException(errorMessage);
    }
    Map<String, String> oauthCookies = oauthResponse.cookies();
    Document oauthPage = oauthResponse.parse();
    Element oauthForm = oauthPage.getElementById("gaia_loginform");
    System.out.println(oauthForm.toString());
    Connection oauthPostConnection = Jsoup.connect("https://accounts.google.com/ServiceLoginAuth");
    HashMap<String, String> formParams = new HashMap<>();

    for (Element child : oauthForm.children()) {
        System.out.println("Tag name: " + child.tagName());
        System.out.println("attrs: " + Arrays.toString(child.attributes().asList().toArray()));
        if (child.tagName().equals("input") && child.hasAttr("name")) {

            String keyName = child.attr("name");
            String keyValue = null;

            if (child.hasAttr("value")) {
                keyValue = child.attr("value");
            }

            if (keyName != null && keyName.trim().length() != 0 && keyValue != null
                    && keyValue.trim().length() != 0) {
                oauthPostConnection.data(keyName, keyValue);
                formParams.put(keyName, keyValue);
            }
        }
    }
    oauthPostConnection.cookies(oauthCookies);
    formParams.put("Email", username);
    formParams.put("Passwd-hidden", password);
    //oauthPostConnection.followRedirects(false);
    System.out.println("form post params were: ");
    for (Map.Entry<String, String> kvp : formParams.entrySet()) {
        //DO NOT let passwords end up in the logs ;)
        if (kvp.getKey().equals("Passwd")) {
            continue;
        }
        System.out.println(kvp.getKey() + "," + kvp.getValue());
    }
    System.out.println("form cookies were: ");
    for (Map.Entry<String, String> cookie : oauthCookies.entrySet()) {
        System.out.println(cookie.getKey() + "," + cookie.getValue());
    }
    //System.exit(0);
    Connection.Response postResponse = null;
    try {
        postResponse = oauthPostConnection.method(Connection.Method.POST).timeout(5000).execute();
    } catch (Throwable t) {
        System.out.println("Failed to post login information to googles endpoint :/ " + t.getMessage());
        System.out.println("This usually means the connection is bad, shareplaylearn.com is down, or "
                + " google is being a punk - login manually and check.");
        assertTrue(false);
    }
    if (postResponse.statusCode() != 200) {
        String errorMessage = "Failed to validate credentials: " + oauthResponse.statusCode() + " / "
                + oauthResponse.statusMessage();
        if (oauthResponse.body() != null) {
            errorMessage += oauthResponse.body();
        }
        throw new UnauthorizedException(errorMessage);
    }
    System.out.println("Response headers (after post to google form & following redirect):");
    for (Map.Entry<String, String> header : postResponse.headers().entrySet()) {
        System.out.println(header.getKey() + "," + header.getValue());
    }
    System.out.println("Final response url was: " + postResponse.url().toString());
    String[] args = postResponse.url().toString().split("&");
    LoginInfo loginInfo = new LoginInfo();
    for (String arg : args) {
        if (arg.startsWith("access_token")) {
            loginInfo.accessToken = arg.split("=")[1].trim();
        } else if (arg.startsWith("id_token")) {
            loginInfo.idToken = arg.split("=")[1].trim();
        } else if (arg.startsWith("expires_in")) {
            loginInfo.expiry = arg.split("=")[1].trim();
        }
    }

    //Google doesn't actually throw a 401 or anything - it just doesn't redirect
    //and sends you back to it's login page to try again.
    //So this is what happens with an invalid password.
    if (loginInfo.accessToken == null || loginInfo.idToken == null) {
        //Document oauthPostResponse = postResponse.parse();
        //System.out.println("*** Oauth response from google *** ");
        //System.out.println(oauthPostResponse.toString());
        throw new UnauthorizedException(
                "Error retrieving authorization: did you use the correct username/password?");
    }
    String[] idTokenFields = loginInfo.idToken.split("\\.");
    if (idTokenFields.length < 3) {
        throw new AuthorizationException("Error parsing id token " + loginInfo.idToken + "\n" + "it only had "
                + idTokenFields.length + " field!");
    }
    String jwtBody = new String(Base64.decodeBase64(idTokenFields[1]), StandardCharsets.UTF_8);
    loginInfo.idTokenBody = new Gson().fromJson(jwtBody, OauthJwt.class);
    loginInfo.id = loginInfo.idTokenBody.sub;
    return loginInfo;
}

From source file:com.ibm.watson.movieapp.dialog.rest.UtilityFunctions.java

/**
 * Makes HTTP GET request/*from  w  w  w.  j  a  v  a2s  .c o m*/
 * <p>
 * This makes HTTP GET requests to the url provided.
 * 
 * @param httpClient the http client used to make the request
 * @param uri the uri for the request
 * @return the JSON object response
 * @throws ClientProtocolException if it is unable to execute the call
 * @throws IOException if it is unable to execute the call
 * @throws IllegalStateException if the input stream could not be parsed correctly
 * @throws HttpException if the HTTP call responded with a status code other than 200 or 201
 */
public static JsonObject httpGet(CloseableHttpClient httpClient, URI uri)
        throws ClientProtocolException, IOException, IllegalStateException, HttpException {
    HttpGet httpGet = new HttpGet(uri);
    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        return UtilityFunctions.parseHTTPResponse(response, uri.toString());
    } catch (ClientProtocolException e) {
        throw e;
    }

}

From source file:org.altchain.neo4j.database.Database.java

@SuppressWarnings("unchecked")
public static URI cypherQueryGetSingle(String query) {

    String cypherUri = "http://localhost:7474/db/data/cypher";

    WebResource resource = Client.create().resource(cypherUri);

    JSONObject queryObject = new JSONObject();
    queryObject.put("query", query);
    queryObject.put("params", new JSONObject());

    //logger.info("query: "+query );

    ClientResponse clientResponse = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
            .entity(queryObject.toJSONString()).post(ClientResponse.class);

    String jsonString = clientResponse.getEntity(String.class);

    Object JSONResponse = JSONValue.parse(jsonString);
    //logger.info("json repsonse: "+jsonString );

    String path = null;/* www .j  a v  a2s  . co  m*/
    try {
        path = (String) ((JSONObject) ((JSONArray) ((JSONArray) ((JSONObject) JSONResponse).get("data")).get(0))
                .get(0)).get("self");
    } catch (Exception e) {
        logger.info("PROBLEM WITH CYPHER QUERY: " + query + " json response: " + JSONResponse.toString());
    }

    URI location = URI.create(path);
    logger.debug(String.format("POST to [%s], status code [%d], location header [%s], JSON: %s", cypherUri,
            clientResponse.getStatus(), location.toString(), queryObject.toJSONString()));

    clientResponse.close();

    return location;

}

From source file:com.feilong.core.net.ParamExtensionUtil.java

/**
 * url???./*  w  w w. j  av a 2s .c o  m*/
 * 
 * @param uri
 *            the uri
 * @param paramNameList
 *            ?????list
 * @param charsetType
 *            ??, {@link CharsetType}<br>
 *            <span style="color:green">null empty,?,?</span><br>
 *            ??,??,ie?chrome? url ,?
 * @return  <code>uri</code> null, {@link StringUtils#EMPTY}<br>
 *         ? {@link #retentionParamList(String, String, List, String)}
 * @see #retentionParamList(String, String, List, String)
 */
public static String retentionParamList(URI uri, List<String> paramNameList, String charsetType) {
    return null == uri ? EMPTY
            : retentionParamList(uri.toString(), uri.getRawQuery(), paramNameList, charsetType);
}

From source file:com.feilong.core.net.ParamExtensionUtil.java

/**
 * ?.//from w  ww .  j a v a  2  s. c o m
 * 
 * @param uri
 *            the uri
 * @param paramNameList
 *            ??? list
 * @param charsetType
 *            ??, {@link CharsetType}<br>
 *            <span style="color:green">null empty,?,?</span><br>
 *            ??,??,ie?chrome? url ,?
 * @return  <code>uri</code> null, {@link StringUtils#EMPTY}<br>
 *          <code>paramNameList</code> nullempty, <code>uri.toString()</code><br>
 */
public static String removeParameterList(URI uri, List<String> paramNameList, String charsetType) {
    return null == uri ? EMPTY
            : removeParameterList(uri.toString(), uri.getRawQuery(), paramNameList, charsetType);
}

From source file:com.lightbox.android.network.HttpHelper.java

private static URI addQueryParametersToUri(URI uri, Map<String, Object> urlParameters) {
    if (urlParameters != null && urlParameters.size() > 0) {
        Uri androidUri = Uri.parse(uri.toString());
        Uri.Builder uriBuilder = androidUri.buildUpon();
        for (Map.Entry<String, Object> param : urlParameters.entrySet()) {
            uriBuilder.appendQueryParameter(param.getKey(), param.getValue().toString());
        }//from ww w. j ava2s  .  c  om
        uri = URI.create(uriBuilder.build().toString());
    }
    return uri;
}

From source file:com.shareplaylearn.utilities.OauthPasswordFlow.java

public static LoginInfo googleLogin(String username, String password, String clientId, String callbackUri)
        throws URISyntaxException, IOException, AuthorizationException, UnauthorizedException {

    CloseableHttpClient httpClient = HttpClients.custom().build();
    String oAuthQuery = "client_id=" + clientId + "&";
    oAuthQuery += "response_type=code&";
    oAuthQuery += "scope=openid email&";
    oAuthQuery += "redirect_uri=" + callbackUri;
    URI oAuthUrl = new URI("https", null, "accounts.google.com", 443, "/o/oauth2/auth", oAuthQuery, null);
    Connection oauthGetCoonnection = Jsoup.connect(oAuthUrl.toString());
    Connection.Response oauthResponse = oauthGetCoonnection.method(Connection.Method.GET).execute();
    if (oauthResponse.statusCode() != 200) {
        String errorMessage = "Error contacting Google's oauth endpoint: " + oauthResponse.statusCode() + " / "
                + oauthResponse.statusMessage();
        if (oauthResponse.body() != null) {
            errorMessage += oauthResponse.body();
        }//w ww . j  ava  2s  .  c  om
        throw new AuthorizationException(errorMessage);
    }
    Map<String, String> oauthCookies = oauthResponse.cookies();
    Document oauthPage = oauthResponse.parse();
    Element oauthForm = oauthPage.getElementById("gaia_loginform");
    System.out.println(oauthForm.toString());
    Connection oauthPostConnection = Jsoup.connect("https://accounts.google.com/ServiceLoginAuth");
    HashMap<String, String> formParams = new HashMap<>();
    for (Element child : oauthForm.children()) {
        if (child.tagName().equals("input") && child.hasAttr("name")) {

            String keyName = child.attr("name");
            String keyValue = null;

            if (keyName.equals("Email")) {
                keyValue = username;
            } else if (keyName.equals("Passwd")) {
                keyValue = password;
            } else if (child.hasAttr("value")) {
                keyValue = child.attr("value");
            }

            if (keyValue != null) {
                oauthPostConnection.data(keyName, keyValue);
                formParams.put(keyName, keyValue);
            }
        }
    }
    oauthPostConnection.cookies(oauthCookies);
    //oauthPostConnection.followRedirects(false);
    System.out.println("form post params were: ");
    for (Map.Entry<String, String> kvp : formParams.entrySet()) {
        //DO NOT let passwords end up in the logs ;)
        if (kvp.getKey().equals("Passwd")) {
            continue;
        }
        System.out.println(kvp.getKey() + "," + kvp.getValue());
    }
    System.out.println("form cookies were: ");
    for (Map.Entry<String, String> cookie : oauthCookies.entrySet()) {
        System.out.println(cookie.getKey() + "," + cookie.getValue());
    }
    Connection.Response postResponse = null;
    try {
        postResponse = oauthPostConnection.method(Connection.Method.POST).timeout(5000).execute();
    } catch (Throwable t) {
        System.out.println("Failed to post login information to googles endpoint :/ " + t.getMessage());
        System.out.println("This usually means the connection is bad, shareplaylearn.com is down, or "
                + " google is being a punk - login manually and check.");
        assertTrue(false);
    }
    if (postResponse.statusCode() != 200) {
        String errorMessage = "Failed to validate credentials: " + oauthResponse.statusCode() + " / "
                + oauthResponse.statusMessage();
        if (oauthResponse.body() != null) {
            errorMessage += oauthResponse.body();
        }
        throw new UnauthorizedException(errorMessage);
    }
    System.out.println("Response headers (after post to google form & following redirect):");
    for (Map.Entry<String, String> header : postResponse.headers().entrySet()) {
        System.out.println(header.getKey() + "," + header.getValue());
    }
    System.out.println("Final response url was: " + postResponse.url().toString());
    String[] args = postResponse.url().toString().split("&");
    LoginInfo loginInfo = new LoginInfo();
    for (String arg : args) {
        if (arg.startsWith("access_token")) {
            loginInfo.accessToken = arg.split("=")[1].trim();
        } else if (arg.startsWith("id_token")) {
            loginInfo.idToken = arg.split("=")[1].trim();
        } else if (arg.startsWith("expires_in")) {
            loginInfo.expiry = arg.split("=")[1].trim();
        }
    }

    //Google doesn't actually throw a 401 or anything - it just doesn't redirect
    //and sends you back to it's login page to try again.
    //So this is what happens with an invalid password.
    if (loginInfo.accessToken == null || loginInfo.idToken == null) {
        //Document oauthPostResponse = postResponse.parse();
        //System.out.println("*** Oauth response from google *** ");
        //System.out.println(oauthPostResponse.toString());
        throw new UnauthorizedException(
                "Error retrieving authorization: did you use the correct username/password?");
    }
    String[] idTokenFields = loginInfo.idToken.split("\\.");
    if (idTokenFields.length < 3) {
        throw new AuthorizationException("Error parsing id token " + loginInfo.idToken + "\n" + "it only had "
                + idTokenFields.length + " field!");
    }
    String jwtBody = new String(Base64.decodeBase64(idTokenFields[1]), StandardCharsets.UTF_8);
    loginInfo.idTokenBody = new Gson().fromJson(jwtBody, OauthJwt.class);
    loginInfo.id = loginInfo.idTokenBody.sub;
    return loginInfo;
}

From source file:piecework.util.FormUtility.java

public static void addCrossOriginHeaders(UserInterfaceSettings settings, Response.ResponseBuilder builder,
        ModelProvider deploymentProvider, Object entity, boolean isAnonymous, String... methods)
        throws PieceworkException {
    String methodHeader = null;/* w ww.j ava2 s .  c  om*/

    if (entity != null && methods != null && methods.length > 0)
        methodHeader = StringUtils.join(methods, ",");

    // Never allow CORS for anonymous resources
    if (!isAnonymous) {

        URI remoteHost = remoteHost(settings, deploymentProvider);

        if (remoteHost != null) {
            String hostUri = remoteHost.toString();
            if (LOG.isDebugEnabled())
                LOG.debug("Setting Access-Control-Allow-Origin to " + hostUri);
            builder.header("Access-Control-Allow-Origin", hostUri);
            builder.header("Access-Control-Allow-Credentials", "true");
            // For file upload
            builder.header("Access-Control-Allow-Headers",
                    "Accept, Content-Type, Content-Range, Content-Disposition, Content-Description");
            if (StringUtils.isNotEmpty(methodHeader))
                builder.header("Access-Control-Allow-Methods", methodHeader);
        }
    }

    if (StringUtils.isNotEmpty(methodHeader))
        builder.header("Allow", methodHeader);
}

From source file:fedora.server.security.servletfilters.xmluserfile.FedoraUsers.java

public static FedoraUsers getInstance(URI fedoraUsersXML) {
    FedoraUsers fu = null;/*from w ww .  ja  v  a 2  s  . c om*/
    BeanReader reader = new BeanReader();
    reader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
    reader.getBindingConfiguration().setMapIDs(false);

    try {
        reader.registerMultiMapping(getBetwixtMapping());
        fu = (FedoraUsers) reader.parse(fedoraUsersXML.toString());
    } catch (IntrospectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return fu;
}

From source file:org.openmrs.module.webservices.rest.ITBase.java

@BeforeClass
public static void waitForServerToStart() {
    synchronized (serverStartupLock) {
        if (!serverStarted) {
            final long time = System.currentTimeMillis();
            final int timeout = 300000;
            final int retryAfter = 10000;

            final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(retryAfter)
                    .setConnectTimeout(retryAfter).build();

            final String startupUri = TEST_URL.getScheme() + "://" + TEST_URL.getHost() + ":"
                    + TEST_URL.getPort() + TEST_URL.getPath();
            System.out.println(//from  w  ww.j av a 2 s  . c  o m
                    "Waiting for server at " + startupUri + " for " + timeout / 1000 + " more seconds...");

            while (System.currentTimeMillis() - time < timeout) {
                try {
                    final HttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build();
                    final HttpGet sessionGet = new HttpGet(startupUri);
                    sessionGet.setConfig(requestConfig);
                    final HttpClientContext context = HttpClientContext.create();
                    final HttpResponse response = client.execute(sessionGet, context);

                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 400) {
                        throw new RuntimeException(status + " " + response.getStatusLine().getReasonPhrase());
                    }

                    URI finalUri = sessionGet.getURI();
                    List<URI> redirectLocations = context.getRedirectLocations();
                    if (redirectLocations != null) {
                        finalUri = redirectLocations.get(redirectLocations.size() - 1);
                    }

                    String finalUriString = finalUri.toString();
                    if (!finalUriString.contains("initialsetup")) {
                        serverStarted = true;
                        return;
                    }
                } catch (IOException e) {
                    System.out.println(e.toString());
                }

                try {
                    System.out.println("Waiting for " + (timeout - (System.currentTimeMillis() - time)) / 1000
                            + " more seconds...");
                    Thread.sleep(retryAfter);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            throw new RuntimeException("Server startup took longer than 5 minutes!");
        }
    }
}