List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:org.duracloud.common.rest.RestUtilImpl.java
/** * Retrieves the contents of the HTTP Request. * * @return InputStream from the request//from www. ja v a 2 s. co m */ @Override public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception { RequestContent rContent = null; // See if the request is a multi-part file upload request if (ServletFileUpload.isMultipartContent(request)) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, use the first available File item FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { rContent = new RequestContent(); rContent.contentStream = item.openStream(); rContent.mimeType = item.getContentType(); FileItemHeaders itemHeaders = item.getHeaders(); if (itemHeaders != null) { String contentLength = itemHeaders.getHeader("Content-Length"); if (contentLength != null) { rContent.size = Long.parseLong(contentLength); } } break; } } } else { // If the content stream was not found as a multipart, // try to use the stream from the request directly rContent = new RequestContent(); rContent.contentStream = request.getInputStream(); if (request.getContentLength() >= 0) { rContent.size = request.getContentLength(); } } // Attempt to set the mime type and size if not already set if (rContent != null) { if (rContent.mimeType == null) { MediaType mediaType = headers.getMediaType(); if (mediaType != null) { rContent.mimeType = mediaType.toString(); } } if (rContent.size == 0) { List<String> lengthHeaders = headers.getRequestHeader("Content-Length"); if (lengthHeaders != null && lengthHeaders.size() > 0) { rContent.size = Long.parseLong(lengthHeaders.get(0)); } } } return rContent; }
From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java
/** * {@inheritDoc}/*w w w .j ava 2 s . co m*/ */ public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad // happened, Upload // should be able to // take care of most // stuff String p = new String(req.getPathInfo().getBytes("ISO-8859-1"), "UTF-8"); DavPath path = new DavPath(p); try { InputStream data = req.getInputStream(); WikiContext context = m_engine.createContext(req, WikiContext.UPLOAD); String wikipage = path.get(0); errorPage = context.getURL(WikiContext.UPLOAD, wikipage); String changeNote = null; // FIXME: Does not quite work boolean created = executeUpload(context, data, path.getName(), errorPage, wikipage, changeNote, req.getContentLength()); if (created) { res.sendError(HttpServletResponse.SC_CREATED); } else { res.sendError(HttpServletResponse.SC_OK); } } catch (ProviderException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (RedirectException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.red5.server.net.rtmpt.RTMPTServlet.java
/** * Start a new RTMPT session.//from ww w. j a v a 2 s . com * * @param req * Servlet request * @param resp * Servlet response * @throws IOException * I/O exception */ protected void handleOpen(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.debug("handleOpen"); // skip sent data skipData(req); // TODO: should we evaluate the pathinfo? RTMPTConnection conn = (RTMPTConnection) manager.createConnection(RTMPTConnection.class); log.trace("{}", conn); if (conn != null) { // set properties conn.setServlet(this); conn.setServletRequest(req); // add the connection to the manager manager.setConnection(conn); // set handler conn.setHandler(handler); conn.setDecoder(handler.getCodecFactory().getRTMPDecoder()); conn.setEncoder(handler.getCodecFactory().getRTMPEncoder()); handler.connectionOpened(conn); conn.dataReceived(); conn.updateReadBytes(req.getContentLength()); // set thread local reference Red5.setConnectionLocal(conn); if (conn.getId() != 0) { // return session id to client returnMessage(String.format("%s\n", conn.getSessionId()), resp); } else { // no more clients are available for serving returnMessage((byte) 0, resp); } } else { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.setHeader("Connection", "Keep-Alive"); resp.setHeader("Cache-Control", "no-cache"); resp.flushBuffer(); } }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
/** * TODO: add same functionality & checks as in HTTPDemon.parseMultipart * * parse multi-part form data for formfields, see also original * implementation in HTTPDemon.parseMultipart * * For file data the parameter for the formfield contains the filename and a * additional parameter with appendix [fieldname]$file conteins the upload content * (e.g. <input type="file" name="upload"> upload="local/filename" upload$file=[content]) * * @param request/* w w w. ja va 2 s . co m*/ * @param args found fields/values are added to the map */ protected void parseMultipart(final HttpServletRequest request, final serverObjects args) throws IOException { // reject too large uploads if (request.getContentLength() > SIZE_FILE_THRESHOLD) throw new IOException("FileUploadException: uploaded file too large = " + request.getContentLength()); // check if we have enough memory if (!MemoryControl.request(request.getContentLength() * 3, false)) { throw new IOException("not enough memory available for request. request.getContentLength() = " + request.getContentLength() + ", MemoryControl.available() = " + MemoryControl.available()); } ServletFileUpload upload = new ServletFileUpload(DISK_FILE_ITEM_FACTORY); upload.setFileSizeMax(SIZE_FILE_THRESHOLD); try { // Parse the request to get form field items List<FileItem> fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator<FileItem> i = fileItems.iterator(); final BlockingQueue<Map.Entry<String, byte[]>> files = new LinkedBlockingQueue<>(); while (i.hasNext()) { FileItem item = i.next(); if (item.isFormField()) { // simple text if (item.getContentType() == null || !item.getContentType().contains("charset")) { // old yacy clients use their local default charset, on most systems UTF-8 (I hope ;) args.add(item.getFieldName(), item.getString(StandardCharsets.UTF_8.name())); } else { // use default encoding (given as header or ISO-8859-1) args.add(item.getFieldName(), item.getString()); } } else { // read file upload args.add(item.getFieldName(), item.getName()); // add the filename to the parameters InputStream filecontent = null; try { filecontent = item.getInputStream(); files.put(new AbstractMap.SimpleEntry<String, byte[]>(item.getFieldName(), FileUtils.read(filecontent))); } catch (IOException e) { ConcurrentLog.info("FILEHANDLER", e.getMessage()); } finally { if (filecontent != null) try { filecontent.close(); } catch (IOException e) { ConcurrentLog.info("FILEHANDLER", e.getMessage()); } } } } if (files.size() <= 1) { // TODO: should include additonal checks to limit parameter.size below rel. large SIZE_FILE_THRESHOLD for (Map.Entry<String, byte[]> job : files) { // add the file content to parameter fieldname$file String n = job.getKey(); byte[] v = job.getValue(); String filename = args.get(n); if (filename != null && filename.endsWith(".gz")) { // transform this value into base64 String b64 = Base64Order.standardCoder.encode(v); args.put(n + "$file", b64); args.remove(n); args.put(n, filename + ".base64"); } else { args.put(n + "$file", v); // the byte[] is transformed into UTF8. You cannot push binaries here } } } else { // do this concurrently (this would all be superfluous if serverObjects could store byte[] instead only String) int t = Math.min(files.size(), Runtime.getRuntime().availableProcessors()); final Map.Entry<String, byte[]> POISON = new AbstractMap.SimpleEntry<>(null, null); Thread[] p = new Thread[t]; for (int j = 0; j < t; j++) { files.put(POISON); p[j] = new Thread("YaCyDefaultServlet.parseMultipart-" + j) { @Override public void run() { Map.Entry<String, byte[]> job; try { while ((job = files.take()) != POISON) { String n = job.getKey(); byte[] v = job.getValue(); String filename = args.get(n); String b64 = Base64Order.standardCoder.encode(v); synchronized (args) { args.put(n + "$file", b64); args.remove(n); args.put(n, filename + ".base64"); } } } catch (InterruptedException e) { } } }; p[j].start(); } for (int j = 0; j < t; j++) p[j].join(); } } catch (Exception ex) { ConcurrentLog.info("FILEHANDLER", ex.getMessage()); } }
From source file:it.classhidra.core.controller.bean.java
public boolean initJsonPart(HttpServletRequest request) throws bsControllerException { boolean isJson = false; HashMap parameters = new HashMap(); DataInputStream in = null;/*from w w w . ja v a 2s .com*/ try { in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength && totalBytesRead > -1) { bytesRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += bytesRead; } String json = new String(dataBytes, 0, dataBytes.length).trim(); if (json.charAt(0) == '{' && json.charAt(json.length() - 1) == '}') isJson = true; if (isJson) { if (json.charAt(0) == '{' && json.length() > 0) json = json.substring(1, json.length()); if (json.charAt(json.length() - 1) == '}' && json.length() > 0) json = json.substring(0, json.length() - 1); StringTokenizer st = new StringTokenizer(json, ","); while (st.hasMoreTokens()) { String pair = st.nextToken(); StringTokenizer st1 = new StringTokenizer(pair, ":"); String key = null; String value = null; if (st1.hasMoreTokens()) key = st1.nextToken(); if (st1.hasMoreTokens()) value = st1.nextToken(); if (key != null && value != null) { key = key.trim(); if (key.charAt(0) == '"' && key.length() > 0) key = key.substring(1, key.length()); if (key.charAt(key.length() - 1) == '"' && key.length() > 0) key = key.substring(0, key.length() - 1); value = value.trim(); if (value.charAt(0) == '"' && value.length() > 0) value = value.substring(1, value.length()); if (value.charAt(value.length() - 1) == '"' && value.length() > 0) value = value.substring(0, value.length() - 1); parameters.put(key, value); } } } } catch (Exception e) { } finally { try { in.close(); } catch (Exception ex) { } } if (isJson) initPartFromMap(parameters); return isJson; }
From source file:it.classhidra.core.controller.bsController.java
public static String getPropertyMultipart(String key, HttpServletRequest req) { try {/*from w w w. j ava 2 s . c om*/ String file = (String) req.getAttribute("multipart/form-data"); DataInputStream in = null; String contentType = req.getContentType(); if (contentType != null && contentType.indexOf("multipart/form-data") != -1) { if (file == null) { in = new DataInputStream(req.getInputStream()); int formDataLength = req.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { bytesRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += bytesRead; } file = new String(dataBytes, 0, dataBytes.length, "ASCII"); in.close(); req.setAttribute("multipart/form-data", file); } String check = "Content-Disposition: form-data; name=\"" + key + "\""; int pos = file.indexOf(check); if (pos > -1) { int pos1 = file.indexOf("-----------------------------", pos); if (pos1 > -1) { String result = file.substring(pos + check.length(), pos1); result = result.replace('\n', ' ').replace('\r', ' '); return result.trim(); } } } } catch (Exception e) { new bsControllerException(e, iStub.log_DEBUG); return null; } return null; }
From source file:org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.java
@Override public void parseFileParts() throws FileUploadException { HttpServletRequest request = getContainerRequest(); // The encoding that will be used to decode the string parameters // It should NOT be null at this point, but it may be // especially if the older Servlet API 2.2 is used String encoding = request.getCharacterEncoding(); // The encoding can also be null when using multipart/form-data encoded forms. // In that case we use the [application-encoding] which we always demand using // the attribute 'accept-encoding' in wicket forms. if (encoding == null) { encoding = Application.get().getRequestCycleSettings().getResponseRequestEncoding(); }//from w w w .ja v a 2s . co m FileUploadBase fileUpload = newFileUpload(encoding); List<FileItem> items; if (wantUploadProgressUpdates()) { ServletRequestContext ctx = new ServletRequestContext(request) { @Override public InputStream getInputStream() throws IOException { return new CountingInputStream(super.getInputStream()); } }; totalBytes = request.getContentLength(); onUploadStarted(totalBytes); try { items = fileUpload.parseRequest(ctx); } finally { onUploadCompleted(); } } else { // try to parse the file uploads by using Apache Commons FileUpload APIs // because they are feature richer (e.g. progress updates, cleaner) items = fileUpload.parseRequest(new ServletRequestContext(request)); if (items.isEmpty()) { // fallback to Servlet 3.0 APIs items = readServlet3Parts(request); } } // Loop through items for (final FileItem item : items) { // Get next item // If item is a form field if (item.isFormField()) { // Set parameter value final String value; if (encoding != null) { try { value = item.getString(encoding); } catch (UnsupportedEncodingException e) { throw new WicketRuntimeException(e); } } else { value = item.getString(); } addParameter(item.getFieldName(), value); } else { List<FileItem> fileItems = files.get(item.getFieldName()); if (fileItems == null) { fileItems = new ArrayList<>(); files.put(item.getFieldName(), fileItems); } // Add to file list fileItems.add(item); } } }
From source file:org.iff.infra.util.servlet.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;//from ww w.j av a2s.com //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); setXForwardedForHeader(servletRequest, proxyRequest); {//add by tylerchen String header = initParameterMap.get("header"); if (header != null) { String[] split = header.split("@@@"); for (String s : split) { String[] headerPaire = s.split("="); if (headerPaire.length == 2) { proxyRequest.addHeader(headerPaire[0], headerPaire[1]); } } } } HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send //TODO copy response headers? return; } // 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, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); if ("true".equals(initParameterMap.get("cached"))) {//add cache by tylerchen //servlet?? //?????20 //20????servlet HttpServletResponse response = (HttpServletResponse) servletResponse; Date date = new Date(); response.setDateHeader("Last-Modified", date.getTime()); //Last-Modified:??? response.setDateHeader("Expires", date.getTime() * 100); //Expires:? response.setHeader("Cache-Control", "public"); //Cache-Control???,public:????? response.setHeader("Cache-Control", "max-age=" + date.getTime() * 100); response.setHeader("Pragma", "Pragma"); //Pragma:??Pragmano-cache? //??????? /*response.setHeader( "Pragma", "no-cache" ); response.setDateHeader("Expires", 0); response.addHeader( "Cache-Control", "no-cache" );//????? response.addHeader( "Cache-Control", "no-store" );//???? response.addHeader( "Cache-Control", "must-revalidate" );*///?????? } // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } 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); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) consumeQuietly(proxyResponse.getEntity()); //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }
From source file:org.mitre.dsmiley.httpproxy.DynamicProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/* ww w .j ava 2s . c o m*/ //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { LOG.info("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); // copying response headers to make sure SESSIONID or other Cookie which comes from remote server // will be saved in client when the proxied url was redirected to another one. // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51) copyResponseHeaders(proxyResponse, servletRequest, servletResponse); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send return; } // 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, proxyResponse.getStatusLine().getReasonPhrase()); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } 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); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) consumeQuietly(proxyResponse.getEntity()); //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }
From source file:edu.umn.msi.tropix.webgui.server.UploadController.java
@ServiceMethod(secure = true) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { LOG.debug("In UploadController.handleRequest"); //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId")); //Preconditions.checkState(userId != null); final String userId = userSession.getGridId(); LOG.debug("Upload by user with id " + userId); String clientId = request.getParameter("clientId"); if (!StringUtils.hasText(clientId)) { clientId = UUID.randomUUID().toString(); }/*from w w w . j av a 2 s. c o m*/ final String endStr = request.getParameter("end"); final String startStr = request.getParameter("start"); final String zipStr = request.getParameter("zip"); final String lastUploadStr = request.getParameter("lastUpload"); final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false; final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true; LOG.trace("Upload request with startStr " + startStr); final StringWriter rawJsonWriter = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter); final FileItemFactory factory = new DiskFileItemFactory(); final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr) : request.getContentLength(); long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L; final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Deal with international file names final FileItemIterator iter = upload.getItemIterator(request); // Setup message conditionalSampleComponent to track upload progress... final ProgressMessageSupplier supplier = new ProgressMessageSupplier(); supplier.setId(userId + "/" + clientId); supplier.setName("Upload File(s) to Web Application"); final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl(); progressTracker.setUserGridId(userId); progressTracker.setCometPusher(cometPusher); progressTracker.setProgressMessageSupplier(supplier); jsonWriter.object(); jsonWriter.key("result"); jsonWriter.array(); while (iter.hasNext()) { final FileItemStream item = iter.next(); if (item.isFormField()) { continue; } File destination; InputStream inputStream = null; OutputStream outputStream = null; if (!isZip) { final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName(); LOG.debug("Handling upload of file with name " + fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(fileName); recordJsonInfo(jsonWriter, info); destination = info.getTempLocation(); } else { destination = FILE_UTILS.createTempFile(); } try { inputStream = item.openStream(); outputStream = FILE_UTILS.getFileOutputStream(destination); bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength, progressTracker); if (isZip) { ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() { public File apply(final String fileName) { final String cleanedUpFileName = FilenameUtils.getName(fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName); recordJsonInfo(jsonWriter, info); return info.getTempLocation(); } }); } } finally { IO_UTILS.closeQuietly(inputStream); IO_UTILS.closeQuietly(outputStream); if (isZip) { FILE_UTILS.deleteQuietly(destination); } } } if (lastUploads) { progressTracker.complete(); } jsonWriter.endArray(); jsonWriter.endObject(); // response.setStatus(200); final String json = rawJsonWriter.getBuffer().toString(); LOG.debug("Upload json response " + json); response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this response.getOutputStream().println(json); return null; }