Example usage for java.net URI getQuery

List of usage examples for java.net URI getQuery

Introduction

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

Prototype

public String getQuery() 

Source Link

Document

Returns the decoded query component of this URI.

Usage

From source file:com.microsoft.tfs.client.common.ui.dialogs.connect.ACSCredentialsDialogD11.java

private ACSConfigurationResult configureAuthenticationFromAuthProvider(final String target,
        final NameValuePair[] formInput) throws Exception {
    final URI targetURI;

    try {/*from  w  w w.  j a v  a  2s .co m*/
        targetURI = new URI(target);
    } catch (final Exception e) {
        log.warn(MessageFormat.format("ACS form action is not parseable: {0}", target), e); //$NON-NLS-1$
        throw new Exception("ACS form action is not parseable"); //$NON-NLS-1$
    }

    /* Make sure we're posting back to ACS */
    if (!ACS_SCHEME.equalsIgnoreCase(targetURI.getScheme()) || targetURI.getHost() == null
            || !targetURI.getHost().toLowerCase().endsWith(ACS_DOMAIN)
            || !ACS_PATH.equalsIgnoreCase(targetURI.getPath())
            || !ACS_QUERY.equalsIgnoreCase(targetURI.getQuery())) {
        throw new Exception(MessageFormat.format("ACS form location is not in the domain: {0}", ACS_DOMAIN)); //$NON-NLS-1$
    }

    /*
     * Build a connection to the server to submit the form.
     */
    final HttpClient httpClient = getHttpClient();
    final PostMethod postMethod = new PostMethod(target);

    /*
     * Ignore cookies, do not follow redirects, do not do authentication. We
     * expect the resultant page (and only the resultant page) to populate
     * our cookies.
     */
    postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    postMethod.setFollowRedirects(false);
    postMethod.setDoAuthentication(false);
    postMethod.getParams().setContentCharset("UTF-8"); //$NON-NLS-1$

    /* Add the ACS form elements */
    for (int i = 0; i < formInput.length; i++) {
        postMethod.addParameter(formInput[i]);
    }

    final int status = httpClient.executeMethod(postMethod);

    if (status != HttpStatus.SC_OK) {
        final String message = MessageFormat.format("ACS authentication did not return success: {0}", //$NON-NLS-1$
                Integer.toString(status));
        throw new Exception(message);
    }

    final SAXParser acsResultParser = SAXUtils.newSAXParser();
    final ACSResultHandler acsResultHandler = new ACSResultHandler();
    acsResultParser.parse(postMethod.getResponseBodyAsStream(), acsResultHandler);

    final String finalTarget = acsResultHandler.getFormAction();
    final NameValuePair[] finalParameters = acsResultHandler.getFormInputs();

    return configureAuthenticationFromACS(finalTarget, finalParameters);
}

From source file:org.soyatec.windowsazure.internal.MessageCanonicalizer2.java

/**
 * Create the canonicalized resource with the url address and resourceUriComponents.
 * @param address//  ww  w.j  a  v a 2s  .  co m
 *          The uri address of the HTTP request.
 * @param uriComponents
 *          Components of the Uri extracted out of the request.
 * @return canonicalized resource
 */
