Example usage for javax.servlet.http HttpServletRequest getQueryString

List of usage examples for javax.servlet.http HttpServletRequest getQueryString

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getQueryString.

Prototype

public String getQueryString();

Source Link

Document

Returns the query string that is contained in the request URL after the path.

Usage

From source file:com.yoshio3.modules.AzureADServerAuthModule.java

private AuthStatus getAuthResultFromServerAndSetSession(Subject clientSubject, HttpServletRequest httpRequest,
        Map<String, String> params, String currentUri) {
    try {//www. j a  va 2s  .  co m
        String fullUrl = currentUri
                + (httpRequest.getQueryString() != null ? "?" + httpRequest.getQueryString() : "");
        AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params);
        //params ?? error ???????AuthenticationErrorResponse
        // if there is an error key in params, return AuthenticationErrorResponse
        //??? AuthenticationSuccessResponse ?
        // if it was successful, return AuthenticationSuccessResponse

        //??????
        // if authentication was successful
        if (authResponse instanceof AuthenticationSuccessResponse) {
            //???????
            // obtain the result from the response and save it in the session

            AuthenticationSuccessResponse authSuccessResponse = (AuthenticationSuccessResponse) authResponse;
            AuthenticationResult result = getAccessToken(authSuccessResponse.getAuthorizationCode(),
                    currentUri);
            AzureADUserPrincipal userPrincipal = new AzureADUserPrincipal(result);
            setSessionPrincipal(httpRequest, userPrincipal);

            //?
            // set the user principal
            String[] groups = getGroupList(userPrincipal);
            System.out.println(": " + Arrays.toString(groups));
            AzureADCallbackHandler azureCallBackHandler = new AzureADCallbackHandler(clientSubject, httpRequest,
                    userPrincipal);
            loginContext = new LoginContext(LOGIN_CONTEXT_NAME, azureCallBackHandler);
            loginContext.login();
            Subject subject = loginContext.getSubject();

            CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, userPrincipal);
            GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, groups);

            Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
            handler.handle(callbacks);

            return AuthStatus.SUCCESS;
        } else {
            // ?????
            // if authentication failed
            AuthenticationErrorResponse authErrorResponse = (AuthenticationErrorResponse) authResponse;
            CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject,
                    (Principal) null);
            GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, null);

            Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
            handler.handle(callbacks);

            return AuthStatus.FAILURE;
        }
    } catch (Throwable ex) {
        CallerPrincipalCallback callerCallBack = new CallerPrincipalCallback(clientSubject, (Principal) null);
        GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject, null);

        Callback[] callbacks = new Callback[] { callerCallBack, groupPrincipalCallback };
        try {
            handler.handle(callbacks);
        } catch (IOException | UnsupportedCallbackException ex1) {
            LOGGER.log(Level.SEVERE, null, ex1);
        }
        LOGGER.log(Level.SEVERE, null, ex);
        return AuthStatus.FAILURE;
    }
}

From source file:net.riezebos.thoth.servlets.ThothServlet.java

protected void handleForbidden(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (isLoggedIn(request))
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    else {/*  w  ww.j a  va 2  s. c o m*/
        String queryString = request.getQueryString();
        String originalRequest = request.getRequestURI() + (queryString == null ? "" : "?" + queryString);

        HttpSession session = request.getSession(true);
        session.setAttribute(REDIRECT_AFTER_LOGIN, originalRequest);

        String loginRedirect = getRootRedirect(request);
        loginRedirect += "?cmd=" + LoginCommand.TYPE_CODE;
        response.sendRedirect(loginRedirect);
    }
}

From source file:com.eviware.soapui.impl.wsdl.mock.WsdlMockRunner.java

public MockResult dispatchGetRequest(HttpServletRequest request, HttpServletResponse response)
        throws DispatchException {
    try {//from   w w  w  . java  2s.  c  om
        String qs = request.getQueryString();
        if (qs != null && qs.toUpperCase().startsWith("WSDL")) {
            dispatchWsdlRequest(request, response);
        } else {
            if (qs != null && qs.startsWith("cmd=")) {
                dispatchCommand(request.getParameter("cmd"), request, response);
            } else {
                String docroot = PropertyExpander.expandProperties(mockContext, getMockService().getDocroot());
                if (StringUtils.hasContent(docroot)) {
                    try {
                        String pathInfo = request.getPathInfo();
                        if (pathInfo == null)
                            pathInfo = "";

                        if (mockService.getPath().length() > 1 && pathInfo.startsWith(mockService.getPath()))
                            pathInfo = pathInfo.substring(mockService.getPath().length());

                        String filename = docroot + pathInfo.replace('/', File.separatorChar);
                        File file = new File(filename);
                        if (file.exists()) {
                            returnFile(response, file);
                        }
                    } catch (Throwable e) {
                        throw new DispatchException(e);
                    }
                }
            }
        }

        return null;
    } catch (Exception e) {
        throw new DispatchException(e);
    }
}

From source file:com.streamsets.lib.security.http.SSOUserAuthenticator.java

