List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:org.gcaldaemon.core.servlet.ServletListener.java
private final void processRequest(HttpServletRequest req, HttpServletResponse rsp, boolean getMethod) throws ServletException, IOException { try {/*from w ww .ja v a2s . c o m*/ // Transform HttpServletRequest to Request Request request = new Request(); request.method = getMethod ? GET_METHOD : PUT_METHOD; // Transform URL request.url = req.getPathInfo(); int i = request.url.indexOf('@'); if (i != -1) { request.url = request.url.substring(0, i) + "%40" + request.url.substring(i + 1); } // Get the properties of the request HashMap properties = new HashMap(); Enumeration names = req.getHeaderNames(); String header; while (names.hasMoreElements()) { header = (String) names.nextElement(); properties.put(formatString(header.toCharArray()), req.getHeader(header)); } // Transform username and password header = (String) properties.get(AUTHORIZATION); if (header != null && header.startsWith(BASIC)) { header = StringUtils.decodeBASE64(header.substring(6)); int n = header.indexOf(COLON); if (n != 0) { request.username = header.substring(0, n); } if (n != header.length() - 1) { request.password = header.substring(n + 1); } } // Get Content-Length header int contentLength = 0; header = (String) properties.get(CONTENT_LENGTH); if (header != null && header.length() != 0) { contentLength = Integer.parseInt(header); } // Read body if (contentLength != 0) { int packet, readed = 0; request.body = new byte[contentLength]; ServletInputStream in = req.getInputStream(); while (readed != contentLength) { packet = in.read(request.body, readed, contentLength - readed); if (packet == -1) { throw new EOFException(); } readed += packet; } } // Redirect request to superclass Response response; if (getMethod) { response = doGet(request); } else { response = doPut(request); } // Set response status rsp.setStatus(response.status); // Add unauthorized header and realm if (response.status == STATUS_UNAUTHORIZED) { String realm = null; int s, e = request.url.indexOf("%40"); if (e != -1) { s = request.url.lastIndexOf('/', e); if (s != -1) { realm = request.url.substring(s + 1, e).replace('.', ' '); } } if (realm == null) { s = request.url.indexOf("private"); if (s != -1) { e = request.url.indexOf('/', s + 7); if (e != -1) { realm = request.url.substring(s + 8, e); } } } if (realm == null || realm.length() == 0) { realm = "Google Account"; } rsp.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + '\"'); } // Write body ServletOutputStream out = null; try { out = rsp.getOutputStream(); out.write(response.body); } finally { if (out != null) { try { out.close(); } catch (Exception ignored) { } } } } catch (Exception processingError) { throw new ServletException("Unable to process " + req.getMethod() + " request!", processingError); } }
From source file:org.asynchttpclient.test.EchoHandler.java
@Override public void handle(String pathInContext, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException { LOGGER.debug("Echo received request {} on path {}", request, pathInContext); if (httpRequest.getHeader("X-HEAD") != null) { httpResponse.setContentLength(1); }/*from w w w . j a v a2 s.c om*/ if (httpRequest.getHeader("X-ISO") != null) { httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_ISO_8859_1_CHARSET); } else { httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET); } if (request.getMethod().equalsIgnoreCase("OPTIONS")) { httpResponse.addHeader("Allow", "GET,HEAD,POST,OPTIONS,TRACE"); } Enumeration<String> e = httpRequest.getHeaderNames(); String headerName; while (e.hasMoreElements()) { headerName = e.nextElement(); if (headerName.startsWith("LockThread")) { final int sleepTime = httpRequest.getIntHeader(headerName); try { Thread.sleep(sleepTime == -1 ? 40 : sleepTime * 1000); } catch (InterruptedException ex) { // } } if (headerName.startsWith("X-redirect")) { httpResponse.sendRedirect(httpRequest.getHeader("X-redirect")); return; } httpResponse.addHeader("X-" + headerName, httpRequest.getHeader(headerName)); } String pathInfo = httpRequest.getPathInfo(); if (pathInfo != null) httpResponse.addHeader("X-pathInfo", pathInfo); String queryString = httpRequest.getQueryString(); if (queryString != null) httpResponse.addHeader("X-queryString", queryString); httpResponse.addHeader("X-KEEP-ALIVE", httpRequest.getRemoteAddr() + ":" + httpRequest.getRemotePort()); Cookie[] cs = httpRequest.getCookies(); if (cs != null) { for (Cookie c : cs) { httpResponse.addCookie(c); } } Enumeration<String> i = httpRequest.getParameterNames(); if (i.hasMoreElements()) { StringBuilder requestBody = new StringBuilder(); while (i.hasMoreElements()) { headerName = i.nextElement(); httpResponse.addHeader("X-" + headerName, httpRequest.getParameter(headerName)); requestBody.append(headerName); requestBody.append("_"); } if (requestBody.length() > 0) { String body = requestBody.toString(); httpResponse.getOutputStream().write(body.getBytes()); } } String requestBodyLength = httpRequest.getHeader("X-" + CONTENT_LENGTH); if (requestBodyLength != null) { byte[] requestBodyBytes = IOUtils.toByteArray(httpRequest.getInputStream()); int total = requestBodyBytes.length; httpResponse.addIntHeader("X-" + CONTENT_LENGTH, total); String md5 = TestUtils.md5(requestBodyBytes, 0, total); httpResponse.addHeader(CONTENT_MD5.toString(), md5); httpResponse.getOutputStream().write(requestBodyBytes, 0, total); } else { int size = 16384; if (httpRequest.getContentLength() > 0) { size = httpRequest.getContentLength(); } if (size > 0) { int read = 0; while (read > -1) { byte[] bytes = new byte[size]; read = httpRequest.getInputStream().read(bytes); if (read > 0) { httpResponse.getOutputStream().write(bytes, 0, read); } } } } request.setHandled(true); httpResponse.getOutputStream().flush(); // FIXME don't always close, depends on the test, cf ReactiveStreamsTest httpResponse.getOutputStream().close(); }
From source file:io.milton.servlet.ServletRequest.java
public ServletRequest(HttpServletRequest r, ServletContext servletContext) { this.request = r; this.servletContext = servletContext; String sMethod = r.getMethod(); method = Request.Method.valueOf(sMethod); String s = r.getRequestURL().toString(); //MiltonUtils.stripContext(r); url = s;//from www . ja va 2 s . c o m tlRequest.set(r); tlServletContext.set(servletContext); if (log.isTraceEnabled()) { log.trace("Dumping headers ---- " + r.getMethod() + " " + r.getRequestURL() + " -----"); log.trace("Request class: " + r.getClass()); log.trace("Response class: " + r.getClass()); Enumeration names = r.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = r.getHeader(name); log.trace(" " + name + "=" + value); } log.trace("-------------------------------------------"); } }
From source file:org.gluu.oxtrust.action.Authenticator.java
/** * Authenticate using credentials passed from web request header *///from ww w.j a v a2s . co m public boolean shibboleth2Authenticate() { log.debug("Checking if user authenticated with shibboleth already"); boolean result = false; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest(); String authType = request.getAuthType(); String userUid = request.getHeader("REMOTE_USER"); String userUidlower = request.getHeader("remote_user"); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); log.trace(headerName + "-->" + request.getHeader(headerName)); } log.debug("Username is " + userUid); log.debug("UsernameLower is " + userUidlower); log.debug("AuthType is " + authType); Map<String, String[]> headers = FacesContext.getCurrentInstance().getExternalContext() .getRequestHeaderValuesMap(); for (String name : headers.keySet()) { log.trace(name + "==>" + StringUtils.join(headers.get(name))); } if (StringHelper.isEmpty(userUid) || StringHelper.isEmpty(authType) || !authType.equals("shibboleth")) { result = false; return result; } Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+"); Matcher matcher = pattern.matcher(userUid); User user = null; if (matcher.matches()) { // Find user by uid user = personService.getPersonByEmail(userUid); } else { // Find user by uid user = personService.getUserByUid(userUid); } if (user == null) { result = false; return result; } log.debug("Person Inum is " + user.getInum()); if (GluuStatus.ACTIVE.getValue().equals(user.getAttribute("gluuStatus"))) { credentials.setUsername(user.getUid()); // credentials.setPassword(""); Principal principal = new SimplePrincipal(user.getUid()); log.debug("Principal is " + principal.toString()); identity.acceptExternallyAuthenticatedPrincipal(principal); log.info("User '{0}' authenticated with shibboleth already", userUid); identity.quietLogin(); postLogin(user); Contexts.getSessionContext().set(OxTrustConstants.APPLICATION_AUTHORIZATION_TYPE, OxTrustConstants.APPLICATION_AUTHORIZATION_NAME_SHIBBOLETH2); result = true; if (Events.exists()) { facesMessages.clear(); Events.instance().raiseEvent(Identity.EVENT_LOGIN_SUCCESSFUL); } } else { result = false; } return result; }
From source file:it.cloudicaro.disit.servlet.kb.SparqlProxy.java
private void buildSparqlResponse(HttpServletRequest theReq, HttpServletResponse theResp) throws Exception { Date start = new Date(); HttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = null;/* w w w . j a va 2 s .c om*/ HttpResponse response = null; String theServerHost = Configuration.getInstance().get("kb.rdf.sparql_endpoint", "http://192.168.0.106:8080/openrdf-sesame/repositories/icaro5"); String query = theReq.getParameter("query"); String aEncodedQuery = URLEncoder.encode(query, "UTF-8"); String theReqUrl = theServerHost + "?query=" + aEncodedQuery; //System.out.println("request: " + theReqUrl); try { httpget = new HttpGet(theReqUrl); //System.out.println("request header:"); Enumeration<String> aHeadersEnum = theReq.getHeaderNames(); while (aHeadersEnum.hasMoreElements()) { String aHeaderName = aHeadersEnum.nextElement(); String aHeaderVal = theReq.getHeader(aHeaderName); httpget.setHeader(aHeaderName, aHeaderVal); //System.out.println(" "+aHeaderName+": "+aHeaderVal); } if (log.isDebugEnabled()) { log.debug("executing request " + httpget.getURI()); } // Create a response handler response = httpclient.execute(httpget); //System.out.println("response header:"); // set the same Headers for (Header aHeader : response.getAllHeaders()) { if (!aHeader.getName().equals("Transfer-Encoding") || !aHeader.getValue().equals("chunked")) theResp.setHeader(aHeader.getName(), aHeader.getValue()); //System.out.println(" "+aHeader.getName()+": "+aHeader.getValue()); } // set the same locale if (response.getLocale() != null) theResp.setLocale(response.getLocale()); // set the content theResp.setContentLength((int) response.getEntity().getContentLength()); theResp.setContentType(response.getEntity().getContentType().getValue()); // set the same status theResp.setStatus(response.getStatusLine().getStatusCode()); // redirect the output InputStream aInStream = null; OutputStream aOutStream = null; try { aInStream = response.getEntity().getContent(); aOutStream = theResp.getOutputStream(); byte[] buffer = new byte[1024]; int r = 0; do { r = aInStream.read(buffer); if (r != -1) aOutStream.write(buffer, 0, r); } while (r != -1); /* int data = aInStream.read(); while (data != -1) { aOutStream.write(data); data = aInStream.read(); } */ } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (aInStream != null) { aInStream.close(); } if (aOutStream != null) { aOutStream.close(); } } Date end = new Date(); System.out.println(start + " SPARQL-PERFORMANCE: " + (end.getTime() - start.getTime()) + "ms " + query); } finally { httpclient.getConnectionManager().closeExpiredConnections(); httpclient.getConnectionManager().shutdown(); } }
From source file:org.alfresco.web.app.servlet.ajax.AjaxServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// www. j a v a 2s .co m protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); // set default character encoding for the response response.setCharacterEncoding("utf-8"); response.setContentType("text/xml;charset=UTF-8"); long startTime = 0; String uri = request.getRequestURI(); if (logger.isDebugEnabled()) { final String queryString = request.getQueryString(); logger.debug("Processing URL: " + uri + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : "")); } // dump the request headers if (headersLogger.isDebugEnabled()) { final Enumeration<?> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { final String name = (String) headers.nextElement(); headersLogger.debug(name + ": " + request.getHeader(name)); } } try { // Make sure the user is authenticated, if not throw an error to return the // 500 Internal Server Error code back to the client AuthenticationStatus status = servletAuthenticate(request, response, false); if (status == AuthenticationStatus.Failure) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied: User not authenticated"); return; } setNoCacheHeaders(response); uri = uri.substring(request.getContextPath().length() + "/".length()); final String[] tokens = uri.split("/"); if (tokens.length < 3) { throw new AlfrescoRuntimeException("Servlet URL did not contain all required args: " + uri); } // retrieve the command from the URL final String commandName = tokens[1]; // retrieve the binding expression from the URL final String expression = tokens[2]; // setup the faces context final FacesContext facesContext = FacesHelper.getFacesContext(request, response, getServletContext()); // start a timer if (perfLogger.isDebugEnabled()) startTime = System.currentTimeMillis(); // instantiate the relevant command AjaxCommand command = null; if (Command.invoke.toString().equals(commandName)) { command = new InvokeCommand(); } else if (Command.get.toString().equals(commandName)) { command = new GetCommand(); } else { throw new AlfrescoRuntimeException("Unrecognised command received: " + commandName); } // execute the command command.execute(facesContext, expression, request, response); } catch (RuntimeException error) { handleError(response, error); } finally { // measure the time taken if (perfLogger.isDebugEnabled()) { perfLogger.debug("Time to execute command: " + (System.currentTimeMillis() - startTime) + "ms"); } ContextHolder.setContext(null); } }
From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java
/** * Determines whether a basic authentication header of the kind "Authorization: Basic ..." * is included in a HTTP request/* w w w .j a v a 2s .com*/ * @param req HTTP request * @return true for a basic authentication header provided */ private boolean isBasicAuthenticationHeaderProvided(HttpServletRequest req) { for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) { String headerKey = (String) enu.nextElement(); String headerValue = req.getHeader(headerKey); if (isBasicAuthenticationHeader(headerKey, headerValue)) return true; } return false; }
From source file:org.springframework.web.method.support.InvocableHandlerMethod.java
/** * Invoke the method after resolving its argument values in the context of * the given request./*from ww w .jav a2 s .com*/ * <p> * Argument values are commonly resolved through * {@link HandlerMethodArgumentResolver}s. The {@code provideArgs} parameter * however may supply argument values to be used directly, i.e. without * argument resolution. Examples of provided argument values include a * {@link WebDataBinder}, a {@link SessionStatus}, or a thrown exception * instance. Provided argument values are checked before argument resolvers. * * @param request * the current request * @param mavContainer * the ModelAndViewContainer for this request * @param providedArgs * "given" arguments matched by type, not resolved * @return the raw value returned by the invoked method * @exception Exception * raised if no suitable argument resolver can be found, or * if the method raised an exception */ public Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception { if (!SpringContextUtils.isContextInjected()) { return invokeForRequest1(request, mavContainer, providedArgs); } ILogService logService = SpringContextUtils.getBean(ILogService.class); Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs); StringBuilder sb = new StringBuilder(); String fullPath = ""; StringBuilder headerSB = new StringBuilder(); Map<String, String> headersMap = new HashMap<String, String>(); if (request instanceof ServletWebRequest) { HttpServletRequest servletWebRequest = ((ServletWebRequest) request).getRequest(); // path fullPath = servletWebRequest.getRequestURI(); sb.append("path:" + fullPath); sb.append(AdamSysConstants.LINE_SEPARATOR); sb.append("from:" + servletWebRequest.getRemoteAddr()); sb.append(AdamSysConstants.LINE_SEPARATOR); // header sb.append("header:"); sb.append(AdamSysConstants.LINE_SEPARATOR); Enumeration headerNames = servletWebRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = headerNames.nextElement().toString(); String value = request.getHeader(key); headersMap.put(key, value); headerSB.append(key + ":"); headerSB.append(value); headerSB.append(AdamSysConstants.LINE_SEPARATOR); } } sb.append(headerSB); sb.append("Invoking ["); sb.append(getBeanType().getSimpleName()).append("."); sb.append(getMethod().getName()).append("] method with arguments "); sb.append(AdamSysConstants.LINE_SEPARATOR); for (Object arg : args) { sb.append(arg + ":"); sb.append(JSON.toJSONString(arg)); sb.append(AdamSysConstants.LINE_SEPARATOR); } ThreadLocalHolder.initRunningAccount(); String runningAccount = ThreadLocalHolder.getRunningAccount(); logger.info("RA:" + runningAccount + " " + sb.toString()); long beginTime = System.currentTimeMillis(); Object returnValue = null; String methodName = AdamClassUtils.getTargetClass(this).getSimpleName() + ".invokeForRequest"; ThreadLocalHolder.setRunningAccountFlag(1); try { returnValue = doBefore(fullPath, headersMap, args, returnValue); if (returnValue == null) { returnValue = doInvoke(args); } } catch (Throwable t) { logger.error("returnValue:[" + JSON.toJSONString(returnValue) + "]" + t, t); ResultVo<String> resultVo = new ResultVo<String>(); resultVo.setResultCode(this.getClass(), BaseReslutCodeConstants.CODE_SYSTEM_ERROR); resultVo.setResultMsg(AdamExceptionUtils.getStackTrace(t)); returnValue = resultVo; } finally { returnValue = doAfter(fullPath, headersMap, args, returnValue); } if (returnValue instanceof ResultVo) { ResultVo resultVo = (ResultVo) returnValue; resultVo.setResultMsg("ra:" + runningAccount); if (resultVo.getResultCode().startsWith(BaseReslutCodeConstants.CODE_SYSTEM_ERROR)) { logService.sendTechnologyErrorAccountLog(args, returnValue, methodName, ""); } } long endTime = System.currentTimeMillis(); RequestLogEntity orderRequestLogEntity = new RequestLogEntity(); orderRequestLogEntity.setUrl(fullPath); orderRequestLogEntity.setHeader(headerSB.toString()); orderRequestLogEntity.setRequest(sb.toString()); orderRequestLogEntity.setResponse(JSON.toJSONString(returnValue)); orderRequestLogEntity.setUseTime(endTime - beginTime); logService.sendRequestLog(orderRequestLogEntity); logger.info("RA:" + runningAccount + " " + "Method [" + getMethod().getName() + "] " + AdamSysConstants.LINE_SEPARATOR + "returned [" + JSON.toJSONString(returnValue) + "]" + "useTime:" + (endTime - beginTime)); return returnValue; }
From source file:com.glaf.mail.website.springmvc.MailReceiveController.java
@ResponseBody @RequestMapping("/view") public void view(HttpServletRequest request) { String messageId = request.getParameter("messageId"); if (messageId != null) { messageId = RequestUtils.decodeString(messageId); Map<String, Object> dataMap = JsonUtils.decode(messageId); String taskId = (String) dataMap.get("taskId"); String itemId = (String) dataMap.get("itemId"); if (taskId != null && itemId != null) { MailItem mailItem = mailDataFacede.getMailItem(taskId, itemId); if (mailItem != null) { mailItem.setReceiveStatus(1); mailItem.setReceiveDate(new Date()); mailItem.setReceiveIP(RequestUtils.getIPAddress(request)); String contentType = request.getContentType(); mailItem.setContentType(contentType); logger.debug("contentType:" + contentType); java.util.Enumeration<String> e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); logger.debug(name + "=" + request.getHeader(name)); }/*from www .jav a 2s .c om*/ String userAgent = request.getHeader("user-agent"); if (userAgent != null) { if (userAgent.indexOf("Chrome") != -1) { mailItem.setBrowser("Chrome"); } else if (userAgent.indexOf("MSIE") != -1) { mailItem.setBrowser("IE"); } else if (userAgent.indexOf("Firefox") != -1) { mailItem.setBrowser("Firefox"); } if (userAgent.indexOf("Windows") != -1) { mailItem.setClientOS("Windows"); } } mailDataFacede.updateMail(taskId, mailItem); } } } }