Example usage for java.net URL getQuery

List of usage examples for java.net URL getQuery

Introduction

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

Prototype

public String getQuery() 

Source Link

Document

Gets the query part of this URL .

Usage

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.AuthorizationProcessManager.java

/**
 * Extract grant code from url string//from  w w  w.  jav a  2  s  . c om
 * @param urlString url that contain the grant code
 * @return grant code
 * @throws MalformedURLException in case of illegal url format
 */
private String extractGrantCode(String urlString) throws MalformedURLException {

    URL url = new URL(urlString);
    String code = Utils.getParameterValueFromQuery(url.getQuery(), "code");

    if (code == null) {
        throw new RuntimeException("Failed to extract grant code from url");
    }

    logger.debug("Grant code extracted successfully");
    return code;
}

From source file:org.wso2.identity.integration.test.saml.SAMLInvalidIssuerTestCase.java

@BeforeClass(alwaysRun = true)
public void testInit() throws Exception {
    super.init();

    ConfigurationContext configContext = ConfigurationContextFactory
            .createConfigurationContextFromFileSystem(null, null);
    applicationManagementServiceClient = new ApplicationManagementServiceClient(sessionCookie, backendURL,
            configContext);/* w  w  w  .  java 2  s  .c  om*/
    remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie);

    isSAMLReturned = false;

    httpClient = new DefaultHttpClient();
    httpClient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {

            if (response == null) {
                throw new IllegalArgumentException("HTTP Response should not be null");
            }
            //get the location header to find out where to redirect to
            Header locationHeader = response.getFirstHeader("Location");
            if (locationHeader == null) {
                // got a redirect resp, but no location header
                throw new ProtocolException(
                        "Received redirect resp " + response.getStatusLine() + " but no location header");
            }

            URL url = null;
            try {
                url = new URL(locationHeader.getValue());
                if (SAML_ERROR_NOTIFICATION_PATH.equals(url.getPath())
                        && url.getQuery().contains("SAMLResponse")) {
                    isSAMLReturned = true;
                }
            } catch (MalformedURLException e) {
                throw new ProtocolException("Invalid redirect URI: " + locationHeader.getValue(), e);
            }

            return super.getLocationURI(response, context);
        }
    });

    createUser();
    createApplication();

    //Starting tomcat
    log.info("Starting Tomcat");
    tomcatServer = getTomcat();

    //TODO: Uncomment below once the tomcat dependency issue is resolved
    //        URL resourceUrl = getClass()
    //                .getResource(File.separator + "samples" + File.separator + "org.wso2.sample.is .sso.agent.war");
    URL resourceUrl = getClass()
            .getResource(File.separator + "samples" + File.separator + "travelocity.com.war");
    startTomcat(tomcatServer, "/travelocity.com", resourceUrl.getPath());

}

From source file:org.keycloak.testsuite.oauth.OAuthRedirectUriTest.java

@Test
public void testValid() throws IOException {
    oauth.redirectUri(APP_ROOT + "/auth");
    OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");

    Assert.assertNotNull(response.getCode());
    URL url = new URL(driver.getCurrentUrl());
    Assert.assertTrue(url.toString().startsWith(APP_ROOT));
    Assert.assertTrue(url.getQuery().contains("code="));
    Assert.assertTrue(url.getQuery().contains("state="));
}

From source file:org.keycloak.testsuite.oauth.OAuthRedirectUriTest.java

@Test
public void testWithParams() throws IOException {
    oauth.redirectUri(APP_ROOT + "/auth?key=value");
    OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");

    Assert.assertNotNull(response.getCode());
    URL url = new URL(driver.getCurrentUrl());
    Assert.assertTrue(url.toString().startsWith(APP_ROOT));
    Assert.assertTrue(url.getQuery().contains("key=value"));
    Assert.assertTrue(url.getQuery().contains("state="));
    Assert.assertTrue(url.getQuery().contains("code="));
}

From source file:org.fao.geonet.utils.AbstractHttpRequest.java

public void setUrl(URL url) {
    host = url.getHost();//from   w  w  w  .  j  a  va 2  s.  c om
    port = url.getPort();
    protocol = url.getProtocol();
    address = url.getPath();
    query = url.getQuery();
}

