List of usage examples for javax.servlet ServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:com.sg.rest.filters.LoggerFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString()); throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST); }//from www .ja v a 2 s . c o m HttpServletRequest httpRequest = (HttpServletRequest) request; StringBuilder sb = new StringBuilder(); //General header sb.append(System.lineSeparator()); sb.append(INCOMING_REQUEST); //Request url sb.append(System.lineSeparator()); sb.append(REQUEST_URL); sb.append(httpRequest.getRequestURL()); //Method sb.append(System.lineSeparator()); sb.append(METHOD); sb.append(httpRequest.getMethod()); //Parameters if (httpRequest.getParameterNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(PARAMETERS); Enumeration enParams = httpRequest.getParameterNames(); while (enParams.hasMoreElements()) { sb.append(System.lineSeparator()); String paramName = (String) enParams.nextElement(); sb.append(paramName); sb.append(" : "); sb.append(httpRequest.getParameter(paramName)); } } //Attributes if (httpRequest.getAttributeNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(ATTRIBUTES); Enumeration enAttribs = httpRequest.getAttributeNames(); while (enAttribs.hasMoreElements()) { sb.append(System.lineSeparator()); String attribName = (String) enAttribs.nextElement(); sb.append(attribName); sb.append(" : "); sb.append(httpRequest.getAttribute(attribName)); } } //Headers if (httpRequest.getHeaderNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(HEADERS); Enumeration enHeaders = httpRequest.getHeaderNames(); while (enHeaders.hasMoreElements()) { sb.append(System.lineSeparator()); String headerName = (String) enHeaders.nextElement(); sb.append(headerName); sb.append(" : "); sb.append(httpRequest.getHeader(headerName)); } } //AuthType if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) { sb.append(System.lineSeparator()); sb.append(AUTH_TYPE); sb.append(httpRequest.getAuthType()); } //Cookies if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) { sb.append(System.lineSeparator()); sb.append(COOKIES); for (Cookie cookie : httpRequest.getCookies()) { sb.append(System.lineSeparator()); sb.append(cookie.getName()); sb.append(" : "); sb.append(cookie.getValue()); } } //RemoteAddr if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_ADDR); sb.append(httpRequest.getRemoteAddr()); } //RemoteHost if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_HOST); sb.append(httpRequest.getRemoteHost()); } //User principal if (httpRequest.getUserPrincipal() != null) { if (httpRequest.getUserPrincipal().getName() != null && !httpRequest.getUserPrincipal().getName().isEmpty()) { sb.append(System.lineSeparator()); sb.append(PRINCIPAL); sb.append(httpRequest.getUserPrincipal().getName()); } } //Body ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest( (HttpServletRequest) request); String body = IOUtils.toString(wrappedRequest.getReader()); if (body != null && !body.isEmpty()) { sb.append(System.lineSeparator()); sb.append(BODY); sb.append(System.lineSeparator()); sb.append(body); } wrappedRequest.resetInputStream(); LOGGER.info(sb.toString()); chain.doFilter(wrappedRequest, response); }
From source file:com.keithhutton.ws.proxy.ProxyServlet.java
private XmlRpcRequest getMethodAndParamsFromRequest(ServletRequest req) throws XmlRpcException { final XmlRpcStreamRequestConfig pConfig = getConfig((HttpServletRequest) req); final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory()); final XMLReader xr = SAXParsers.newXMLReader(); xr.setContentHandler(parser);/*from w w w . j a v a2s.c om*/ try { xr.parse(new InputSource(req.getInputStream())); } catch (SAXException e) { Exception ex = e.getException(); if (ex != null && ex instanceof XmlRpcException) { throw (XmlRpcException) ex; } throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e); } catch (IOException e) { throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e); } final List params = parser.getParams(); final int paramCount = params == null ? 0 : params.size(); XmlRpcRequest xmlRpcRequest = new XmlRpcRequest() { public XmlRpcRequestConfig getConfig() { return pConfig; } public String getMethodName() { return parser.getMethodName(); } public int getParameterCount() { return params == null ? 0 : params.size(); } public Object getParameter(int pIndex) { return paramCount > 0 ? params.get(pIndex) : null; } }; this.log.info("xmlRpcRequest method = " + xmlRpcRequest.getMethodName()); this.log.info("xmlRpcRequest pcount = " + xmlRpcRequest.getParameterCount()); this.log.info("xmlRpcRequest param1 = " + xmlRpcRequest.getParameter(0)); return xmlRpcRequest; }
From source file:com.arvato.thoroughly.filter.AccessLogFilter.java
@Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws ServletException, IOException { ServletRequest requestWrapper = arg0; try {/*w ww . ja v a 2 s .c om*/ final HttpServletRequest request = (HttpServletRequest) arg0; final String username = request.getRemoteUser(); LOGGER.trace("Username : " + username); final String ip = HttpHelper.getIpAddress(request); LOGGER.trace("Client ip is : " + ip); final StringBuffer URL = request.getRequestURL(); LOGGER.trace("URL of the client request is : " + URL.toString()); requestWrapper = new FilterRequestWrapper(request); String body = IOUtils.toString(requestWrapper.getInputStream()); LOGGER.trace("Request body is : " + body); } catch (Exception e) { LOGGER.error("An error occurred inside AccessLogFilter:" + e.getMessage()); } chain.doFilter(requestWrapper, arg1); }
From source file:net.lightbody.bmp.proxy.jetty.servlet.MultiPartFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *//*w w w . jav a 2s . co m*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest srequest = (HttpServletRequest) request; if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) { chain.doFilter(request, response); return; } LineInput in = new LineInput(request.getInputStream()); String content_type = srequest.getContentType(); String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary="))); byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1); MultiMap params = new MultiMap(); // Get first boundary String line = in.readLine(); if (!line.equals(boundary)) { log.warn(line); throw new IOException("Missing initial multi part boundary"); } // Read each part boolean lastPart = false; String content_disposition = null; while (!lastPart) { while ((line = in.readLine()) != null) { // If blank line, end of part headers if (line.length() == 0) break; // place part header key and value in map int c = line.indexOf(':', 0); if (c > 0) { String key = line.substring(0, c).trim().toLowerCase(); String value = line.substring(c + 1, line.length()).trim(); if (key.equals("content-disposition")) content_disposition = value; } } // Extract content-disposition boolean form_data = false; if (content_disposition == null) { throw new IOException("Missing content-disposition"); } StringTokenizer tok = new StringTokenizer(content_disposition, ";"); String name = null; String filename = null; while (tok.hasMoreTokens()) { String t = tok.nextToken().trim(); String tl = t.toLowerCase(); if (t.startsWith("form-data")) form_data = true; else if (tl.startsWith("name=")) name = value(t); else if (tl.startsWith("filename=")) filename = value(t); } // Check disposition if (!form_data) { log.warn("Non form-data part in multipart/form-data"); continue; } if (name == null || name.length() == 0) { log.warn("Part with no name in multipart/form-data"); continue; } OutputStream out = null; File file = null; try { if (filename != null && filename.length() > 0) { file = File.createTempFile("MultiPart", "", tempdir); out = new FileOutputStream(file); request.setAttribute(name, file); params.put(name, filename); } else out = new ByteArrayOutputStream(); int state = -2; int c; boolean cr = false; boolean lf = false; // loop for all lines` while (true) { int b = 0; while ((c = (state != -2) ? state : in.read()) != -1) { state = -2; // look for CR and/or LF if (c == 13 || c == 10) { if (c == 13) state = in.read(); break; } // look for boundary if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b]) b++; else { // this is not a boundary if (cr) out.write(13); if (lf) out.write(10); cr = lf = false; if (b > 0) out.write(byteBoundary, 0, b); b = -1; out.write(c); } } // check partial boundary if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) { if (cr) out.write(13); if (lf) out.write(10); cr = lf = false; out.write(byteBoundary, 0, b); b = -1; } // boundary match if (b > 0 || c == -1) { if (b == byteBoundary.length) lastPart = true; if (state == 10) state = -2; break; } // handle CR LF if (cr) out.write(13); if (lf) out.write(10); cr = (c == 13); lf = (c == 10 || state == 10); if (state == 10) state = -2; } } finally { IO.close(out); } if (file == null) { byte[] bytes = ((ByteArrayOutputStream) out).toByteArray(); params.add(name, bytes); } } chain.doFilter(new Wrapper(srequest, params), response); // TODO delete the files if they still exist. }
From source file:org.commoncrawl.service.listcrawler.MultiPartFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) *//* w ww . ja va2 s. c o m*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { LOG.info("Hit doFilter"); HttpServletRequest srequest = (HttpServletRequest) request; if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) { LOG.info(srequest.toString()); LOG.info("Rejecting. Invalid mime type:" + srequest.getContentType()); chain.doFilter(request, response); return; } LOG.info("OK Looks Good So Far"); BufferedInputStream in = new BufferedInputStream(request.getInputStream()); String content_type = srequest.getContentType(); // TODO - handle encodings String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary="))); byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1); MultiMap params = new MultiMap(); try { // Get first boundary byte[] bytes = TypeUtil.readLine(in); String line = bytes == null ? null : new String(bytes, "UTF-8"); if (line == null || !line.equals(boundary)) { throw new IOException("Missing initial multi part boundary"); } // Read each part boolean lastPart = false; String content_disposition = null; String file_content_type = null; while (!lastPart) { while (true) { bytes = TypeUtil.readLine(in); // If blank line, end of part headers if (bytes == null || bytes.length == 0) break; line = new String(bytes, "UTF-8"); // place part header key and value in map int c = line.indexOf(':', 0); if (c > 0) { String key = line.substring(0, c).trim().toLowerCase(); String value = line.substring(c + 1, line.length()).trim(); if (key.equals("content-disposition")) content_disposition = value; else if (key.equals("content-type")) file_content_type = value; } } // Extract content-disposition boolean form_data = false; if (content_disposition == null) { throw new IOException("Missing content-disposition"); } StringTokenizer tok = new StringTokenizer(content_disposition, ";"); String name = null; String filename = null; while (tok.hasMoreTokens()) { String t = tok.nextToken().trim(); String tl = t.toLowerCase(); if (t.startsWith("form-data")) form_data = true; else if (tl.startsWith("name=")) name = value(t); else if (tl.startsWith("filename=")) filename = value(t); } // Check disposition if (!form_data) { continue; } if (name == null || name.length() == 0) { continue; } OutputStream out = null; File file = null; try { if (filename != null && filename.length() > 0) { file = File.createTempFile("MultiPart", "", tempdir); LOG.info("Got FileName:" + filename + " Creating Temp File:" + file); out = new FileOutputStream(file); UploadFileData uploadData = new UploadFileData(); uploadData.fieldName = name; uploadData.incomingFile = file; uploadData.incomingFilename = filename; uploadData.incomingContentType = file_content_type; request.setAttribute(name, uploadData); params.put(name, filename); if (_deleteFiles) { //file.deleteOnExit(); ArrayList<UploadFileData> files = (ArrayList<UploadFileData>) request .getAttribute(FILES); if (files == null) { files = new ArrayList<UploadFileData>(); request.setAttribute(FILES, files); } files.add(uploadData); } } else out = new ByteArrayOutputStream(); int state = -2; int c; boolean cr = false; boolean lf = false; // loop for all lines` while (true) { int b = 0; while ((c = (state != -2) ? state : in.read()) != -1) { state = -2; // look for CR and/or LF if (c == 13 || c == 10) { if (c == 13) state = in.read(); break; } // look for boundary if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b]) b++; else { // this is not a boundary if (cr) out.write(13); if (lf) out.write(10); cr = lf = false; if (b > 0) out.write(byteBoundary, 0, b); b = -1; out.write(c); } } // check partial boundary if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) { if (cr) out.write(13); if (lf) out.write(10); cr = lf = false; out.write(byteBoundary, 0, b); b = -1; } // boundary match if (b > 0 || c == -1) { if (b == byteBoundary.length) lastPart = true; if (state == 10) state = -2; break; } // handle CR LF if (cr) out.write(13); if (lf) out.write(10); cr = (c == 13); lf = (c == 10 || state == 10); if (state == 10) state = -2; } } finally { if (out != null) { out.close(); } } if (file == null) { bytes = ((ByteArrayOutputStream) out).toByteArray(); params.add(name, bytes); } } // handle request chain.doFilter(new Wrapper(srequest, params), response); } catch (IOException e) { LOG.error("###Exception In Multipart:" + CCStringUtils.stringifyException(e)); throw e; } finally { LOG.info("Deleting Files Here"); deleteFiles(request); } }
From source file:org.webdavaccess.servlet.WebdavServlet.java
/** * overwrites propNode and type, parsed from xml input stream * //from www .j a v a 2 s. com * @param propNode * @param type * @param req * HttpServletRequest * @throws ServletException */ private PropertyNodeType getPropertyNodeAndType(ServletRequest req) throws ServletException { PropertyNodeType nodeType = new PropertyNodeType(FIND_ALL_PROP); if (req.getContentLength() != 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { nodeType.setType(FIND_BY_PROPERTY); nodeType.setNode(currentNode); } if (currentNode.getNodeName().endsWith("propname")) { nodeType.setType(FIND_PROPERTY_NAMES); } if (currentNode.getNodeName().endsWith("allprop")) { nodeType.setType(FIND_ALL_PROP); } break; } } } catch (Exception e) { } } else { // no content, which means it is a allprop request nodeType.setType(FIND_ALL_PROP); } return nodeType; }
From source file:org.webdavaccess.servlet.WebdavServlet.java
/** * Gets properties to be set from request * /*from w w w . j a va 2 s. c o m*/ * @param req * @return Properties * @throws ServletException */ private Properties[] getPropertiesToSetOrRemove(ServletRequest req) throws ServletException { Properties[] props = new Properties[] { new Properties(), new Properties() }; if (req.getContentLength() == 0) return props; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.ELEMENT_NODE: if ("set".equals(currentNode.getLocalName())) { NodeList propList = currentNode.getChildNodes(); for (int j = 0; j < propList.getLength(); j++) { Node propNode = propList.item(j); if ("prop".equals(propNode.getLocalName())) { NodeList propNodes = propNode.getChildNodes(); for (int k = 0; k < propNodes.getLength(); k++) { Node node = propNodes.item(k); String pname = node.getNodeName(); if (pname == null || pname.trim().length() == 0) continue; String value = node.getTextContent(); props[0].setProperty(pname, value); } } } } else if ("remove".equals(currentNode.getLocalName())) { NodeList propList = currentNode.getChildNodes(); for (int j = 0; j < propList.getLength(); j++) { Node propNode = propList.item(j); if ("prop".equals(propNode.getLocalName())) { NodeList propNodes = propNode.getChildNodes(); for (int k = 0; k < propNodes.getLength(); k++) { Node node = propNodes.item(k); String pname = node.getNodeName(); if (pname == null || pname.trim().length() == 0) continue; String value = node.getTextContent(); props[1].setProperty(pname, value); } } } } break; case Node.TEXT_NODE: default: break; } } } catch (Exception e) { throw new ServletException("Unable to parse properties set/remove request"); } return props; }
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
private ConstraintSecurityHandler createSecurityHandler(Handler handler) throws Exception { final Authenticator authenticator = authenticatorProvider.getAuthenticator(); final String authMethod; switch (authProps.getAuthType()) { case BASIC:/*from w w w . ja v a 2 s .c o m*/ authMethod = Constraint.__BASIC_AUTH; break; case DIGEST: authMethod = Constraint.__DIGEST_AUTH; break; default: authMethod = "customauth"; } Constraint constraint = new Constraint(); constraint.setName(authMethod); constraint.setRoles(new String[] { "user" }); constraint.setAuthenticate(true); ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setAuthenticator(new org.eclipse.jetty.security.Authenticator() { @Override public void setConfiguration(AuthConfiguration configuration) { } @Override public String getAuthMethod() { return authMethod; } @Override public void prepareRequest(ServletRequest request) { } @Override public Authentication validateRequest(final ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String remoteAddress = StringUtils.trimToEmpty(request.getRemoteAddr()); int remotePort = request.getRemotePort(); String localAddress = StringUtils.trimToEmpty(request.getLocalAddr()); int localPort = request.getLocalPort(); String protocol = StringUtils.trimToEmpty(request.getProtocol()); String method = StringUtils.trimToEmpty(request.getMethod()); String requestURI = StringUtils.trimToEmpty(request.getRequestURI()); Map<String, List<String>> headers = HttpMessageConverter.convertFieldEnumerationToMap(request); Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>(); for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) { queryParameters.put(entry.getKey(), Arrays.asList(entry.getValue())); } EntityProvider entityProvider = new EntityProvider() { @Override public byte[] getEntity() throws IOException { byte[] entity = (byte[]) req.getAttribute(ATTRIBUTE_NAME); if (entity == null) { entity = IOUtils.toByteArray(req.getInputStream()); req.setAttribute(ATTRIBUTE_NAME, entity); } return entity; } }; RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort, protocol, method, requestURI, headers, queryParameters, entityProvider, configuration.getRequestInformation(request)); try { AuthenticationResult result = authenticator.authenticate(requestInfo); for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) { if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) { for (int i = 0; i < entry.getValue().size(); i++) { if (i == 0) { response.setHeader(entry.getKey(), entry.getValue().get(i)); } else { response.addHeader(entry.getKey(), entry.getValue().get(i)); } } } } switch (result.getStatus()) { case CHALLENGED: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_CONTINUE; case SUCCESS: Principal userPrincipal = new KnownUser(StringUtils.trimToEmpty(result.getUsername()), null); Subject subject = new Subject(); subject.getPrincipals().add(userPrincipal); return new UserAuthentication(getAuthMethod(), new DefaultUserIdentity(subject, userPrincipal, new String[] { "user" })); case FAILURE: default: response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return org.eclipse.jetty.server.Authentication.SEND_FAILURE; } } catch (Throwable t) { logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " (" + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t); eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null, ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(), "Error in HTTP authentication for " + connectorProperties.getName(), t)); throw new ServerAuthException(t); } } @Override public boolean secureResponse(ServletRequest request, ServletResponse response, boolean mandatory, User validatedUser) throws ServerAuthException { return true; } }); securityHandler.addConstraintMapping(constraintMapping); securityHandler.setHandler(handler); return securityHandler; }
From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { chain.doFilter(req, res);// w w w . java 2 s .co m return; } HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; if (httpRequest.getMethod().equals("OPTIONS")) { chain.doFilter(req, res); return; } String uri = httpRequest.getRequestURI(); for (Pattern pattern : endpointBlacklistRegex) { if (pattern.matcher(uri).matches()) { chain.doFilter(req, res); return; } } String informat = getInformat(httpRequest); String outformat = getOutformat(httpRequest); if (outformat != null && (informat == null || !outformat.equals(informat))) { Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat + "\" when informat is also \"" + outformat + "\""); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (outformat != null && !outputFormats.contains(outformat)) { Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format"); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (informat == null) { chain.doFilter(req, res); return; } boolean roundtripping = false; if (outformat != null) { roundtripping = true; logger.debug("convert from " + informat + " to " + outformat); } else { logger.debug("convert input from " + informat + " to nif"); } // do conversion of informat to nif // create BodySwappingServletRequest String inputQueryString = req.getParameter("input"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream requestInputStream = inputQueryString == null ? /* * read * data * from * request * body */req.getInputStream() : /* * read data from query string input * parameter */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) { // copy request content to buffer IOUtils.copy(requestInputStream, baos); } // create request wrapper that converts the body of the request from the // original format to turtle Reader nif; byte[] baosData = baos.toByteArray(); if (baosData.length == 0) { Exception exception = new BadRequestException("No input data found in request."); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } ByteArrayInputStream bais = new ByteArrayInputStream(baosData); try { nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase()); } catch (ConversionException e) { logger.error("Error", e); throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed"); } BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif, roundtripping); if (!roundtripping) { chain.doFilter(bssr, res); return; } ConversionHttpServletResponseWrapper dummyResponse; try { dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi, new ByteArrayInputStream(baosData), informat, outformat); chain.doFilter(bssr, dummyResponse); ServletOutputStream sos = httpResponse.getOutputStream(); byte[] data = dummyResponse.writeBackToClient(); httpResponse.setContentLength(data.length); sos.write(data); sos.flush(); sos.close(); } catch (ConversionException e) { e.printStackTrace(); // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new // InternalServerErrorException()); } }