private static String getCanonicalizedResource(URI address, ResourceUriComponents uriComponents) {
    //      Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
    //      Append the resource's encoded URI path, without any query parameters.
    //      Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
    //      Convert all parameter names to lowercase.
    //      Sort the query parameters lexicographically by parameter name, in ascending order.
    //      URL-decode each query parameter name and value.
    //      Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
    //      parameter-name:parameter-value
    //      If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
    //      parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
    //      Append a new line character (\n) after each name-value pair. 

    //      Get Container Metadata
    //         GET http://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=metadata 
    //      CanonicalizedResource:
    //          /myaccount/mycontainer\ncomp:metadata\nrestype:container
    //
    //      List Blobs operation:
    //          GET http://myaccount.blob.core.windows.net/container?restype=container&comp=list&include=snapshots&include=metadata&include=uncommittedblobs
    //      CanonicalizedResource:
    //          /myaccount/mycontainer\ncomp:list\ninclude:metadata,snapshots,uncommittedblobs\nrestype:container

    StringBuilder canonicalizedResource = new StringBuilder(ConstChars.Slash);
    canonicalizedResource.append(uriComponents.getAccountName());

    // Note that AbsolutePath starts with a '/'.

    String path = address.getRawPath();
    //      path = path.replaceAll(" ", "%20");
    //      path = java.net.URLEncoder.encode(path);
    canonicalizedResource.append(path);

    NameValueCollection query = HttpUtilities.parseQueryString(address.getQuery());

    ArrayList<String> paramNames = new ArrayList<String>();
    paramNames.addAll(query.keySet());
    Collections.sort(paramNames, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });

    for (String key : paramNames) {
        StringBuilder canonicalizedElement = new StringBuilder(URLDecoder.decode(key));
        canonicalizedElement.append(ConstChars.Colon);
        String value = query.getMultipleValuesAsString(key);
        canonicalizedElement.append(URLDecoder.decode(value));

        canonicalizedResource.append(ConstChars.Linefeed);
        canonicalizedResource.append(canonicalizedElement.toString());
    }

    return canonicalizedResource.toString();
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

public String registerConnectionAsApp(String oAutRedirectUrl)
        throws ConnectionException, IOException, URISyntaxException {
    URI oAutRedirectUri = new URI(oAutRedirectUrl);

    Map<String, String> queryParameters = new LinkedHashMap<String, String>();
    String query = oAutRedirectUri.getQuery();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        queryParameters.put(URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()),
                URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name()));
    }//from  w  ww.j  a  va  2 s  .c  o m
    String accessToken = queryParameters.get("openid.oa2.access_token");

    Map<String, String> cookieMap = new HashMap<String, String>();

    List<JsonWebSiteCookie> webSiteCookies = new ArrayList<JsonWebSiteCookie>();
    for (HttpCookie cookie : getSessionCookies("https://www.amazon.com")) {
        cookieMap.put(cookie.getName(), cookie.getValue());
        webSiteCookies.add(new JsonWebSiteCookie(cookie.getName(), cookie.getValue()));
    }

    JsonWebSiteCookie[] webSiteCookiesArray = new JsonWebSiteCookie[webSiteCookies.size()];
    webSiteCookiesArray = webSiteCookies.toArray(webSiteCookiesArray);

    JsonRegisterAppRequest registerAppRequest = new JsonRegisterAppRequest(serial, accessToken, frc,
            webSiteCookiesArray);
    String registerAppRequestJson = gson.toJson(registerAppRequest);

    HashMap<String, String> registerHeaders = new HashMap<String, String>();
    registerHeaders.put("x-amzn-identity-auth-domain", "api.amazon.com");

    String registerAppResultJson = makeRequestAndReturnString("POST", "https://api.amazon.com/auth/register",
            registerAppRequestJson, true, registerHeaders);
    JsonRegisterAppResponse registerAppResponse = parseJson(registerAppResultJson,
            JsonRegisterAppResponse.class);

    Response response = registerAppResponse.response;
    if (response == null) {
        throw new ConnectionException("Error: No response received from register application");
    }
    Success success = response.success;
    if (success == null) {
        throw new ConnectionException("Error: No success received from register application");
    }

    Tokens tokens = success.tokens;
    if (tokens == null) {
        throw new ConnectionException("Error: No tokens received from register application");
    }
    Bearer bearer = tokens.bearer;
    if (bearer == null) {
        throw new ConnectionException("Error: No bearer received from register application");
    }
    this.refreshToken = bearer.refresh_token;
    if (StringUtils.isEmpty(this.refreshToken)) {
        throw new ConnectionException("Error: No refresh token received");
    }
    String usersMeResponseJson = makeRequestAndReturnString("GET",
            "https://alexa.amazon.com/api/users/me?platform=ios&version=2.2.223830.0", null, false, null);
    JsonUsersMeResponse usersMeResponse = parseJson(usersMeResponseJson, JsonUsersMeResponse.class);

    URI uri = new URI(usersMeResponse.marketPlaceDomainName);
    String host = uri.getHost();
    setAmazonSite(host);
    try {
        exhangeToken();
    } catch (Exception e) {
        logout();
        throw e;
    }
    String deviceName = null;
    Extensions extensions = success.extensions;
    if (extensions != null) {
        DeviceInfo deviceInfo = extensions.device_info;
        if (deviceInfo != null) {
            deviceName = deviceInfo.device_name;
        }
    }
    if (deviceName == null) {
        deviceName = "Unknown";
    }
    this.deviceName = deviceName;
    return deviceName;
}