From source file:com.cladonia.xngreditor.URLUtilities.java

/**
 * Encrypts the password in this URL.// w  ww .j a  v  a  2 s  . c o m
 * 
 * @param url the url.
 * 
 * @return the encrypted string.
 */
public static String encrypt(URL url) {
    String password = getPassword(url);
    String username = getUsername(url);

    if (password != null) {
        password = StringUtilities.encrypt(password);
    }

    //      System.out.println( "URLUtilities.encrypt( "+url+") ["+password+"]");

    return createURL(url.getProtocol(), username, password, url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef()).toString();
}

From source file:org.springframework.richclient.image.Handler.java

protected URLConnection openConnection(URL url) throws IOException {
    if (!StringUtils.hasText(url.getPath())) {
        throw new MalformedURLException("must provide an image key.");
    } else if (StringUtils.hasText(url.getHost())) {
        throw new MalformedURLException("host part should be empty.");
    } else if (url.getPort() != -1) {
        throw new MalformedURLException("port part should be empty.");
    } else if (StringUtils.hasText(url.getQuery())) {
        throw new MalformedURLException("query part should be empty.");
    } else if (StringUtils.hasText(url.getRef())) {
        throw new MalformedURLException("ref part should be empty.");
    } else if (StringUtils.hasText(url.getUserInfo())) {
        throw new MalformedURLException("user info part should be empty.");
    }/*from w w  w  . j a  v a  2  s  .  c o  m*/
    urlHandlerImageSource.getImage(url.getPath());
    Resource image = urlHandlerImageSource.getImageResource(url.getPath());
    if (image != null)
        return image.getURL().openConnection();

    throw new IOException("null image returned for key [" + url.getFile() + "].");
}

From source file:com.squid.kraken.v4.auth.OAuth2LoginServlet.java

