List of usage examples for javax.servlet.http HttpServletRequest getQueryString
public String getQueryString();
From source file:com.meltmedia.cadmium.servlets.jersey.StatusService.java
@GET @Path("/health") @Produces("text/plain") public String health(@Context HttpServletRequest request) { StringBuilder builder = new StringBuilder(); builder.append("Server: " + request.getServerName() + "\n"); builder.append("Scheme: " + request.getScheme() + "\n"); builder.append("Port: " + request.getServerPort() + "\n"); builder.append("ContextPath: " + request.getContextPath() + "\n"); builder.append("ServletPath: " + request.getServletPath() + "\n"); builder.append("Uri: " + request.getRequestURI() + "\n"); builder.append("Query: " + request.getQueryString() + "\n"); Enumeration<?> headerNames = request.getHeaderNames(); builder.append("Headers:\n"); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); Enumeration<?> headers = request.getHeaders(name); builder.append(" '" + name + "':\n"); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); builder.append(" -" + headerValue + "\n"); }//from ww w . j a v a 2s . c om } if (request.getCookies() != null) { builder.append("Cookies:\n"); for (Cookie cookie : request.getCookies()) { builder.append(" '" + cookie.getName() + "':\n"); builder.append(" value: " + cookie.getValue() + "\n"); builder.append(" domain: " + cookie.getDomain() + "\n"); builder.append(" path: " + cookie.getPath() + "\n"); builder.append(" maxAge: " + cookie.getMaxAge() + "\n"); builder.append(" version: " + cookie.getVersion() + "\n"); builder.append(" comment: " + cookie.getComment() + "\n"); builder.append(" secure: " + cookie.getSecure() + "\n"); } } return builder.toString(); }
From source file:org.gnode.wda.server.ProxyServlet.java
License:asdf
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Create new client to perform the proxied request HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); uri.append(targetServer);/*from w ww . j a v a 2 s .c om*/ // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method. // Turns "/proxy/asdf" into "/asdf" uri.append(req.getRequestURI().substring(6)); // Add any supplied query strings String queryString = req.getQueryString(); if (queryString != null) { uri.append("?" + queryString); } // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); String headerValue = req.getHeader(headerName); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) { // System.out.println(headerName.toLowerCase() + ": " + headerValue); request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); if (entity == null) return; InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); int b = input.read(); while (b != -1) { output.write(b); b = input.read(); } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:com.eviware.soapui.mockaswar.MockAsWarServlet.java
public void printDetail(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html"); PrintWriter out = response.getWriter(); startHtmlPage(out, "MockService Detail", null); int id = 0;// w ww . j a va2 s . c o m try { id = Integer.parseInt(request.getQueryString()); } catch (NumberFormatException e) { } if (id > 0) { for (MockResult result : results) { if (result.hashCode() == id) { id = 0; printResult(out, result); } } } if (id > 0) { out.print("<p>Missing specified MockResult</p>"); } out.print("</body></html>"); out.flush(); }
From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java
private void executeRemoteRequest(RequestMethod method, URI uri, HttpServletRequest req, HttpServletResponse rsp) throws IOException { if (logger.isDebugEnabled()) { logger.debug("executeRemoteRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]" + " redirected to " + uri.toASCIIString()); }/* ww w . j av a2 s .co m*/ HttpRequestBase request = resolveRequest(method, uri); executeRemoteRequest(request, req, rsp); }
From source file:com.sun.identity.saml2.plugins.SAML2IDPProxyFRImpl.java
private String buildReturnURL(String requestID, HttpServletRequest request) { String methodName = "buildReturnURL"; StringBuffer sb = new StringBuffer(); String baseURL = request.getScheme() + "://" + request.getHeader("host") + request.getRequestURI(); String qs = request.getQueryString(); if (qs != null && !qs.isEmpty()) { baseURL = baseURL + "?" + qs; }//from w ww . j a v a 2 s .c om StringBuffer retURL = new StringBuffer().append(baseURL); if (retURL.toString().indexOf("?") == -1) { retURL.append("?"); } else { retURL.append("&"); } retURL.append("requestID=").append(requestID); sb.append(retURL); String returnURL = sb.toString(); debugMessage(methodName, " ReturnURL is: " + returnURL); return returnURL; }
From source file:org.oncoblocks.centromere.web.controller.AbstractApiController.java
/** * Queries the repository using inputted query string paramters, defined within a annotated * {@link Model} classes. Supports hypermedia, pagination, sorting, field * filtering, and field exclusion./* ww w . j a va 2 s . c o m*/ * * @param pagedResourcesAssembler {@link PagedResourcesAssembler} * @param request {@link HttpServletRequest} * @return */ @RequestMapping(value = "", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, ApiMediaTypes.APPLICATION_HAL_JSON_VALUE, ApiMediaTypes.APPLICATION_HAL_XML_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_PLAIN_VALUE }) public HttpEntity<?> find(@PageableDefault(size = 1000) Pageable pageable, PagedResourcesAssembler<T> pagedResourcesAssembler, HttpServletRequest request) { ResponseEnvelope envelope; Set<String> fields = RequestUtils.getFilteredFieldsFromRequest(request); Set<String> exclude = RequestUtils.getExcludedFieldsFromRequest(request); pageable = RequestUtils.remapPageable(pageable, model); Map<String, String[]> parameterMap = request.getParameterMap(); List<QueryCriteria> criterias = RequestUtils.getQueryCriteriaFromRequest(model, request); String mediaType = request.getHeader("Accept"); Link selfLink = new Link(linkTo(this.getClass()).slash("").toString() + (request.getQueryString() != null ? "?" + request.getQueryString() : ""), "self"); if (parameterMap.containsKey("page") || parameterMap.containsKey("size")) { Page<T> page = repository.find(criterias, pageable); if (ApiMediaTypes.isHalMediaType(mediaType)) { PagedResources<FilterableResource> pagedResources = pagedResourcesAssembler.toResource(page, assembler, selfLink); envelope = new ResponseEnvelope(pagedResources, fields, exclude); } else { envelope = new ResponseEnvelope(page, fields, exclude); } } else { Sort sort = pageable.getSort(); List<T> entities = null; if (sort != null) { entities = (List<T>) repository.find(criterias, sort); } else { entities = (List<T>) repository.find(criterias); } if (ApiMediaTypes.isHalMediaType(mediaType)) { List<FilterableResource> resourceList = assembler.toResources(entities); Resources<FilterableResource> resources = new Resources<>(resourceList); resources.add(selfLink); envelope = new ResponseEnvelope(resources, fields, exclude); } else { envelope = new ResponseEnvelope(entities, fields, exclude); } } return new ResponseEntity<>(envelope, HttpStatus.OK); }
From source file:com.pliu.azuremgmtsdk.BasicFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try {/*from ww w .j a v a 2 s. co m*/ String subscriptionId = httpRequest.getParameter("subscriptionId"); if (subscriptionId != null) httpRequest.getSession().setAttribute("subscriptionId", subscriptionId); String currentUri = httpRequest.getRequestURL().toString(); String queryStr = httpRequest.getQueryString(); String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : ""); // check if user has a AuthData in the session if (!AuthHelper.isAuthenticated(httpRequest)) { if (AuthHelper.containsAuthenticationData(httpRequest)) { processAuthenticationData(httpRequest, currentUri, fullUrl); } else { // not authenticated // we can get the tenant id for the subscription first getTenantIdForSubscription(httpRequest); // then authenticate sendAuthRedirect(httpRequest, httpResponse); return; } } if (isAuthDataExpired(httpRequest)) { updateAuthDataUsingRefreshToken(httpRequest); } } catch (AuthenticationException authException) { // something went wrong (like expiration or revocation of token) // we should invalidate AuthData stored in session and redirect to Authorization server removePrincipalFromSession(httpRequest); sendAuthRedirect(httpRequest, httpResponse); return; } catch (Throwable exc) { httpResponse.setStatus(500); request.setAttribute("error", exc.getMessage()); request.getRequestDispatcher("/error.jsp").forward(request, response); } } chain.doFilter(request, response); }
From source file:it.cnr.icar.eric.server.interfaces.soap.RegistryBSTServlet.java
@SuppressWarnings("unused") public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); String requestUri = req.getRequestURI(); String servletPath = req.getServletPath(); String scheme = req.getScheme(); String serverName = req.getServerName(); String queryString = req.getQueryString(); String ericName = RegistryProperties.getInstance().getProperty("eric.name", "eric"); int serverPort = req.getServerPort(); StringBuffer sb = new StringBuffer(); sb.append(scheme).append("://").append(serverName).append(':'); sb.append(serverPort);//w w w. j a v a 2s . com sb.append('/'); sb.append(ericName); sb.append("/registry/thin/browser.jsp"); String url = sb.toString(); PrintWriter wt = resp.getWriter(); wt.println(ServerResourceBundle.getInstance().getString("message.urlForSOAP")); wt.println(ServerResourceBundle.getInstance().getString("message.urlForWebAccess", new Object[] { url })); wt.flush(); wt.close(); }
From source file:it.geosolutions.httpproxy.service.impl.ProxyHelperImpl.java
/** * Prepare a proxy method execution/*from w w w .jav a2 s .c o m*/ * * @param httpServletRequest * @param httpServletResponse * @param proxy * * @return ProxyMethodConfig to execute the method * * @throws IOException * @throws ServletException */ public ProxyMethodConfig prepareProxyMethod(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, ProxyService proxy) throws IOException, ServletException { URL url = null; String user = null, password = null; Map<?, ?> pars; String method = httpServletRequest.getMethod(); if (HttpMethods.METHOD_GET.equals(method)) { // Obtain pars from parameter map pars = httpServletRequest.getParameterMap(); } else { //Parse the queryString to not read the request body calling getParameter from httpServletRequest // so the method can simply forward the request body pars = splitQuery(httpServletRequest.getQueryString()); } // Obtain ProxyMethodConfig from pars for (Object key : pars.keySet()) { String value = (pars.get(key) instanceof String) ? (String) pars.get(key) : ((String[]) pars.get(key))[0]; if ("user".equals(key)) { user = value; } else if ("password".equals(key)) { password = value; } else if ("url".equals(key)) { url = new URL(value); } } // get url from the attribute if present if (url == null) { String urlString = (String) httpServletRequest.getAttribute("url"); if (urlString != null) url = new URL(urlString); } if (url != null) { // init and return the config proxy.onInit(httpServletRequest, httpServletResponse, url); return new ProxyMethodConfig(url, user, password, method); } else { return null; } }