StringBuffer getRequestUrl(HttpServletRequest request, Set<String> queryStringParamsToRemove) {
    StringBuffer requestUrl;//from w w w .j  av  a 2 s  . c o m

    if (this.dpmBaseUrl != null && !isDataCollector) {
        requestUrl = new StringBuffer(this.dpmBaseUrl);
        requestUrl.append(request.getRequestURI());
    } else {
        requestUrl = new StringBuffer(request.getRequestURL());
    }

    String qs = request.getQueryString();
    if (qs != null) {
        String qsSeparator = "?";
        for (String paramArg : Splitter.on("&").split(qs)) {
            String[] paramArgArr = paramArg.split("=", 2);
            if (!queryStringParamsToRemove.contains(paramArgArr[0])) {
                requestUrl.append(qsSeparator).append(paramArg);
                qsSeparator = "&";
            }
        }
    }
    return requestUrl;
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static Map<String, Object> getUrlOnlyParameterMap(HttpServletRequest request) {
    // NOTE: these have already been through canonicalizeParameterMap, so not doing it again here
    Map<String, Object> paramMap = getQueryStringOnlyParameterMap(request.getQueryString());
    paramMap.putAll(getPathInfoOnlyParameterMap(request.getPathInfo(), null, null));
    return paramMap;
}

From source file:org.jetbrains.webdemo.handlers.ServerHandler.java

private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> postParameters) {
    final boolean hasoutbody = (request.getMethod().equals("POST"));

    try {//from  ww w.  j av a2  s . co m
        final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/"
                + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        final Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            final String header = headers.nextElement();
            final Enumeration<String> values = request.getHeaders(header);
            while (values.hasMoreElements()) {
                final String value = values.nextElement();
                conn.addRequestProperty(header, value);
            }
        }

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setUseCaches(false);
        conn.setDoOutput(hasoutbody);

        if (postParameters != null && !postParameters.isEmpty()) {
            conn.setRequestMethod("POST");
            try (OutputStream requestBody = conn.getOutputStream()) {
                boolean first = true;
                for (Map.Entry<String, String> entry : postParameters.entrySet()) {
                    if (entry.getValue() == null)
                        continue;
                    if (first) {
                        first = false;
                    } else {
                        requestBody.write('&');
                    }
                    requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes());
                    requestBody.write('=');
                    requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes());
                }
            }
        } else {
            conn.setRequestMethod("GET");
        }

        StringBuilder responseBody = new StringBuilder();
        if (conn.getResponseCode() >= 400) {
            StringBuilder serverMessage = new StringBuilder();
            try (InputStream errorStream = conn.getErrorStream()) {
                if (errorStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = errorStream.read(buffer);
                        if (read <= 0)
                            break;
                        serverMessage.append(new String(buffer, 0, read));
                    }
                }
            }

            switch (conn.getResponseCode()) {
            case HttpServletResponse.SC_NOT_FOUND:
                responseBody.append("Kotlin compile server not found");
                break;
            case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
                responseBody.append("Kotlin compile server is temporary overloaded");
                break;
            default:
                responseBody = serverMessage;
                break;
            }
        } else {
            try (InputStream inputStream = conn.getInputStream()) {
                if (inputStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = inputStream.read(buffer);
                        if (read <= 0)
                            break;
                        responseBody.append(new String(buffer, 0, read));
                    }
                }
            }
        }
        writeResponse(request, response, responseBody.toString(), conn.getResponseCode());
    } catch (SocketTimeoutException e) {
        writeResponse(request, response, "Compile server connection timeout",
                HttpServletResponse.SC_GATEWAY_TIMEOUT);
    } catch (Exception e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "",
                "Can't forward request to Kotlin compile server");
        writeResponse(request, response, "Can't send your request to Kotlin compile server",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.adito.boot.Util.java

/**
 * Dump all request parameters and some other useful stuff from
 * the request to {@link System#err}/*from   w  w w . j  av  a2 s .c  om*/
 * 
 * @param request request to get parameters from
 */
public static void dumpRequest(HttpServletRequest request) {
    System.err.println("Context Path " + request.getContextPath());
    System.err.println("Path Translated " + request.getPathTranslated());
    System.err.println("Path Info " + request.getPathInfo());
    System.err.println("Query: " + request.getQueryString());
    System.err.println("Request URI: " + request.getRequestURI());
    System.err.println("Request URL: " + request.getRequestURL());
    System.err.println("Is Secure: " + request.isSecure());
    System.err.println("Scheme: " + request.getScheme());
    dumpRequestParameters(request);
    dumpRequestAttributes(request);
    dumpRequestHeaders(request);

}

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from w w  w .  j  a va 2s  .c  om
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test(timeout = TestUtils.SHORT_TIMEOUT)
public void testGetDispatchUrl() throws Exception {
    HttpServletRequest request;
    Dispatch dispatch;/*  w  ww  . ja  va 2s  .  c  o m*/
    String path;
    String query;
    URI uri;

    dispatch = new DefaultDispatch();

    path = "http://test-host:42/test-path";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test-path"));

    path = "http://test-host:42/test,path";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test,path"));

    path = "http://test-host:42/test%2Cpath";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test%2Cpath"));

    path = "http://test-host:42/test%2Cpath";
    query = "test%26name=test%3Dvalue";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(query).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test%2Cpath?test%26name=test%3Dvalue"));

}

From source file:cn.vlabs.duckling.vwb.VWBContext.java

private String getRequestURL(HttpServletRequest request) {
    String url = getBaseURL() + request.getServletPath();

    if (request.getPathInfo() != null)
        url += request.getPathInfo();// w w w.  j ava2 s .c  om

    if (request.getQueryString() != null)
        url = url + "?" + request.getQueryString();
    return url;
}