List of usage examples for javax.servlet.http HttpServletRequest getIntHeader
public int getIntHeader(String name);
int
. From source file:net.sf.j2ep.requesthandlers.MaxForwardRequestHandler.java
/** * Sets the headers and does some checking for if this request * is meant for the server or for the proxy. This check is done * by looking at the Max-Forwards header. * //from w w w .j av a 2 s .co m * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String) */ public HttpMethod process(HttpServletRequest request, String url) throws IOException { HttpMethodBase method = null; if (request.getMethod().equalsIgnoreCase("OPTIONS")) { method = new OptionsMethod(url); } else if (request.getMethod().equalsIgnoreCase("TRACE")) { method = new TraceMethod(url); } else { return null; } try { int max = request.getIntHeader("Max-Forwards"); if (max == 0 || request.getRequestURI().equals("*")) { setAllHeaders(method, request); method.abort(); } else if (max != -1) { setHeaders(method, request); method.setRequestHeader("Max-Forwards", "" + max--); } else { setHeaders(method, request); } } catch (NumberFormatException e) { } return method; }
From source file:com.zextras.zimbradrive.UploadFileHttpHandler.java
private HttpEntity createUploadFileRequest(HttpServletRequest httpServletRequest, String formBoundary, Account userAccount) throws IOException { InputStream userRequestInputStream = httpServletRequest.getInputStream(); String userInfoPartsString = createUserInfoInFormStyle(userAccount, formBoundary); String internalFormPartsBoundary = getInternalBodyBoundary(formBoundary); List<InputStream> payloadStreamToSendToDrive = Arrays.asList( new ByteArrayInputStream(userInfoPartsString.getBytes()), new ByteArrayInputStream(internalFormPartsBoundary.getBytes()), userRequestInputStream // TODO: This inputStreams will be closed? );//w w w. jav a 2 s. c om SequenceInputStream payloadToSendToDriveInputStream = new SequenceInputStream( Collections.enumeration(payloadStreamToSendToDrive)); int contentLength = httpServletRequest.getIntHeader(HTTP.CONTENT_LEN); int diffInternalFormPartsBoundaryAndFirstBodyBoundary = 2; // getFirstBodyBoundary(boundaryOfParts) - getInternalBodyBoundary(formBoundary) contentLength = contentLength + userInfoPartsString.length() + diffInternalFormPartsBoundaryAndFirstBodyBoundary; return new InputStreamEntity(payloadToSendToDriveInputStream, contentLength); }
From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java
/** * @param req/* ww w . j a va 2s. co m*/ * @param resp * @throws ServletException * @throws IOException */ public void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { System.out.println("================================="); String fileName = req.getHeader(HttpLargeFileTransfer.FILE_NAME_HEADER); if (fileName == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Filename not specified"); return; } String clientID = req.getHeader(HttpLargeFileTransfer.CLIENT_ID_HEADER); if (null == clientID) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Client ID"); return; } String serviceNumber = req.getHeader(HttpLargeFileTransfer.SERVICE_NUMBER); if (null == serviceNumber) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Service Number"); return; } String databaseName = StringUtils.replace(serviceNumber, ".", "_"); int numChunks = req.getIntHeader(HttpLargeFileTransfer.FILE_CHUNK_COUNT_HEADER); int chunkCnt = req.getIntHeader(HttpLargeFileTransfer.FILE_CHUNK_HEADER); if (numChunks == -1 || chunkCnt == -1) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing chunk information"); return; } if (chunkCnt == 0) { // check permission to create file here } OutputStream fos = null; if (numChunks == 1) { fos = new FileOutputStream(fileName); // create } else { fos = new FileOutputStream(getTempFile(clientID), (chunkCnt > 0)); // append } InputStream fis = req.getInputStream(); byte[] buf = new byte[BUFFER_SIZE]; int totalLen = 0; while (true) { int len = fis.read(buf); if (len > 0) { totalLen += len; fos.write(buf, 0, len); } else if (len == -1) { break; } } fis.close(); fos.close(); File destFile = new File(fileName); boolean isOK = true; if (numChunks > 1 && chunkCnt == numChunks - 1) { File tmpFile = new File(getTempFile(clientID)); if (destFile.exists()) { destFile.delete(); } if (!tmpFile.renameTo(destFile)) { isOK = false; resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to create file"); return; } } if (isOK) { String fullDestPath = destFile + ".sql"; if (uncompressFile(destFile.getAbsolutePath(), fullDestPath)) { //File newFile = new File(fullDestPath); databaseName = "db"; //System.out.println("Uncompressed:["+fullDestPath+"] size: ["+newFile.length()+"] database["+databaseName+"]"); MySQLBackupService backupService = new MySQLBackupService(); if (backupService.doRestore(fullDestPath, "/usr/local/mysql/bin/mysql", databaseName, "root", "root")) { resp.setStatus(HttpServletResponse.SC_OK); } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error restoring"); } } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error decompressing"); } }
From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java
private File getRequestBodyAsFile(HttpServletRequest req) throws IOException { if (this.m_requestBody == null) { this.m_requestBody = TempFileProvider.createTempFile("webdav_" + req.getMethod() + "_", ".bin"); OutputStream out = new FileOutputStream(this.m_requestBody); int bytesRead = FileCopyUtils.copy(req.getInputStream(), out); // ALF-7377: check for corrupt request int contentLength = req.getIntHeader(WebDAV.HEADER_CONTENT_LENGTH); if (contentLength >= 0 && contentLength != bytesRead) { throw new IOException("Request body does not have specified Content Length"); }//from ww w .jav a 2 s .com } return this.m_requestBody; }
From source file:org.apache.camel.component.websocket.SignalkWebSocketServlet.java
public void init() throws ServletException { try {/*from w ww. jav a 2s . c o m*/ String bs = getInitParameter("bufferSize"); if (logger.isDebugEnabled()) logger.debug("Upgrade ws, create factory:"); this._webSocketFactory = new WebSocketFactory(this, (bs == null) ? 8192 : Integer.parseInt(bs)) { private WebSocketBuffers _buffers = new WebSocketBuffers(8192); private Map<WebSocketServletConnection, String> sessionMap = new HashMap<WebSocketServletConnection, String>(); public void upgrade(HttpServletRequest request, HttpServletResponse response, WebSocket websocket, String protocol) throws IOException { String sessionId = request.getRequestedSessionId(); if (logger.isDebugEnabled()) logger.debug("Upgrade ws, requested sessionId:" + sessionId); if (StringUtils.isBlank(sessionId)) { sessionId = request.getSession().getId(); if (logger.isDebugEnabled()) logger.debug("Request.sessionId:" + sessionId); } if (StringUtils.isBlank(sessionId)) { sessionId = ((DefaultWebsocket) websocket).getConnectionKey(); if (logger.isDebugEnabled()) logger.debug("Request.wsSessionId:" + sessionId); } if (!("websocket".equalsIgnoreCase(request.getHeader("Upgrade")))) throw new IllegalStateException("!Upgrade:websocket"); if (!("HTTP/1.1".equals(request.getProtocol()))) { throw new IllegalStateException("!HTTP/1.1"); } int draft = request.getIntHeader("Sec-WebSocket-Version"); if (draft < 0) { draft = request.getIntHeader("Sec-WebSocket-Draft"); } int requestedVersion = draft; AbstractHttpConnection http = AbstractHttpConnection.getCurrentConnection(); if (http instanceof BlockingHttpConnection) throw new IllegalStateException("Websockets not supported on blocking connectors"); ConnectedEndPoint endp = (ConnectedEndPoint) http.getEndPoint(); List<String> extensions_requested = new ArrayList<>(); Enumeration<String> e = request.getHeaders("Sec-WebSocket-Extensions"); while (e.hasMoreElements()) { QuotedStringTokenizer tok = new QuotedStringTokenizer((String) e.nextElement(), ","); while (tok.hasMoreTokens()) { extensions_requested.add(tok.nextToken()); } } if (draft < getMinVersion()) draft = 2147483647; WebSocketServletConnection connection; switch (draft) { case -1: case 0: connection = new WebSocketServletConnectionD00(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol); break; case 1: case 2: case 3: case 4: case 5: case 6: connection = new WebSocketServletConnectionD06(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol); break; case 7: case 8: List<Extension> extensions = initExtensions(extensions_requested, 5, 5, 3); connection = new WebSocketServletConnectionD08(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions, draft); break; case 13: List<Extension> extensions1 = initExtensions(extensions_requested, 5, 5, 3); connection = new WebSocketServletConnectionRFC6455(this, websocket, endp, this._buffers, http.getTimeStamp(), (int) getMaxIdleTime(), protocol, extensions1, draft); break; case 9: case 10: case 11: case 12: default: String versions = "13"; if (getMinVersion() <= 8) versions = new StringBuilder().append(versions).append(", 8").toString(); if (getMinVersion() <= 6) versions = new StringBuilder().append(versions).append(", 6").toString(); if (getMinVersion() <= 0) { versions = new StringBuilder().append(versions).append(", 0").toString(); } response.setHeader("Sec-WebSocket-Version", versions); StringBuilder err = new StringBuilder(); err.append("Unsupported websocket client version specification "); if (requestedVersion >= 0) err.append("[").append(requestedVersion).append("]"); else { err.append("<Unspecified, likely a pre-draft version of websocket>"); } err.append(", configured minVersion [").append(getMinVersion()).append("]"); err.append(", reported supported versions [").append(versions).append("]"); // LOG.warn(err.toString(), new Object[0]); throw new HttpException(400, "Unsupported websocket version specification"); } addConnection(connection); connection.getConnection().setMaxBinaryMessageSize(getMaxBinaryMessageSize()); connection.getConnection().setMaxTextMessageSize(getMaxTextMessageSize()); connection.handshake(request, response, protocol); response.flushBuffer(); connection.fillBuffersFrom(((HttpParser) http.getParser()).getHeaderBuffer()); connection.fillBuffersFrom(((HttpParser) http.getParser()).getBodyBuffer()); String wsSession = ((DefaultWebsocket) websocket).getConnectionKey(); //if(logger.isDebugEnabled())logger.debug("Upgraded session " + request.getSession().getId() + " to ws " + ((DefaultWebsocket) websocket).getConnectionKey()); if (logger.isDebugEnabled()) logger.debug("Upgraded session " + sessionId + " to ws " + wsSession + " from remote ip:" + request.getRemoteAddr()); try { sessionMap.put(connection, wsSession); SubscriptionManagerFactory.getInstance().add(sessionId, wsSession, ConfigConstants.OUTPUT_WS, request.getLocalAddr(), request.getRemoteAddr()); //add default sub, or specific sub here, all instant policy String subscribe = request.getParameter("subscribe"); if (StringUtils.isBlank(subscribe) || "self".equals(subscribe)) { //subscribe to self String sub = "{\"context\":\"vessels.self\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}"; sendSub(request, sub, wsSession); } else if ("all".equals(subscribe)) { //subscribe to all String sub = "{\"context\":\"vessels.*\",\"subscribe\":[{\"path\":\"*\", \"policy\":\"instant\"}]}"; sendSub(request, sub, wsSession); } else if ("none".equals(subscribe)) { //subscribe to none - do nothing } } catch (Exception e1) { logger.error(e1.getMessage(), e1); throw new IOException(e1); } // LOG.debug("Websocket upgrade {} {} {} {}", new Object[] { request.getRequestURI(), Integer.valueOf(draft), protocol, connection }); request.setAttribute("org.eclipse.jetty.io.Connection", connection); connection.getConnection().sendMessage(Util.getWelcomeMsg().toString()); } private void sendSub(HttpServletRequest request, String sub, String wsSession) throws Exception { Map<String, Object> headers = new HashMap<>(); headers.put(MSG_SRC_IP, request.getRemoteAddr()); headers.put(MSG_SRC_IP_PORT, request.getRemotePort()); if (Util.sameNetwork(request.getLocalAddr(), request.getRemoteAddr())) { headers.put(MSG_TYPE, INTERNAL_IP); } else { headers.put(MSG_TYPE, EXTERNAL_IP); } headers.put(WebsocketConstants.CONNECTION_KEY, wsSession); if (logger.isDebugEnabled()) logger.debug("Sending connection sub:" + sub); producer.sendBodyAndHeaders(RouteManager.SEDA_INPUT, sub, headers); } @Override protected boolean removeConnection(WebSocketServletConnection connection) { //unsubscribe and remove websocket session String wsSession = sessionMap.get(connection); if (logger.isDebugEnabled()) logger.debug("Ended wsSession " + wsSession); try { SubscriptionManagerFactory.getInstance().removeWsSession(wsSession); } catch (Exception e1) { logger.error(e1.getMessage(), e1); } return super.removeConnection(connection); } }; this._webSocketFactory.setMaxTextMessageSize(256 * 1024); this._webSocketFactory.start(); String max = getInitParameter("maxIdleTime"); if (max != null) { this._webSocketFactory.setMaxIdleTime(Integer.parseInt(max)); } max = getInitParameter("maxTextMessageSize"); if (max != null) { this._webSocketFactory.setMaxTextMessageSize(Integer.parseInt(max)); } max = getInitParameter("maxBinaryMessageSize"); if (max != null) { this._webSocketFactory.setMaxBinaryMessageSize(Integer.parseInt(max)); } String min = getInitParameter("minVersion"); if (min != null) this._webSocketFactory.setMinVersion(Integer.parseInt(min)); } catch (ServletException x) { throw x; } catch (Exception x) { throw new ServletException(x); } }
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); }/*www. ja v a 2 s . c o m*/ 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:org.codehaus.wadi.web.impl.CommonsHttpProxy.java
protected void doProxy(URI uri, WebInvocation context) throws ProxyingException { HttpServletRequest hreq = context.getHreq(); HttpServletResponse hres = context.getHres(); long startTime = System.currentTimeMillis(); String m = hreq.getMethod();/*from ww w.j a va 2s .com*/ Class clazz = (Class) _methods.get(m); if (clazz == null) { throw new IrrecoverableException("unsupported http method: " + m); } HttpMethod hm = null; try { hm = (HttpMethod) clazz.newInstance(); } catch (Exception e) { throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen } String requestURI = getRequestURI(hreq); hm.setPath(requestURI); String queryString = hreq.getQueryString(); if (queryString != null) { hm.setQueryString(queryString); requestURI += queryString; } hm.setFollowRedirects(false); //hm.setURI(new URI(uri)); hm.setStrictMode(false); // check connection header String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ? if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; // TODO ?? } // copy headers boolean xForwardedFor = false; boolean hasContent = false; int contentLength = 0; Enumeration enm = hreq.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! - using javax.servlet ? String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) { try { contentLength = hreq.getIntHeader(hdr); hasContent = contentLength > 0; } catch (NumberFormatException e) { if (_log.isWarnEnabled()) _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e); } } if ("content-type".equals(lhdr)) { hasContent = true; } Enumeration vals = hreq.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { hm.addRequestHeader(hdr, val); // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ? } } } // cookies... // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending. // we have to explicitly use their interface to add the cookies - painful... // DOH! - an org.apache.commons.httpclient.Cookie is NOT a // javax.servlet.http.Cookie - and it looks like the two don't // map onto each other without data loss... HttpState state = new HttpState(); javax.servlet.http.Cookie[] cookies = hreq.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { javax.servlet.http.Cookie c = cookies[i]; String domain = c.getDomain(); if (domain == null) { domain = hreq.getServerName(); // TODO - tmp test // _log.warn("defaulting cookie domain"); } // domain=null; String cpath = c.getPath(); if (cpath == null) { cpath = hreq.getContextPath(); // fix for Jetty // _log.warn("defaulting cookie path"); } //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length())); Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure()); state.addCookie(cookie); //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString()); } } // Proxy headers hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\""); if (!xForwardedFor) hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr()); // Max-Forwards... // a little bit of cache control // String cache_control = hreq.getHeader("Cache-Control"); // if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) // httpMethod.setUseCaches(false); // customize Connection // uc.setDoInput(true); int client2ServerTotal = 0; if (hasContent) { // uc.setDoOutput(true); try { if (hm instanceof EntityEnclosingMethod) ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream()); // TODO - do we need to close response stream at end... ? } catch (IOException e) { throw new IrrecoverableException("could not pss request input across proxy", e); } } try { HttpClient client = new HttpClient(); HostConfiguration hc = new HostConfiguration(); //String host=location.getAddress().getHostAddress(); // inefficient - but stops httpclient from rejecting half our cookies... String host = uri.getHost(); hc.setHost(host, uri.getPort()); client.executeMethod(hc, hm, state); } catch (IOException e) // TODO { _log.warn("problem proxying connection:", e); } InputStream fromServer = null; // handler status codes etc. int code = 502; // String message="Bad Gateway: could not read server response code or message"; code = hm.getStatusCode(); // IOException // message=hm.getStatusText(); // IOException hres.setStatus(code); // hres.setStatus(code, message); - deprecated... try { fromServer = hm.getResponseBodyAsStream(); // IOException } catch (IOException e) { _log.warn("problem acquiring http client output", e); } // clear response defaults. hres.setHeader("Date", null); hres.setHeader("Server", null); // set response headers // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ? // Try this inside Tomcat... Header[] headers = hm.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { String h = headers[i].toExternalForm(); int index = h.indexOf(':'); String key = h.substring(0, index).trim().toLowerCase(); String val = h.substring(index + 1, h.length()).trim(); if (val != null && !_DontProxyHeaders.contains(key)) { hres.addHeader(key, val); // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val); } } hres.addHeader("Via", "1.1 (WADI)"); // copy server->client int server2ClientTotal = 0; if (fromServer != null) { try { OutputStream toClient = hres.getOutputStream();// IOException server2ClientTotal += copy(fromServer, toClient, 8192);// IOException } catch (IOException e) { _log.warn("problem proxying server response back to client", e); } finally { try { fromServer.close(); } catch (IOException e) { // well - we did our best... _log.warn("problem closing server response stream", e); } } } long endTime = System.currentTimeMillis(); long elapsed = endTime - startTime; if (_log.isDebugEnabled()) { _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:" + elapsed + ", uri:" + uri); } }
From source file:org.getobjects.servlets.WOServletRequest.java
protected void loadContentFromRequest(final HttpServletRequest _rq) { servLog.debug("loading content from Servlet request ..."); InputStream is = null;/*from ww w . j a va 2s . c o m*/ try { is = _rq.getInputStream(); } catch (IOException ioe) { // TODO: could be a real exception? we might need to compare content-len? servLog.warn("Could not acquire InputStream from Servlet", ioe); } if (is != null) this.loadContentFromStream(_rq.getIntHeader("content-length"), is); }
From source file:org.infoscoop.web.MultiRssServlet.java
private void mergeRssAnd2JSON(HttpServletRequest request, HttpServletResponse response, String uid, String widgetId, int pageSize, NodeList urlList) throws Exception { try {/*from w w w . jav a 2 s .com*/ RssJsonResultBuilder resultBuilder = new SortedRssJsonResultBuilder(pageSize); String dateTimeFormat = request.getHeader("X-IS-DATETIMEFORMAT"); if (dateTimeFormat != null) { dateTimeFormat = URLDecoder.decode(dateTimeFormat, "UTF-8"); } String freshTime = request.getHeader("X-IS-FRESHTIME"); String maxCountString = request.getHeader("X-IS-RSSMAXCOUNT"); int maxCount = 1000; if (maxCountString != null) { try { int paramMaxCount = Integer.parseInt(maxCountString); if (paramMaxCount >= 0) { maxCount = paramMaxCount; } } catch (NumberFormatException e) { log.warn("rssmaxcount \"" + maxCountString + "\" isn't integer value."); } } // Norrowing String titleFilter = request.getHeader("X-IS-TITLEFILTER"); if (titleFilter != null) titleFilter = URLDecoder.decode(titleFilter, "UTF-8"); String creatorFilter = request.getHeader("X-IS-CREATORFILTER"); if (creatorFilter != null) creatorFilter = URLDecoder.decode(creatorFilter, "UTF-8"); String categoryFilter = request.getHeader("X-IS-CATEGORYFILTER"); if (categoryFilter != null) categoryFilter = URLDecoder.decode(categoryFilter, "UTF-8"); int DEFAULT_TIMEOUT = 15 * 1000; boolean modified = false; Map cacheHeaders = new HashMap(); Map errorMap = new HashMap(); List siteCacheHeaders = new ArrayList(); for (int i = 0; i < urlList.getLength(); i++) { Element rssEl = (Element) urlList.item(i); String url = rssEl.getAttribute("url"); ProxyRequest proxyRequest = new ProxyRequest(url, "NoOperation"); proxyRequest.setLocales(request.getLocales()); proxyRequest.setPortalUid(uid); int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000; proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT); //proxyRequest.setTimeout(timeout); proxyRequest.addIgnoreHeader("user-agent"); proxyRequest.addIgnoreHeader("X-IS-DATETIMEFORMAT"); proxyRequest.addIgnoreHeader("X-IS-FRESHTIME"); proxyRequest.addIgnoreHeader("X-IS-REFRESH"); proxyRequest.addIgnoreHeader("X-IS-RSSMAXCOUNT"); proxyRequest.addIgnoreHeader("X-IS-PAGESIZE"); Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); proxyRequest.putRequestHeader(headerName, request.getHeader(headerName)); } NodeList rssChildNodes = rssEl.getElementsByTagName("header"); for (int j = 0; j < rssChildNodes.getLength(); j++) { Element header = (Element) rssChildNodes.item(j); if (header.getFirstChild() != null) { String name = header.getAttribute("name"); String value = header.getFirstChild().getNodeValue(); if (name == null || name.trim().length() == 0 || value == null || value.trim().length() == 0) continue; proxyRequest.putRequestHeader(name, value); } } int statusCode = 0; String methodType = rssEl.getAttribute("method"); try { if ("post".equals(methodType)) { statusCode = proxyRequest.executePost(); } else { statusCode = proxyRequest.executeGet(); } } catch (SocketTimeoutException ex) { log.error("url: [" + url + "] socket timeout.", ex); errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_TIMEOUT)); } catch (ConnectTimeoutException ex) { log.error("url: [" + url + "] connection timeout.", ex); errorMap.put(url, new Integer(500)); } catch (SocketException ex) { log.error("url: [" + url + "] socket error.", ex); errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND)); } catch (IOException ex) { log.error("url: [" + url + "] I/O error.", ex); errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND)); } catch (Exception ex) { log.error("url: [" + url + "]" + ex.getMessage(), ex); errorMap.put(url, new Integer(500)); } BufferedInputStream bis = null; if (errorMap.containsKey(url)) { // nothing } else if (statusCode == 204) { log.warn("url:[" + url + "] is no content #" + statusCode); modified = true; } else if (statusCode == 304) { log.warn("url:[" + url + "] is not modified #" + statusCode); } else if (statusCode != 200) { log.error("url:[" + url + "] had error status code #" + statusCode); errorMap.put(url, new Integer(statusCode)); } else { log.info("url:[" + url + "] is succed #" + statusCode); try { modified = true; bis = new BufferedInputStream(proxyRequest.getResponseBody()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[10240]; int c; while ((c = bis.read(buf)) != -1) { baos.write(buf, 0, c); baos.flush(); } bis.close(); byte[] data = baos.toByteArray(); baos.close(); //RssCacheDAO.newInstance().insertCache(uid, widgetId+url, -1,data ); Map responseHeaders = proxyRequest.getResponseHeaders(); String lastModifiedName = "Last-Modified".toLowerCase(); if (responseHeaders.containsKey(lastModifiedName)) { siteCacheHeaders.add(lastModifiedName); siteCacheHeaders.add(responseHeaders.get(lastModifiedName)); } String etagName = "ETag".toLowerCase(); if (responseHeaders.containsKey(etagName)) { siteCacheHeaders.add(etagName); siteCacheHeaders.add(responseHeaders.get(etagName)); } if (siteCacheHeaders.size() > 0) { cacheHeaders.put(url, siteCacheHeaders.toArray()); siteCacheHeaders.clear(); } bis = new BufferedInputStream(new ByteArrayInputStream(data)); } catch (IOException ex) { log.error("rss reading " + url + " is failed.", ex); cacheHeaders.remove(url); errorMap.put(url, new Integer(500)); bis.close(); bis = null; } } if (bis == null) continue; RssHandler handler; boolean isAtom = RssFilter.isAtom(bis); XMLFilter.skipEmptyLine(bis); if (isAtom) { handler = new AtomHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter, creatorFilter, categoryFilter, i); } else { handler = new RssHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter, creatorFilter, categoryFilter, i); } try { XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setEntityResolver(NoOpEntityResolver.getInstance()); reader.setContentHandler(handler); reader.parse(new InputSource(bis)); } catch (SAXException e) { log.info("Parsing rss " + url + " is failed.", e); cacheHeaders.remove(url); errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_CONTENT_PARSE_ERROR)); } } if (!modified && errorMap.isEmpty()) { log.warn("multi rss is not modified."); response.setStatus(304); return; } else { try { long freshTimeLong = new Date().getTime(); if (freshTime != null) freshTimeLong = Long.parseLong(freshTime.trim()); setOldData(resultBuilder, uid, widgetId, freshTimeLong, titleFilter, creatorFilter, categoryFilter); } catch (NumberFormatException e) { log.error("", e); } //} int pageCount = resultBuilder.getPageCount(); // We create the result cash by all means. //if( pageCount > 1 ) { for (int pageNum = 0; pageNum < pageCount; pageNum++) { RssCacheDAO.newInstance().insertCache(uid, widgetId, pageNum, resultBuilder.getResult(pageNum)); } //} } response.addHeader("Content-Type", "text/plain; charset=UTF-8"); String result = resultBuilder.getResult(); if (!errorMap.isEmpty()) { JSONObject errors = new JSONObject(errorMap); result = "{errors:" + errors.toString() + "," + result.substring(result.indexOf("{") + 1); } if (!cacheHeaders.isEmpty()) { StringBuffer cacheHeadersBuf = new StringBuffer(); cacheHeadersBuf.append("cacheHeaders : {"); for (Iterator keys = cacheHeaders.keySet().iterator(); keys.hasNext();) { String url = (String) keys.next(); Object[] headers = (Object[]) cacheHeaders.get(url); cacheHeadersBuf.append("\"").append(url).append("\" : {"); for (int i = 0; i < headers.length; i += 2) { cacheHeadersBuf.append("\"").append(headers[i]).append("\""); cacheHeadersBuf.append(" : '").append(headers[i + 1]).append("'"); if (i + 2 < headers.length) cacheHeadersBuf.append(","); } cacheHeadersBuf.append("}"); if (keys.hasNext()) cacheHeadersBuf.append(","); } cacheHeadersBuf.append("}"); result = "{" + cacheHeadersBuf.toString() + "," + result.substring(result.indexOf("{") + 1); } response.setContentLength(result.getBytes("UTF-8").length); OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); try { out.write(result); out.flush(); } catch (SocketException ex) { // ignore client abort exception } finally { if (out != null) { try { out.close(); } catch (IOException ex) { // ignore } } } } catch (Exception e) { log.error("unexpected error occurred.", e); response.sendError(500, e.getMessage()); } }