From source file:com.microsoft.tfs.client.common.ui.dialogs.connect.ACSCredentialsDialogD11.java

private ACSConfigurationResult configureAuthenticationFromCurrentPage(final URI locationURI) throws Exception {
    /*//from   w w  w.j av  a 2  s  .  c  o m
     * Mac OS 10.7.4's Webkit has a bug where it caches post data
     * incorrectly, causing it to resubmit an old form back to ACS. Thus, we
     * need to hijack the form bound for ACS and submit it ourselves,
     * wherein we can process the result and send that to TFS service.
     */
    if (useAuthenticationProviderPage() && ACS_SCHEME.equalsIgnoreCase(locationURI.getScheme())
            && locationURI.getHost() != null && locationURI.getHost().toLowerCase().endsWith(ACS_DOMAIN)
            && ACS_PATH.equalsIgnoreCase(locationURI.getPath())
            && ACS_QUERY.equalsIgnoreCase(locationURI.getQuery())) {
        return configureAuthenticationFromAuthProviderPage();
    }

    /*
     * General case: hijack the post results going to TFS service and we'll
     * submit them ourselves to capture the cookie.
     */
    if (locationURI.getHost().equalsIgnoreCase(serverSigninURL.getHost())
            && locationURI.getPath().equalsIgnoreCase(serverSigninURL.getPath())) {
        final String[] queryPairs = locationURI.getQuery().split("&"); //$NON-NLS-1$

        for (final String pair : queryPairs) {
            final String[] keyValue = pair.split("=", 2); //$NON-NLS-1$
            final String key;
            final String value;

            try {
                key = URLDecoder.decode(keyValue[0], "UTF-8"); //$NON-NLS-1$
                value = URLDecoder.decode(keyValue[1], "UTF-8"); //$NON-NLS-1$
            } catch (final UnsupportedEncodingException e) {
                log.warn("Could not decode location URI query parameters as UTF-8", e); //$NON-NLS-1$
                break;
            }

            /*
             * The "complete=1" param means that auth has completed and we
             * can harvest the cookies from the ACS page.
             */
            if ("complete".equalsIgnoreCase(key) && "1".equals(value)) //$NON-NLS-1$ //$NON-NLS-2$
            {
                return configureAuthenticationFromACSPage();
            }
        }
    }

    /* This page is not helpful, continue processing. */
    return ACSConfigurationResult.CONTINUE;
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

protected void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, IResource res,
        String path) {/*from  ww w . j a  v  a  2s.com*/
    final String sourceMethod = "processRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod,
                new Object[] { req, resp, res, path });
    }
    try {
        URI uri = res.getURI();
        if (path != null && path.length() > 0 && !uri.getPath().endsWith("/")) { //$NON-NLS-1$
            // Make sure we resolve against a folder path
            uri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath() + "/", uri.getQuery(), //$NON-NLS-1$
                    uri.getFragment());
            res = newResource(uri);
        }
        IResource resolved = res.resolve(path);
        if (!resolved.exists()) {
            throw new NotFoundException(resolved.getURI().toString());
        }
        resp.setDateHeader("Last-Modified", resolved.lastModified()); //$NON-NLS-1$
        int expires = getConfig().getExpires();
        resp.addHeader("Cache-Control", //$NON-NLS-1$
                "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        );
        InputStream is = res.resolve(path).getInputStream();
        OutputStream os = resp.getOutputStream();
        CopyUtil.copy(is, os);
    } catch (NotFoundException e) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
        }
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        if (log.isLoggable(Level.WARNING)) {
            log.log(Level.WARNING, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
        }
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }

}

