List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:org.apache.olio.webapp.fileupload.FileUploadHandler.java
/** * Handles the initial fields up to the first upload field. This will * allow creating the database entry and obtaining the auto-generated * ids.//from ww w.j a v a 2 s. co m * @return A hash table with the initial field values */ public Hashtable<String, String> getInitialParams(HttpServletRequest request, HttpServletResponse response) { // print out header for Enumeration enumx = request.getHeaderNames(); String key = ""; String listx = ""; while (enumx.hasMoreElements()) { key = (String) enumx.nextElement(); listx += "\n" + key + ":" + request.getHeader(key); } logger.fine("Incoming Header Item:" + listx); // enable progress bar (this managed bean that is in the session could be comp specific, but I can't create the component specific // session object until I have the components name. For now use static key through backing bean). // Use session to allow the monitoring of the fileupload based HttpSession session = request.getSession(); FileUploadStatus status = new FileUploadStatus(); session.setAttribute(FileUploadUtil.FILE_UPLOAD_STATUS, status); setFileUploadStatus(status); // Create hashtable to hold uploaded data so it can be used by custom post extension Hashtable<String, String> htUpload = new Hashtable<String, String>(); // set to set hashtable for final retrieval status.setUploadItems(htUpload); // get size of upload and set status long totalSizeOfUpload = request.getContentLength(); status.setTotalUploadSize(totalSizeOfUpload); // Check that we have a proper file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Streaming API typically provide better performance for file uploads. // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); try { // Now we should have the componentsName and upload directory to setup remaining upload of file items String compName = htUpload.get(FileUploadUtil.COMPONENT_NAME); status.setName(compName); // Parse the request and return list of "FileItem" whle updating status FileItemIterator iter = upload.getItemIterator(request); status.setReadingComplete(); while (iter.hasNext()) { item = iter.next(); if (item.isFormField()) { // handle a form item being uploaded String itemName = item.getFieldName(); // process form(non-file) item200002 int size = formItemFound(item, htUpload); updateSessionStatus(itemName, size); logger.fine("Form field item:" + itemName); } else { // At the first find of an uploaded file, stop. // We need to insert our record first in order // to find the id. break; } } itemIter = iter; } catch (Exception e) { status.setUploadError( "FileUpload didn't complete successfully. Exception received:" + e.toString()); logger.log(Level.SEVERE, "file.upload.exception", e); } } fileUploadStatus = status; requestParams = htUpload; return htUpload; }
From source file:com.cloud.bridge.service.controller.s3.S3ObjectAction.java
/** * Extract the name and value of all meta data so it can be written with the * object that is being 'PUT'./*from ww w .j a va2s. co m*/ * * @param request * @return */ private S3MetaDataEntry[] extractMetaData(HttpServletRequest request) { List<S3MetaDataEntry> metaSet = new ArrayList<S3MetaDataEntry>(); int count = 0; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String key = (String) headers.nextElement(); if (key.startsWith("x-amz-meta-")) { String name = key.substring(11); String value = request.getHeader(key); if (null != value) { S3MetaDataEntry oneMeta = new S3MetaDataEntry(); oneMeta.setName(name); oneMeta.setValue(value); metaSet.add(oneMeta); count++; } } } if (0 < count) return metaSet.toArray(new S3MetaDataEntry[0]); else return null; }
From source file:org.wso2.carbon.identity.oauth.endpoint.token.OAuth2TokenEndpointTest.java
@Test(dataProvider = "testGetAccessTokenDataProvider") public void testGetAccessToken(String grantType, String additionalParameters) throws Exception { Map<String, String[]> requestParams = new HashMap<>(); requestParams.put(OAuth.OAUTH_CLIENT_ID, new String[] { CLIENT_ID_VALUE }); requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType }); requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" }); // Required params for authorization_code grant type requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL }); requestParams.put(OAuth.OAUTH_CODE, new String[] { "auth_code" }); // Required params for password grant type requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME }); requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" }); // Required params for refresh token grant type requestParams.put(OAuth.OAUTH_REFRESH_TOKEN, new String[] { REFRESH_TOKEN }); // Required params for saml2 bearer grant type requestParams.put(OAuth.OAUTH_ASSERTION, new String[] { "dummyAssertion" }); // Required params for IWA_NLTM grant type requestParams.put(OAuthConstants.WINDOWS_TOKEN, new String[] { "dummyWindowsToken" }); HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>()); when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(AUTHORIZATION_HEADER); when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() { {/*from w ww . j a v a2s . c om*/ add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ); } })); Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>(); grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class); grantTypeValidators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class); grantTypeValidators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class); grantTypeValidators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class); grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString(), NTLMAuthenticationValidator.class); grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString(), SAML2GrantValidator.class); mockOAuthServerConfiguration(); when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators); spy(EndpointUtil.class); doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service"); final Map<String, String> parametersSetToRequest = new HashMap<>(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenReqDTO request = (OAuth2AccessTokenReqDTO) invocation.getArguments()[0]; parametersSetToRequest.put(OAuth.OAUTH_CODE, request.getAuthorizationCode()); parametersSetToRequest.put(OAuth.OAUTH_USERNAME, request.getResourceOwnerUsername()); parametersSetToRequest.put(OAuth.OAUTH_PASSWORD, request.getResourceOwnerPassword()); parametersSetToRequest.put(OAuth.OAUTH_REFRESH_TOKEN, request.getRefreshToken()); parametersSetToRequest.put(OAuth.OAUTH_ASSERTION, request.getAssertion()); parametersSetToRequest.put(OAuthConstants.WINDOWS_TOKEN, request.getWindowsToken()); parametersSetToRequest.put(OAuth.OAUTH_GRANT_TYPE, request.getGrantType()); OAuth2AccessTokenRespDTO tokenRespDTO = new OAuth2AccessTokenRespDTO(); return tokenRespDTO; } }).when(oAuth2Service).issueAccessToken(any(OAuth2AccessTokenReqDTO.class)); CarbonOAuthTokenRequest oauthRequest = new CarbonOAuthTokenRequest(request); Class<?> clazz = OAuth2TokenEndpoint.class; Object tokenEndpointObj = clazz.newInstance(); Method getAccessToken = tokenEndpointObj.getClass().getDeclaredMethod("issueAccessToken", CarbonOAuthTokenRequest.class); getAccessToken.setAccessible(true); OAuth2AccessTokenRespDTO tokenRespDTO = (OAuth2AccessTokenRespDTO) getAccessToken.invoke(tokenEndpointObj, oauthRequest); assertNotNull(tokenRespDTO, "ResponseDTO is null"); String[] paramsToCheck = additionalParameters.split(","); for (String param : paramsToCheck) { assertNotNull(parametersSetToRequest.get(param), "Required parameter " + param + " is not set for " + grantType + "grant type"); } }
From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java
/** {@inheritDoc} */ @SuppressWarnings(value = "unchecked") public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (this.config == null) { return;// w ww. ja va 2 s . c o m } // Just pass through to next filter if we're not at TRACE level if (!logger.isTraceEnabled()) { chain.doFilter(request, response); return; } // Create a variable to hold the (possibly different) request // passed to downstream filters ServletRequest downstreamRequest = request; // Render the generic servlet request properties final StringWriter sw = new StringWriter(); final PrintWriter writer = new PrintWriter(sw); writer.println("Dumping request..."); writer.println("-----------------------------------------------------"); writer.println("REQUEST received " + Calendar.getInstance().getTime()); writer.println(" characterEncoding=" + request.getCharacterEncoding()); writer.println(" contentLength=" + request.getContentLength()); writer.println(" contentType=" + request.getContentType()); writer.println(" locale=" + request.getLocale()); writer.print(" locales="); final Enumeration<Locale> locales = request.getLocales(); for (int i = 0; locales.hasMoreElements(); i++) { if (i > 0) { writer.print(", "); } writer.print(locales.nextElement()); } writer.println(); final Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { final String name = paramNames.nextElement(); writer.print(" parameter=" + name + "="); final String[] values = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { writer.print(", "); } writer.print(values[i]); } writer.println(); } writer.println(" protocol=" + request.getProtocol()); writer.println(" remoteAddr=" + request.getRemoteAddr()); writer.println(" remoteHost=" + request.getRemoteHost()); writer.println(" scheme=" + request.getScheme()); writer.println(" serverName=" + request.getServerName()); writer.println(" serverPort=" + request.getServerPort()); writer.println(" isSecure=" + request.isSecure()); // Render the HTTP servlet request properties if (request instanceof HttpServletRequest) { final HttpServletRequest hrequest = (HttpServletRequest) request; writer.println(" contextPath=" + hrequest.getContextPath()); Cookie[] cookies = hrequest.getCookies(); if (cookies == null) { cookies = new Cookie[0]; } for (int i = 0; i < cookies.length; i++) { writer.println(" cookie=" + cookies[i].getName() + "=" + cookies[i].getValue()); } final Enumeration<String> headerNames = hrequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = hrequest.getHeader(name); writer.println(" header=" + name + "=" + value); } writer.println(" method=" + hrequest.getMethod()); writer.println(" pathInfo=" + hrequest.getPathInfo()); writer.println(" queryString=" + hrequest.getQueryString()); writer.println(" remoteUser=" + hrequest.getRemoteUser()); writer.println("requestedSessionId=" + hrequest.getRequestedSessionId()); writer.println(" requestURI=" + hrequest.getRequestURI()); writer.println(" servletPath=" + hrequest.getServletPath()); // Create a wrapped request that contains the request body // and that we will pass to downstream filters final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest); downstreamRequest = wrappedRequest; writer.println(wrappedRequest.getRequestBodyAsString()); } writer.println("-----------------------------------------------------"); // Log the resulting string writer.flush(); logger.trace(sw.getBuffer().toString()); // Pass control on to the next filter chain.doFilter(downstreamRequest, response); }
From source file:org.apache.ranger.security.web.filter.RangerSSOAuthenticationFilter.java
private String constructForwardableURL(HttpServletRequest httpRequest) { String xForwardedProto = ""; String xForwardedHost = ""; String xForwardedContext = ""; Enumeration<?> names = httpRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration<?> values = httpRequest.getHeaders(name); String value = ""; if (values != null) { while (values.hasMoreElements()) { value = (String) values.nextElement(); }//from w w w.j a va2 s. co m } if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { if (name.equalsIgnoreCase("x-forwarded-proto")) { xForwardedProto = value; } else if (name.equalsIgnoreCase("x-forwarded-host")) { xForwardedHost = value; } else if (name.equalsIgnoreCase("x-forwarded-context")) { xForwardedContext = value; } } } String xForwardedURL = ""; if (StringUtils.trimToNull(xForwardedProto) != null && StringUtils.trimToNull(xForwardedHost) != null && StringUtils.trimToNull(xForwardedContext) != null) { xForwardedURL = xForwardedProto + "://" + xForwardedHost + xForwardedContext + PROXY_RANGER_URL_PATH + httpRequest.getRequestURI(); } return xForwardedURL; }
From source file:org.springframework.security.web.savedrequest.DefaultSavedRequest.java
@SuppressWarnings("unchecked") public DefaultSavedRequest(HttpServletRequest request, PortResolver portResolver) { Assert.notNull(request, "Request required"); Assert.notNull(portResolver, "PortResolver required"); // Cookies//ww w . j a v a2 s. c o m addCookies(request.getCookies()); // Headers Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); // Skip If-Modified-Since and If-None-Match header. SEC-1412, SEC-1624. if (HEADER_IF_MODIFIED_SINCE.equalsIgnoreCase(name) || HEADER_IF_NONE_MATCH.equalsIgnoreCase(name)) { continue; } Enumeration<String> values = request.getHeaders(name); while (values.hasMoreElements()) { this.addHeader(name, values.nextElement()); } } // Locales addLocales(request.getLocales()); // Parameters addParameters(request.getParameterMap()); // Primitives this.method = request.getMethod(); this.pathInfo = request.getPathInfo(); this.queryString = request.getQueryString(); this.requestURI = request.getRequestURI(); this.serverPort = portResolver.getServerPort(request); this.requestURL = request.getRequestURL().toString(); this.scheme = request.getScheme(); this.serverName = request.getServerName(); this.contextPath = request.getContextPath(); this.servletPath = request.getServletPath(); }
From source file:be.fedict.eid.applet.service.AppletServiceServlet.java
@SuppressWarnings("unchecked") @Override//from w ww .ja va 2 s .c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doPost"); /* * First retrieve the HTTP headers. The unmarshaller may digest the * body, which makes it impossible to retrieve the headers afterwards. */ Map<String, String> httpHeaders = new HashMap<String, String>(); Enumeration<String> headerNamesEnum = request.getHeaderNames(); while (headerNamesEnum.hasMoreElements()) { String headerName = headerNamesEnum.nextElement(); httpHeaders.put(headerName, request.getHeader(headerName)); } /* * Incoming message unmarshaller. */ HttpServletRequestHttpReceiver httpReceiver = new HttpServletRequestHttpReceiver(request, this.skipSecureConnectionCheck); Object transferObject; try { transferObject = this.unmarshaller.receive(httpReceiver); } catch (Exception e) { LOG.debug("unmarshaller error: " + e.getMessage(), e); throw new RuntimeException("unmarshaller error: " + e.getMessage(), e); } /* * Protocol state checker for incoming message. */ HttpServletProtocolContext protocolContext = new HttpServletProtocolContext(request); ProtocolStateMachine protocolStateMachine = new ProtocolStateMachine(protocolContext); CleanSessionProtocolStateListener cleanSessionProtocolStateListener = new CleanSessionProtocolStateListener( request); protocolStateMachine.addProtocolStateListener(cleanSessionProtocolStateListener); RequestContext requestContext = new RequestContext(request); protocolStateMachine.addProtocolStateListener(requestContext); protocolStateMachine.checkRequestMessage(transferObject); /* * Message dispatcher */ Class<?> messageClass = transferObject.getClass(); MessageHandler messageHandler = this.messageHandlers.get(messageClass); if (null == messageHandler) { throw new ServletException("unsupported message"); } HttpSession session = request.getSession(); Object responseMessage = messageHandler.handleMessage(transferObject, httpHeaders, request, session); /* * Check outgoing messages for protocol constraints. */ ResponsesAllowed responsesAllowedAnnotation = messageClass.getAnnotation(ResponsesAllowed.class); if (null != responsesAllowedAnnotation) { /* * Make sure the message handlers respect the protocol. */ if (null == responseMessage) { throw new ServletException("null response message while @ResponsesAllowed constraint was set"); } Class<?>[] responsesAllowed = responsesAllowedAnnotation.value(); if (false == isOfClass(responseMessage, responsesAllowed)) { throw new ServletException("response message type incorrect"); } } /* * Protocol state checker for outgoing message. */ protocolStateMachine.checkResponseMessage(responseMessage); /* * Marshall outgoing message. */ if (null != responseMessage) { HttpServletResponseHttpTransmitter httpTransmitter = new HttpServletResponseHttpTransmitter(response); Transport.transfer(responseMessage, httpTransmitter); } }
From source file:org.acegisecurity.ui.savedrequest.SavedRequest.java
public SavedRequest(HttpServletRequest request, PortResolver portResolver) { Assert.notNull(request, "Request required"); Assert.notNull(portResolver, "PortResolver required"); // Cookies/* w ww .j a va 2 s . c o m*/ Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { this.addCookie(cookies[i]); } } // Headers Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration values = request.getHeaders(name); while (values.hasMoreElements()) { String value = (String) values.nextElement(); this.addHeader(name, value); } } // Locales Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = (Locale) locales.nextElement(); this.addLocale(locale); } // Parameters Map parameters = request.getParameterMap(); Iterator paramNames = parameters.keySet().iterator(); while (paramNames.hasNext()) { String paramName = (String) paramNames.next(); Object o = parameters.get(paramName); if (o instanceof String[]) { String[] paramValues = (String[]) o; this.addParameter(paramName, paramValues); } else { if (logger.isWarnEnabled()) { logger.warn("ServletRequest.getParameterMap() returned non-String array"); } } } // Primitives this.method = request.getMethod(); this.pathInfo = request.getPathInfo(); this.queryString = request.getQueryString(); this.requestURI = request.getRequestURI(); this.serverPort = portResolver.getServerPort(request); this.requestURL = request.getRequestURL().toString(); this.scheme = request.getScheme(); this.serverName = request.getServerName(); this.contextPath = request.getContextPath(); this.servletPath = request.getServletPath(); }
From source file:org.jboss.web.loadbalancer.Loadbalancer.java
protected HttpClient prepareServerRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) {//from w ww. j av a2 s.c om // clear state HttpClient client = new HttpClient(connectionManager); client.setStrictMode(false); client.setTimeout(connectionTimeout); method.setFollowRedirects(false); method.setDoAuthentication(false); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); Enumeration reqHeaders = request.getHeaderNames(); while (reqHeaders.hasMoreElements()) { String headerName = (String) reqHeaders.nextElement(); String headerValue = request.getHeader(headerName); if (!ignorableHeader.contains(headerName.toLowerCase())) { method.setRequestHeader(headerName, headerValue); } } //Cookies Cookie[] cookies = request.getCookies(); HttpState state = client.getState(); for (int i = 0; cookies != null && i < cookies.length; ++i) { Cookie cookie = cookies[i]; org.apache.commons.httpclient.Cookie reqCookie = new org.apache.commons.httpclient.Cookie(); reqCookie.setName(cookie.getName()); reqCookie.setValue(cookie.getValue()); if (cookie.getPath() != null) { reqCookie.setPath(cookie.getPath()); } else { reqCookie.setPath("/"); } reqCookie.setSecure(cookie.getSecure()); reqCookie.setDomain(method.getHostConfiguration().getHost()); state.addCookie(reqCookie); } return client; }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.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 Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //TODO why? // if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) // continue; if (hopByHopHeaders.containsHeader(headerName)) 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 headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); //Don't do this unless we need to /*if (headerName.equalsIgnoreCase(HttpHeaders.USER_AGENT)){ headerValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0"; }*///from w w w . j a v a 2s. c o m // 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 = URIUtils.extractHost(this.targetUri); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); } proxyRequest.addHeader(headerName, headerValue); } } }