List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:com.ethercis.vehr.parser.EhrScapeURIParserTest.java
@Test public void testEhrQueryParser() throws ServiceManagerException { // Request request = client.newRequest("http://" + hostname + ":8080/rest/v1/ehr?subjectId=1234&subjectNamespace=ABCDEF"); // request.method(HttpMethod.POST); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRequestURI()).thenReturn("/rest/v1/ehr"); Map<String, String[]> parameters = new HashMap<String, String[]>(); parameters.put("subjectId", new String[] { "1234" }); parameters.put("subjectNamespace", new String[] { "ABCDEF" }); when(request.getParameterMap()).thenReturn(parameters); Map<String, String[]> headers = new HashMap<String, String[]>(); headers.put("Content-Type", new String[] { "application/json" }); when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator())); when(request.getHeader("Content-Type")).thenReturn("application/json"); when(request.getMethod()).thenReturn("POST"); uriParser.parse(request);//w w w. j a v a2 s . c o m assertEquals("POST", uriParser.identifyMethod().toUpperCase()); assertEquals("1234", uriParser.identifyParametersAsProperties().getClientProperty("subjectId").toString()); assertEquals("ABCDEF", uriParser.identifyParametersAsProperties().getClientProperty("subjectNamespace").toString()); ///ehr/{ehrId} retrieve an ehr Status from its id request = mock(HttpServletRequest.class); when(request.getRequestURI()).thenReturn("/rest/v1/ehr/8fd2bea0-9e0e-11e5-8994-feff819cdc9f"); parameters = new HashMap<>(); when(request.getParameterMap()).thenReturn(parameters); headers = new HashMap<>(); headers.put("Content-Type", new String[] { "application/json" }); when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator())); when(request.getHeader("Content-Type")).thenReturn("application/json"); when(request.getMethod()).thenReturn("GET"); uriParser.parse(request); assertEquals("GET", uriParser.identifyMethod().toUpperCase()); assertEquals("rest/v1/ehr/status", uriParser.identifyPath()); assertEquals("8fd2bea0-9e0e-11e5-8994-feff819cdc9f", uriParser.identifyParametersAsProperties().getClientProperty("ehrId").toString()); //Returns a JSON representation of the state of the EHR for a subject Id and namespace (STATUS) request = mock(HttpServletRequest.class); when(request.getRequestURI()).thenReturn("/rest/v1/ehr"); parameters = new HashMap<>(); parameters.put("subjectId", new String[] { "1234" }); parameters.put("subjectNamespace", new String[] { "ABCDEF" }); when(request.getParameterMap()).thenReturn(parameters); headers = new HashMap<>(); headers.put("Content-Type", new String[] { "application/json" }); when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator())); when(request.getHeader("Content-Type")).thenReturn("application/json"); when(request.getMethod()).thenReturn("GET"); uriParser.parse(request); assertEquals("GET", uriParser.identifyMethod().toUpperCase()); assertEquals("rest/v1/ehr/status", uriParser.identifyPath()); assertEquals("1234", uriParser.identifyParametersAsProperties().getClientProperty("subjectId").toString()); assertEquals("ABCDEF", uriParser.identifyParametersAsProperties().getClientProperty("subjectNamespace").toString()); //update the status of an EHR request = mock(HttpServletRequest.class); when(request.getRequestURI()).thenReturn("/rest/v1/ehr/status/8fd2bea0-9e0e-11e5-8994-feff819cdc9f"); parameters = new HashMap<>(); when(request.getParameterMap()).thenReturn(parameters); headers = new HashMap<>(); headers.put("Content-Type", new String[] { "application/json" }); when(request.getHeaderNames()).thenReturn(new IteratorEnumeration<String>(headers.keySet().iterator())); when(request.getHeader("Content-Type")).thenReturn("application/json"); when(request.getMethod()).thenReturn("PUT"); uriParser.parse(request); assertEquals("PUT", uriParser.identifyMethod().toUpperCase()); assertEquals("rest/v1/ehr/status", uriParser.identifyPath()); assertEquals("8fd2bea0-9e0e-11e5-8994-feff819cdc9f", uriParser.identifyParametersAsProperties().getClientProperty("ehrId").toString()); }
From source file:cn.tiup.httpproxy.ProxyServlet.java
/** Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { // Get an Enumeration of all of the header names sent by the client @SuppressWarnings("unchecked") Enumeration<String> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = enumerationOfHeaderNames.nextElement(); copyRequestHeader(servletRequest, proxyRequest, headerName); }//from w ww .j av a 2 s . c om }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request/* w ww . j av a 2s .c o m*/ * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(URL url, HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { this.stringProxyHost = url.getHost(); this.intProxyPort = url.getPort(); this.stringProxyPath = url.getPath(); // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) continue; // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the client Enumeration enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName); while (enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) { stringHeaderValue = getProxyHostAndPort(); } // Skip GZIP Responses if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING) && stringHeaderValue.toLowerCase().contains("gzip")) continue; if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING) && stringHeaderValue.toLowerCase().contains("gzip")) continue; if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING)) continue; Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
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"); }//w w w .j av a 2s.co m } 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:com.zimbra.cs.service.AutoDiscoverServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String userAgent = req.getHeader("User-Agent"); if (userAgent != null && (userAgent.contains("PocketPC") || userAgent.contains("SmartPhone"))) { if (log.isDebugEnabled()) { Enumeration<String> enm = req.getHeaderNames(); while (enm.hasMoreElements()) { String header = enm.nextElement(); log.debug("GET header: %s", header + ":" + req.getHeader(header)); }/* w ww . j av a 2 s . c om*/ } if (req.isSecure()) { Account acct = authenticate(req, resp, NS_MOBILE); if (acct == null) { return; } } else { resp.sendRedirect(LC.zimbra_activesync_autodiscover_url.value()); } } }
From source file:org.mule.transport.servlet.MockHttpServletRequestBuilder.java
private void addHeaderExpectations(HttpServletRequest mockRequest) { Enumeration<String> nameEnum = null; if (headers != null) { nameEnum = keyEnumeration(headers); for (Map.Entry<String, Object> entry : headers.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); Enumeration<String> valueAsEnumeration = null; if (value instanceof Enumeration) { valueAsEnumeration = (Enumeration<String>) value; } else { valueAsEnumeration = new SingleElementEnumeration((String) value); }/*from w ww. java 2s .co m*/ when(mockRequest.getHeaders(eq(key))).thenReturn(valueAsEnumeration); } } when(mockRequest.getHeaderNames()).thenReturn(nameEnum); }
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
/** * Copy request headers from the servlet client to the proxy request. * * @param servletRequest/*w w w . j a v a 2 s .c om*/ * @param proxyRequest */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { continue; } if (hopByHopHeaders.containsHeader(headerName)) { continue; } Enumeration headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { HttpHost host = getTargetHost(servletRequest); if (host != null) { headerValue = host.getHostName(); if (host.getPort() != -1) { headerValue += ":" + host.getPort(); } } } else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { headerValue = getRealCookie(headerValue); } proxyRequest.addHeader(headerName, headerValue); } } }
From source file:com.github.restdriver.clientdriver.HttpRealRequest.java
public HttpRealRequest(HttpServletRequest request) { this.path = request.getPathInfo(); this.method = Method.custom(request.getMethod().toUpperCase()); this.params = HashMultimap.create(); if (request.getQueryString() != null) { MultiMap<String> parameterMap = new MultiMap<String>(); UrlEncoded.decodeTo(request.getQueryString(), parameterMap, "UTF-8", 0); for (Entry<String, String[]> paramEntry : parameterMap.toStringArrayMap().entrySet()) { String[] values = paramEntry.getValue(); for (String value : values) { this.params.put(paramEntry.getKey(), value); }/*from w w w. j av a2s .co m*/ } } headers = new HashMap<String, Object>(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); headers.put(headerName.toLowerCase(), request.getHeader(headerName)); } } try { this.bodyContent = IOUtils.toByteArray(request.getInputStream()); } catch (IOException e) { throw new RuntimeException("Failed to read body of request", e); } this.bodyContentType = request.getContentType(); }
From source file:org.codemucker.testserver.capturing.CapturedRequest.java
public CapturedRequest(final HttpServletRequest req) { scheme = req.getScheme();// w w w.ja v a 2s . com host = req.getServerName(); port = req.getServerPort(); contextPath = req.getContextPath(); servletPath = req.getServletPath(); pathInfo = req.getPathInfo(); characterEncoding = req.getCharacterEncoding(); method = req.getMethod(); final Cookie[] cookies = req.getCookies(); // cookies if (cookies != null) { for (final Cookie cookie : cookies) { this.cookies.add(new CapturedCookie(cookie)); } } // headers for (@SuppressWarnings("unchecked") final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) { final String name = names.nextElement(); @SuppressWarnings("unchecked") final Enumeration<String> values = req.getHeaders(name); if (values != null) { for (; values.hasMoreElements();) { this.addHeader(new CapturedHeader(name, values.nextElement())); } } } // if we use the normal 'toString' on maps, and arrays, we get pretty // poor results // Use ArrayLists instead to get a nice output @SuppressWarnings("unchecked") final Map<String, String[]> paramMap = req.getParameterMap(); if (paramMap != null) { for (final String key : paramMap.keySet()) { final String[] vals = paramMap.get(key); this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals))); } } // handle multipart posts if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items final FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(factory); try { @SuppressWarnings("unchecked") final List<FileItem> items = upload.parseRequest(req); for (final FileItem item : items) { fileItems.add(new CapturedFileItem(item)); } } catch (final FileUploadException e) { throw new RuntimeException("Error handling multipart content", e); } } }
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 .jav a2 s.c o 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); } }