From source file:org.gdms.source.DefaultSourceManager.java

/**
 * Return the DBSource constructed from the provided URI
 * @param uri URI with //from   w w w. j  a  va 2  s.co m
 * @return 
 */
private DBTableSourceDefinition uriToDBDef(URI uri) {
    final String scheme = uri.getScheme().toLowerCase();
    String table = null;
    String sch = null;
    String user = null;
    String password = null;
    boolean ssl = false;
    String dbName = uri.getPath();
    if (dbName.startsWith("/")) {
        dbName = dbName.substring(1);
    }
    String[] params = uri.getQuery().split("&");
    for (int i = 0; i < params.length; i++) {
        String[] vals = params[i].split("=");
        if ("table".equalsIgnoreCase(vals[0])) {
            table = vals[1];
        } else if ("schema".equalsIgnoreCase(vals[0])) {
            sch = vals[1];
        } else if ("user".equalsIgnoreCase(vals[0])) {
            user = vals[1];
        } else if ("password".equalsIgnoreCase(vals[0])) {
            password = vals[1];
        } else if ("ssl".equalsIgnoreCase(vals[0]) && "true".equalsIgnoreCase(vals[1])) {
            ssl = true;
        }
    }
    DBSource s = new DBSource(uri.getHost(), uri.getPort(), dbName, user, password, sch, table,
            "jdbc:" + scheme, ssl);
    return new DBTableSourceDefinition(s);
}

From source file:net.jotel.ws.client.WebSocketClient.java

public void setWebSocketUri(URI uri) throws WebSocketException {
    synchronized (sync) {
        assertIsNotConnected();/*from  w ww  . j ava 2s  . c  o  m*/

        validateWebSocketUri(uri);

        secure = "wss".equalsIgnoreCase(uri.getScheme());
        host = uri.getHost();
        port = uri.getPort();
        if (port == -1) {
            port = secure ? 443 : 80;
        }

        resourceName = uri.getPath();
        if (StringUtils.isBlank(resourceName)) {
            resourceName = "/";
        }

        String query = uri.getQuery();
        if (query != null) {
            resourceName = resourceName + "?" + query;
        }

        origin = (secure ? "https" : "http") + "://" + host;
    }
}

From source file:org.apache.synapse.transport.nhttp.ClientHandler.java

private void setHeaders(HttpContext context, HttpResponse response, MessageContext outMsgCtx,
        MessageContext responseMsgCtx) {
    Header[] headers = response.getAllHeaders();
    if (headers != null && headers.length > 0) {

        Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }//from   w ww.  j  av  a 2  s.  c o m
        });
        String endpointURLPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX);

        String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];

            // if this header is already added
            if (headerMap.containsKey(header.getName())) {
                /* this is a multi-value header */
                // generate the key
                String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
                // get the old value
                String oldValue = headerMap.get(header.getName());
                // adds additional values to a list in a property of message
                // context
                Map map;
                if (responseMsgCtx.getProperty(key) != null) {
                    map = (Map) responseMsgCtx.getProperty(key);
                    map.put(header.getName(), oldValue);
                } else {
                    map = new MultiValueMap();
                    map.put(header.getName(), oldValue);
                    // set as a property in message context
                    responseMsgCtx.setProperty(key, map);
                }

            }

            if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) {
                // Here, we are changing only the host name and the port of
                // the new URI - value of the Location
                // header.
                // If the new URI is again referring to a resource in the
                // server to which the original request
                // is sent, then replace the hostname and port of the URI
                // with the hostname and port of synapse
                // We are not changing the request url here, only the host
                // name and the port.
                try {
                    URI serviceURI = new URI(servicePrefix);
                    URI endpointURI = new URI(endpointURLPrefix);
                    URI locationURI = new URI(header.getValue());

                    if (locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) {
                        URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(),
                                serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(),
                                locationURI.getQuery(), locationURI.getFragment());
                        headerMap.put(header.getName(), newURI.toString());
                        responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX,
                                outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX));
                    }
                } catch (URISyntaxException e) {
                    log.error(e.getMessage(), e);
                }
            } else {
                headerMap.put(header.getName(), header.getValue());
            }
        }
        responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
    }
}