/**
 * Perform the login action via API calls.
 *
 * @param request/* w  w w. j  av a  2  s.com*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void login(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    String responseType = request.getParameter(RESPONSE_TYPE);
    if (responseType == null) {
        responseType = RESPONSE_TYPE_TOKEN;
    }
    String customerId = request.getParameter(CUSTOMER_ID);

    // create a POST method to execute the login request
    HttpPost post;
    List<NameValuePair> values = new ArrayList<NameValuePair>();
    if (responseType.equals(RESPONSE_TYPE_TOKEN)) {
        post = new HttpPost(privateServerURL + V4_RS_AUTH_TOKEN);
    } else {
        post = new HttpPost(privateServerURL + V4_RS_AUTH_CODE);
    }
    if (StringUtils.isNotBlank(customerId)) {
        values.add(new BasicNameValuePair(CUSTOMER_ID, customerId));
    }
    if (request.getParameter(CLIENT_ID) != null) {
        values.add(new BasicNameValuePair(CLIENT_ID, request.getParameter(CLIENT_ID)));
    }

    // get login and pwd either from the request or from the session
    HttpSession session = request.getSession(false);
    String login = request.getParameter(LOGIN);
    if ((session != null) && (login == null)) {
        login = (String) session.getAttribute(LOGIN);
        session.setAttribute(LOGIN, null);
    }
    String password = request.getParameter(PASSWORD);
    if ((session != null) && (password == null)) {
        password = (String) session.getAttribute(PASSWORD);
        session.setAttribute(PASSWORD, null);
    }

    boolean isSso = false;
    String redirectUri = null;
    if (request.getParameter(REDIRECT_URI) != null) {
        redirectUri = request.getParameter(REDIRECT_URI).trim();
        values.add(new BasicNameValuePair(REDIRECT_URI, redirectUri));
        isSso = isSso(request, redirectUri);
    }

    if (isSso == false && ((login == null) || (password == null))) {
        showLogin(request, response);
    } else {
        if (isSso == false) {
            values.add(new BasicNameValuePair(LOGIN, login));
            values.add(new BasicNameValuePair(PASSWORD, password));
        } else {
            String uri = request.getScheme() + "://" + request.getServerName()
                    + ("http".equals(request.getScheme()) && request.getServerPort() == 80
                            || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? ""
                                    : ":" + request.getServerPort());
            post = new HttpPost(uri + V4_RS_SSO_TOKEN);
            if (values != null) {
                URL url = new URL(redirectUri);
                values = getQueryPairs(getRedirectParameters(url.getQuery()));
            }
        }
        post.setEntity(new UrlEncodedFormEntity(values));
        try {
            String redirectUrl = redirectUri;
            // T489 remove any trailing #
            if (redirectUrl.endsWith("#")) {
                redirectUrl = redirectUrl.substring(0, redirectUrl.length() - 1);
            }
            if (responseType.equals(RESPONSE_TYPE_TOKEN)) {
                // token type
                // execute the login request
                AccessToken token = RequestHelper.processRequest(AccessToken.class, request, post);
                String tokenId = token.getId().getTokenId();
                // redirect URL
                if (redirectUrl.contains(ACCESS_TOKEN_PARAM_PATTERN)) {
                    // replace access_token parameter pattern
                    redirectUrl = StringUtils.replace(redirectUrl, ACCESS_TOKEN_PARAM_PATTERN, tokenId);
                } else {
                    // append access_token anchor
                    redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&";
                    redirectUrl += ACCESS_TOKEN + "=" + tokenId;
                }
            } else {
                // auth code type
                // execute the login request
                AuthCode codeObj = RequestHelper.processRequest(AuthCode.class, request, post);
                String code = codeObj.getCode();
                if (redirectUrl.contains(AUTH_CODE_PARAM_PATTERN)) {
                    // replace code parameter pattern
                    redirectUrl = StringUtils.replace(redirectUrl, AUTH_CODE_PARAM_PATTERN, code);
                } else {
                    // append code param
                    redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&";
                    redirectUrl += AUTH_CODE + "=" + code;
                }
            }
            response.sendRedirect(redirectUrl);
        } catch (ServerUnavailableException e1) {
            // Authentication server unavailable
            logger.error(e1.getLocalizedMessage());
            request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE);
            showLogin(request, response);
            return;
        } catch (ServiceException e2) {
            WebServicesException exception = e2.getWsException();
            if (exception != null) {
                if (exception.getCustomers() != null) {
                    // multiple customers found
                    request.setAttribute(DUPLICATE_USER_ERROR, Boolean.TRUE);
                    request.setAttribute(CUSTOMERS_LIST, exception.getCustomers());
                    // save the credentials for later use
                    request.getSession().setAttribute(LOGIN, login);
                    request.getSession().setAttribute(PASSWORD, password);
                } else {
                    String errorMessage = exception.getError();
                    if (!errorMessage.contains("Password")) {
                        request.setAttribute(ERROR, exception.getError());
                    } else {
                        request.setAttribute(ERROR, Boolean.TRUE);
                    }
                }
            } else {
                request.setAttribute(ERROR, Boolean.TRUE);
            }
            // forward to login page
            showLogin(request, response);
            return;
        } catch (SSORedirectException error) {
            response.sendRedirect(error.getRedirectURL());
        }

    }
}

From source file:org.sakaiproject.shortenedurl.impl.RandomisedUrlService.java

/**
 * Encodes a full URL.//from w  ww  . j av a  2 s . co  m
 * 
 * @param rawUrl the URL to encode.
 */
private String encodeUrl(String rawUrl) {
    if (StringUtils.isBlank(rawUrl)) {
        return null;
    }
    String encodedUrl = null;

    try {
        URL url = new URL(rawUrl);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        encodedUrl = uri.toASCIIString();
    } catch (Exception e) {
        log.warn("encoding url: " + rawUrl + ", " + e.getMessage(), e);
    }

    return encodedUrl;
}

From source file:org.apache.ode.axis2.Axis2TestBase.java

public String sendRequestFile(String endpoint, String filename) {
    try {//  ww w. j  a  va2s.c  o m
        URL url = new URL(endpoint);
        // override the port if necessary but only if the given port is the default one
        if (url.getPort() == DEFAULT_TEST_PORT_0 && url.getPort() != getTestPort(0)) {
            url = new URL(url.getProtocol() + "://" + url.getHost() + ":" + getTestPort(0) + url.getPath()
                    + (url.getQuery() != null ? "?" + url.getQuery() : ""));
        }
        return HttpSoapSender.doSend(url, new FileInputStream(server.getResource(filename)), null, 0, null,
                null, null);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}