List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp, AuthStep as) throws ServletException, IOException { HttpSession session = req.getSession(true); if (req.getParameter("SAMLResponse") != null) { String[] resps = req.getParameterValues("SAMLResponse"); if (logger.isDebugEnabled()) { for (int i = 0; i < resps.length; i++) { logger.debug(resps[i]);//from ww w .ja v a2s . co m } } String b64resp = resps[0]; } else { RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); Attribute jumpPage = authParams.get("jumpPage"); if (jumpPage != null && jumpPage.getValues().size() == 1 && !jumpPage.getValues().get(0).isEmpty()) { if (logger.isDebugEnabled()) { Enumeration enumer = req.getHeaderNames(); while (enumer.hasMoreElements()) { String name = (String) enumer.nextElement(); logger.debug("Header '" + name + "'='" + req.getHeader(name) + "'"); } } //String referer = req.getHeader("Referer"); String isJump = req.getParameter("isJump"); if (isJump != null && isJump.equalsIgnoreCase("true")) { logger.debug("initializing SSO"); this.initializeSSO(req, resp, session, false, null); } else { this.initializeSSO(req, resp, session, true, jumpPage.getValues().get(0)); } } else { this.initializeSSO(req, resp, session, false, null); } } }
From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); if (req.getParameter("update") != null) { uri.append(targetUri).append("/").append(req.getParameter("update")); } else {//from ww w .j a va2 s .c o m uri.append(targetUri); } LOG.info("Access URI : " + uri.toString()); // 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<?> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); String headerValue = req.getHeader(headerName); //LOG.info("header: " + headerName + " value: " + headerValue); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-type")) { request.addHeader(headerName, headerValue + ";charset=\"utf-8\""); } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) { 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()); // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; if (!header.getName().equals("Transfer-Encoding")) resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); byte buffer[] = new byte[50]; while (input.read(buffer) != -1) { output.write(buffer); } // 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.web.server.ProxyServlet.java
@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 ww w .ja v a 2s .c om*/ uri.append(req.getRequestURI()); // 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(); 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:net.ymate.module.webproxy.WebProxy.java
@SuppressWarnings("unchecked") public void transmission(HttpServletRequest request, HttpServletResponse response, String url, Type.HttpMethod method) throws Exception { StopWatch _consumeTime = null;//w ww. j a v a2 s. c o m long _threadId = 0; if (_LOG.isDebugEnabled()) { _consumeTime = new StopWatch(); _consumeTime.start(); _threadId = Thread.currentThread().getId(); _LOG.debug("-------------------------------------------------"); _LOG.debug("--> [" + _threadId + "] URL: " + url); } // HttpURLConnection _conn = null; try { if (__moduleCfg.isUseProxy()) { _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy()); } else { _conn = (HttpURLConnection) new URL(url).openConnection(); } _conn.setUseCaches(__moduleCfg.isUseCaches()); _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects()); // boolean _postFlag = Type.HttpMethod.POST.equals(method); boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/"); if (_postFlag) { _conn.setDoOutput(true); _conn.setDoInput(true); _conn.setRequestMethod(method.name()); } if (__moduleCfg.getConnectTimeout() > 0) { _conn.setConnectTimeout(__moduleCfg.getConnectTimeout()); } if (__moduleCfg.getReadTimeout() > 0) { _conn.setReadTimeout(__moduleCfg.getReadTimeout()); } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Method: " + method.name()); _LOG.debug("--> [" + _threadId + "] Request Headers: "); } // Enumeration _header = request.getHeaderNames(); while (_header.hasMoreElements()) { String _name = (String) _header.nextElement(); String _value = request.getHeader(_name); boolean _flag = false; if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type") || __moduleCfg.isTransferHeaderEnabled() && (!__moduleCfg.getTransferHeaderBlackList().isEmpty() && !__moduleCfg.getTransferHeaderBlackList().contains(_name) || !__moduleCfg.getTransferHeaderWhiteList().isEmpty() && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) { _conn.setRequestProperty(_name, _value); _flag = true; } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value); } } _conn.connect(); // if (_postFlag) { DataOutputStream _output = new DataOutputStream(_conn.getOutputStream()); try { if (_multipartFlag) { if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Multipart: TRUE"); } IOUtils.copyLarge(request.getInputStream(), _output); } else { String _charset = request.getCharacterEncoding(); String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset); IOUtils.write(_queryStr, _output, _charset); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Request Parameters: "); Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true, _charset); for (Map.Entry<String, String> _param : _paramsMap.entrySet()) { _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": " + _param.getValue()); } } } _output.flush(); } finally { IOUtils.closeQuietly(_output); } } // int _code = _conn.getResponseCode(); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Code: " + _code); _LOG.debug("--> [" + _threadId + "] Response Headers: "); } // Map<String, List<String>> _headers = _conn.getHeaderFields(); for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) { if (_entry.getKey() != null) { boolean _flag = false; String _values = StringUtils.join(_entry.getValue(), ","); if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type") || __moduleCfg.isTransferHeaderEnabled() && !__moduleCfg.getResponseHeaderWhileList().isEmpty() && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) { response.setHeader(_entry.getKey(), _values); _flag = true; } if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": " + _values); } } } if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) { response.sendError(_code); } else { if (HttpURLConnection.HTTP_OK == _code) { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { if (!_multipartFlag) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody( _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else { IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody"); } } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.flushBuffer(); } else { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.setStatus(_code); response.flushBuffer(); } } } catch (Throwable e) { _LOG.warn("An exception occurred while processing request mapping '" + url + "': ", RuntimeUtils.unwrapThrow(e)); } finally { IOUtils.close(_conn); // if (_LOG.isDebugEnabled()) { if (_consumeTime != null) { _consumeTime.stop(); _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("-------------------------------------------------"); } } }
From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java
public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) { HttpServletRequest initialRequest = (HttpServletRequest) request; this.session = session; this.authorization = authorization; //Copy common data authType = initialRequest.getAuthType(); contextPath = initialRequest.getContextPath(); remoteUser = initialRequest.getRemoteUser(); userPrincipal = initialRequest.getUserPrincipal(); requestedSessionId = initialRequest.getRequestedSessionId(); requestedSessionIdValid = initialRequest.isRequestedSessionIdValid(); attributes = new HashMap(); Enumeration attributeNames = initialRequest.getAttributeNames(); while (attributeNames.hasMoreElements()) { String name = (String) attributeNames.nextElement(); Object attribute = initialRequest.getAttribute(name); if ((null != name) && (null != attribute)) { attributes.put(name, attribute); }// ww w. j av a 2 s.c om } // Warning: For some reason, the various javax.include.* attributes are // not available via the getAttributeNames() call. This may be limited // to a Liferay issue but when the MainPortlet dispatches the call to // the MainServlet, all of the javax.include.* attributes can be // retrieved using this.request.getAttribute() but they do NOT appear in // the Enumeration of names returned by getAttributeNames(). So here // we manually add them to our map to ensure we can find them later. String[] incAttrKeys = Constants.INC_CONSTANTS; for (int index = 0; index < incAttrKeys.length; index++) { String incAttrKey = incAttrKeys[index]; Object incAttrVal = initialRequest.getAttribute(incAttrKey); if (incAttrVal != null) { attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey)); } } headers = new HashMap(); Enumeration headerNames = initialRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); Enumeration values = initialRequest.getHeaders(name); headers.put(name, Collections.list(values)); } parameters = new HashMap(); Enumeration parameterNames = initialRequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); parameters.put(name, initialRequest.getParameterValues(name)); } scheme = initialRequest.getScheme(); serverName = initialRequest.getServerName(); serverPort = initialRequest.getServerPort(); secure = initialRequest.isSecure(); //Copy servlet specific data cookies = initialRequest.getCookies(); method = initialRequest.getMethod(); pathInfo = initialRequest.getPathInfo(); pathTranslated = initialRequest.getPathTranslated(); queryString = initialRequest.getQueryString(); requestURI = initialRequest.getRequestURI(); try { requestURL = initialRequest.getRequestURL(); } catch (NullPointerException e) { //TODO remove this catch block when GlassFish bug is addressed if (log.isErrorEnabled()) { log.error("Null Protocol Scheme in request", e); } HttpServletRequest req = initialRequest; requestURL = new StringBuffer( "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI()); } servletPath = initialRequest.getServletPath(); servletSession = initialRequest.getSession(); isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie(); isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL(); characterEncoding = initialRequest.getCharacterEncoding(); contentLength = initialRequest.getContentLength(); contentType = initialRequest.getContentType(); protocol = initialRequest.getProtocol(); remoteAddr = initialRequest.getRemoteAddr(); remoteHost = initialRequest.getRemoteHost(); initializeServlet2point4Properties(initialRequest); }
From source file:io.datenwelt.cargo.rest.Request.java
public Request(HttpServletRequest servletRequest, List<ContentType> supportedContentTypes, List<ContentEncoding> supportedContentEncodings) throws APIException { this.servletRequest = servletRequest; this.supportedContentTypes = supportedContentTypes; this.supportedContentEncodings = supportedContentEncodings; this.method = servletRequest.getMethod(); this.path = Segment.normalize(servletRequest.getPathInfo()); StringBuffer url = servletRequest.getRequestURL(); String query = servletRequest.getQueryString(); if (query != null && !query.isEmpty()) { url.append("?").append(query); }/* w w w . j av a 2 s.c o m*/ // Parse request URI and construct the base URI. try { requestURI = new URI(url.toString()); String basePath = (servletRequest.getContextPath() == null ? "" : servletRequest.getContextPath()) + (servletRequest.getServletPath() == null ? "" : servletRequest.getServletPath()); baseURI = URI.create(new StringBuffer().append(requestURI.getScheme()).append("://") .append(requestURI.getRawAuthority()).append("/").append(basePath).toString()); path = Segment.normalize(requestURI.getPath()); if (path.startsWith(basePath)) { path = path.substring(basePath.length()); } } catch (URISyntaxException ex) { throw new APIException(new InternalServerError(), "Unable to parse request URI from string '" + requestURI + "'. Using defaut value for base URI. Error: " + ex.getMessage(), ex); } // Parse query string. String queryString = servletRequest.getQueryString(); this.queries.addAll(Query.parseQueryString(queryString)); // Parse header values Enumeration headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement().toString(); Enumeration values = servletRequest.getHeaders(name); while (values.hasMoreElements()) { Header header = headers.get(name); if (header == null) { header = new Header(name); headers.put(header.getName(), header); } String value = values.nextElement().toString(); header.add(Header.decode(name, value)); } } // Collect infos about the remote end. remoteAddress = servletRequest.getRemoteAddr(); remoteHost = servletRequest.getRemoteHost(); remotePort = servletRequest.getRemotePort(); }
From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { ObjectMapper mapper = new ObjectMapper(); String format;//from w ww . j av a 2s .c o m String language; String redirect_url; this.logger.debug("PathInfo = " + httpServletRequest.getPathInfo()); this.logger.debug("QueryString = " + httpServletRequest.getQueryString()); String service = ""; String authorization = ""; String path = httpServletRequest.getPathInfo(); String[] params = path.substring(1, path.length()).split("/"); if (params.length == 1) { service = params[0]; } format = "html"; language = ""; // Hole 'Accept' und 'Authorization' aus dem Header; Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = (String) headerNames.nextElement(); this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Accept")) { this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey)); if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) { format = "html"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) { format = "xml"; } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) { format = "json"; } } if (headerNameKey.equals("Accept-Language")) { language = httpServletRequest.getHeader(headerNameKey); this.logger.debug("Accept-Language: " + language); } if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); } } this.logger.debug("Service: " + service); if (httpServletRequest.getParameter("format") != null && !httpServletRequest.getParameter("format").equals("")) { format = httpServletRequest.getParameter("format"); } this.logger.info("format = " + format); if (format.equals("html") && Lookup.lookupAll(ObjectToHtmlTransformation.class).size() == 0) { this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + "html not implemented!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, ""); } else { // redirect_url redirect_url = ""; if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { if (httpServletRequest.getParameter("redirect_url").contains("redirect_url=")) { String tmp[] = httpServletRequest.getParameter("redirect_url").split("redirect_url="); redirect_url = tmp[0] + "redirect_url=" + URLEncoder.encode(tmp[1], "UTF-8"); } else { redirect_url = httpServletRequest.getParameter("redirect_url"); } } this.logger.info("redirect_url = " + redirect_url); // language if (language.startsWith("de")) { language = "de"; } else if (language.startsWith("en")) { language = "en"; } else if (httpServletRequest.getParameter("l") != null) { language = httpServletRequest.getParameter("l"); } else { language = "de"; } this.logger.info("language = " + language); if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null) { authorization = httpServletRequest.getParameter("access_token"); } if (authorization.equals("")) { // if exists PaiaService-Cookie: read content Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("PaiaService")) { String value = URLDecoder.decode(cookie.getValue(), "UTF-8"); this.logger.info(value); LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class); authorization = loginResponse.getAccess_token(); break; } } } } this.logger.debug("Access_token: " + authorization); StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = httpServletRequest.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } String requestBody = jb.toString(); this.logger.info(requestBody); httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); // 2. Schritt: Service if (service.equals("login") || service.equals("logout") || service.equals("change") || service.equals("renew")) { this.provideService(httpServletRequest, httpServletResponse, service, authorization, requestBody, format, language, redirect_url); } else { this.logger.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service + "' not allowed!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED))); requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } }
From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java
/** * @param req/*from w w w . j a va 2 s .com*/ * @param request * @throws GVException */ private void parseRequest(HttpServletRequest req, String methodName, PatternResolver pr, GVBuffer request) throws GVException { try { Map<String, String[]> params = req.getParameterMap(); Iterator<String> i = params.keySet().iterator(); while (i.hasNext()) { String n = i.next(); String v = params.get(n)[0]; request.setProperty(n, ((v != null) && !"".equals(v)) ? v : "NULL"); } String ct = Optional.ofNullable(req.getContentType()).orElse(""); request.setProperty("HTTP_REQ_CONTENT_TYPE", ct.isEmpty() ? ct : "NULL"); String acc = req.getHeader("Accept"); request.setProperty("HTTP_REQ_ACCEPT", (acc != null) ? acc : "NULL"); if (methodName.equals("POST") || methodName.equals("PUT")) { if (!ct.startsWith(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)) { Object requestContent = IOUtils.toByteArray(req.getInputStream()); if (ct.startsWith(AdapterHttpConstants.APPXML_MIMETYPE_NAME) || ct.startsWith(AdapterHttpConstants.APPJSON_MIMETYPE_NAME) || ct.startsWith("text/")) { /* GESTIRE ENCODING!!! */ requestContent = new String((byte[]) requestContent); } request.setObject(requestContent); } } if (pr.isExtractHdr()) { XMLUtils parser = null; try { parser = XMLUtils.getParserInstance(); Document doc = parser.newDocument("Hdr"); Element root = doc.getDocumentElement(); Enumeration<?> hn = req.getHeaderNames(); while (hn.hasMoreElements()) { Element h = parser.insertElement(root, "h"); String name = (String) hn.nextElement(); String val = req.getHeader(name); parser.setAttribute(h, "n", name); parser.setAttribute(h, "v", val); } request.setProperty("HTTP_REQ_HEADERS", parser.serializeDOM(doc, true, false)); } finally { XMLUtils.releaseParserInstance(parser); } } } catch (Exception exc) { throw new AdapterHttpExecutionException("RESTHttpServletMapping - Error parsing request data", exc); } }
From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(403, "User is not logged in"); return;//from w w w.j a va 2 s.c o m } if (!servletRequest.isUserInRole("HOPS_ADMIN")) { servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(), "You don't have the access right for this service"); return; } if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); } if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not // sure it would truly be compatible String proxyRequestUri = rewriteUrlFromRequest(servletRequest); try { // Execute the request HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getLocalHost(); config.setLocalAddress(localAddress); String method = servletRequest.getMethod(); HttpMethod m; if (method.equalsIgnoreCase("PUT")) { m = new PutMethod(proxyRequestUri); RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(), servletRequest.getContentType()); ((PutMethod) m).setRequestEntity(requestEntity); } else { m = new GetMethod(proxyRequestUri); } Enumeration<String> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String headerName = names.nextElement(); String value = servletRequest.getHeader(headerName); if (PASS_THROUGH_HEADERS.contains(headerName)) { //yarn does not send back the js if encoding is not accepted //but we don't want to accept encoding for the html because we //need to be able to parse it if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null || !servletRequest.getPathInfo().contains(".js"))) { continue; } else { m.setRequestHeader(headerName, value); } } } String user = servletRequest.getRemoteUser(); if (user != null && !user.isEmpty()) { m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII")); } client.executeMethod(config, m); // Process the response int statusCode = m.getStatusCode(); // Pass the response code. This method with the "reason phrase" is //deprecated but it's the only way to pass the reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase()); copyResponseHeaders(m, servletRequest, servletResponse); // Send the content to the client copyResponseEntity(m, servletResponse); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
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 ww w . j a v a 2s .co m // 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(); }