From source file:org.apache.hadoop.fs.azure.NativeAzureFileSystem.java

/**
 * Puts in the authority of the default file system if it is a WASB file
 * system and the given URI's authority is null.
 * //from w  ww  .  j a v  a  2  s.co m
 * @return The URI with reconstructed authority if necessary and possible.
 */
private static URI reconstructAuthorityIfNeeded(URI uri, Configuration conf) {
    if (null == uri.getAuthority()) {
        // If WASB is the default file system, get the authority from there
        URI defaultUri = FileSystem.getDefaultUri(conf);
        if (defaultUri != null && isWasbScheme(defaultUri.getScheme())) {
            try {
                // Reconstruct the URI with the authority from the default URI.
                return new URI(uri.getScheme(), defaultUri.getAuthority(), uri.getPath(), uri.getQuery(),
                        uri.getFragment());
            } catch (URISyntaxException e) {
                // This should never happen.
                throw new Error("Bad URI construction", e);
            }
        }
    }
    return uri;
}

From source file:vitro.vgw.wsiadapter.TCSWSIAdapter.java

void doRequest(String method, URI uri) {

    Request request = newRequest(method);
    URI reqUri = uri;//w w  w  .j  ava2s  .  c  o  m

    //      if(useCoapProxy) {
    //         System.out.println("Setting proxy for request");
    //         request.setOption(new Option(uri.toString(), OptionNumberRegistry.PROXY_URI));
    //      }

    if (method.equals("OBSERVE")) {
        request.setOption(new Option(0, OptionNumberRegistry.OBSERVE));
    }

    // set request URI
    if (method.equals("DISCOVER")
            && (uri.getPath() == null || uri.getPath().isEmpty() || uri.getPath().equals("/"))) {
        // add discovery resource path to URI
        try {
            reqUri = new URI(uri.getScheme(), uri.getAuthority(), DISCOVERY_RESOURCE, uri.getQuery());

        } catch (URISyntaxException e) {
            System.err.println("Failed to parse URI: " + e.getMessage());
            System.exit(ERR_BAD_URI);
        }

    }

    if (useCoapProxy) {
        System.out.println("Setting proxy for request");
        request.setOption(new Option(reqUri.toString(), OptionNumberRegistry.PROXY_URI));
        //         request.setURI(reqUri);
        // override peer address with proxy address
        EndpointAddress a = new EndpointAddress(proxyUri);
        request.setPeerAddress(a);
    } else {
        System.out.println("No proxy for request");
        request.setURI(reqUri);
    }
    request.setPayload("");
    request.setToken(TokenManager.getInstance().acquireToken());
    System.out.println("Ici???s");

    ResponseHandler respHandler = new ResponseHandler() {

        public void handleResponse(Response response) {
            System.out.println("On arrive ici");
            doHandleResponse(response);
        }
    };
    request.registerResponseHandler(respHandler);
    System.out.println("response handler registered");
    // enable response queue in order to use blocking I/O
    //   request.enableResponseQueue(true);

    //
    request.prettyPrint();

    pendingRequests.add(request);
    System.out.println("request stored");
    // execute request
    try {
        request.execute();
        System.out.println("request executed");
    } catch (UnknownHostException e) {
        System.err.println("Unknown host: " + e.getMessage());
        System.exit(ERR_REQUEST_FAILED);
    } catch (IOException e) {
        System.err.println("Failed to execute request: " + e.getMessage());
        System.exit(ERR_REQUEST_FAILED);
    }
}