List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:org.atlasapi.application.users.UsersController.java
@RequestMapping(value = "/4/users/{uid}.*", method = RequestMethod.POST) public void updateUser(HttpServletRequest request, HttpServletResponse response, @PathVariable String uid) throws IOException { ResponseWriter writer = null;//from w ww . ja va 2s .c o m try { writer = writerResolver.writerFor(request, response); Id userId = Id.valueOf(idCodec.decode(uid)); User editingUser = userFetcher.userFor(request).get(); // if not own profile then need to be admin if (!editingUser.is(Role.ADMIN) && !editingUser.getId().equals(userId)) { throw new ResourceForbiddenException(); } Optional<User> existing = userStore.userForId(userId); if (existing.isPresent()) { User posted = deserialize(new InputStreamReader(request.getInputStream()), User.class); // Only admins can change the role for a user // if editing user is not an admin reject if (!editingUser.is(Role.ADMIN) && isUserRoleChanged(posted, existing.get())) { throw new InsufficientPrivilegeException("You do not have permission to change the user role"); } User modified = updateProfileFields(posted, existing.get(), editingUser); userStore.store(modified); UserAwareQueryResult<User> queryResult = UserAwareQueryResult.singleResult(modified, UserAwareQueryContext.standard(request)); resultWriter.write(queryResult, writer); } else { throw new NotFoundException(userId); } } catch (Exception e) { log.error("Request exception " + request.getRequestURI(), e); ErrorSummary summary = ErrorSummary.forException(e); new ErrorResultWriter().write(summary, writer, request, response); } }
From source file:com.oneis.appserver.FileUploads.java
/** * Handle the incoming stream, processing files. *///from w ww .ja v a 2 s . c om public void performUploads(HttpServletRequest request) throws IOException, UserReportableFileUploadException { instructionsRequired = false; // Need a parser for parameters ParameterParser paramParser = new ParameterParser(); paramParser.setLowerCaseNames(true); // Thread ID is used for temporary filenames long threadId = Thread.currentThread().getId(); int fileId = 0; InputStream requestBody = request.getInputStream(); MultipartStream multipart = new MultipartStream(requestBody, boundary); multipart.setHeaderEncoding("UTF-8"); boolean nextPart = multipart.skipPreamble(); while (nextPart) { String headerPart = multipart.readHeaders(); // Parse headers, splitting out the bits we're interested in String name = null; String filename = null; Map<String, String> itemHeaders = HeaderParser.parse(headerPart, true /* keys to lower case */); String mimeType = itemHeaders.get("content-type"); String disposition = itemHeaders.get("content-disposition"); if (disposition != null) { Map disp = paramParser.parse(disposition, PARAMPARSER_SEPERATORS); name = (String) disp.get("name"); filename = (String) disp.get("filename"); } // Set a default MIME type if none is given (Safari may omit it) if (mimeType == null) { mimeType = "application/octet-stream"; } // Remove the path prefix from IE (before the length check) if (filename != null) { int slash1 = filename.lastIndexOf('/'); int slash2 = filename.lastIndexOf('\\'); int slash = (slash1 > slash2) ? slash1 : slash2; if (slash != -1) { filename = filename.substring(slash + 1); } } boolean isFile = (filename != null && filename.length() > 0); if (isFile) { // File - did the app server give instructions about it? Upload upload = files.get(name); if (upload == null) { // Looks like a file, but the app server didn't say it should be. Give up. throw new UserReportableFileUploadException( "A file was uploaded, but it was not expected by the application. Field name: '" + name + "'"); } String dir = upload.getSaveDirectory(); if (dir == null) { // Ooops. throw new IOException("app server didn't specify dir"); } // Generate a temporary filename File outFile = null; do { outFile = new File(String.format("%1$s/u%2$d.%3$d", dir, threadId, fileId++)); } while (!outFile.createNewFile()); OutputStream outStream = new FileOutputStream(outFile); // Decorate with a digest? MessageDigest digest = null; if (upload.getDigestName() != null) { try { digest = MessageDigest.getInstance(upload.getDigestName()); } catch (java.security.NoSuchAlgorithmException e) { digest = null; } if (digest != null) { outStream = new DigestOutputStream(outStream, digest); } } // Decorate with a decompressor? String filterName = upload.getFilterName(); if (filterName != null && filterName.equals("inflate")) { outStream = new InflaterOutputStream(outStream); } multipart.readBodyData(outStream); outStream.close(); String digestAsString = null; if (digest != null) { String.format("%1$s_digest", name); digestAsString = StringUtils.bytesToHex(digest.digest()); } upload.setUploadDetails(outFile.getPath(), digestAsString, mimeType, filename, outFile.length()); } else { // Normal field - just absorb a few k max of it, turn it into a field ByteArrayOutputStream value = new ByteArrayOutputStream(); // TODO: Limit request size as a whole, not on a per-parameter basis. multipart.readBodyData(new LimitedFilterOutputStream(value, MAX_TEXT_PARAMETER_LENGTH)); params.put(name, value.toString("UTF-8")); } nextPart = multipart.readBoundary(); } }
From source file:com.couchbase.capi.servlet.CAPIServlet.java
/** * Handle _revs_diff by claiming we don't have any of these revisions * * @param req/*from w w w . j a v a2 s . c o m*/ * @param resp * @param database * @throws ServletException * @throws IOException */ protected void handleRevsDiff(HttpServletRequest req, HttpServletResponse resp, String database) throws ServletException, IOException { if (!req.getMethod().equals("POST")) { throw new UnsupportedOperationException("_revs_diff must be POST"); } logger.trace("Got revs diff request for " + database); OutputStream os = resp.getOutputStream(); InputStream is = req.getInputStream(); int requestLength = req.getContentLength(); byte[] buffer = new byte[requestLength]; IOUtils.readFully(is, buffer, 0, requestLength); logger.trace("revs diff request body was {}", new String(buffer)); @SuppressWarnings("unchecked") Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class); logger.trace("revs diff parsed value is " + parsedValue); try { Map<String, Object> responseMap = capiBehavior.revsDiff(database, parsedValue); if (responseMap != null) { mapper.writeValue(os, responseMap); } else { sendNotFoundResponse(resp, "missing"); } } catch (UnavailableException e) { sendServiceUnavailableResponse(resp, "too many concurrent requests"); } }
From source file:freeciv.servlet.ProxyServlet.java
/** * Performs an HTTP POST request/*from w ww . jav a2s .c o m*/ * @param httpServletRequest The {@link HttpServletRequest} object passed * in by the servlet engine representing the * client request to be proxied * @param httpServletResponse The {@link HttpServletResponse} object by which * we can send a proxied response to the client */ public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a standard POST request PostMethod postMethodProxyRequest = new PostMethod(this.getProxyURL(httpServletRequest)); // Forward the request headers setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest); // don't change Content-type header from client. //postMethodProxyRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); postMethodProxyRequest.setRequestBody(httpServletRequest.getInputStream()); this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse); httpServletResponse.setHeader("Cache-Control", "no-cache"); //HTTP 1.1 httpServletResponse.setHeader("Pragma", "no-cache"); //HTTP 1.0 httpServletResponse.setDateHeader("Expires", 0); //prevents caching at the proxy server }
From source file:com.googlesource.gerrit.plugins.lfs.locks.LfsLocksContext.java
LfsLocksContext(LfsGson gson, final HttpServletRequest req, final HttpServletResponse res) { this.path = req.getPathInfo().startsWith("/") ? req.getPathInfo() : "/" + req.getPathInfo(); this.req = req; this.res = res; this.writer = Suppliers.memoize(new Supplier<Writer>() { @Override// w w w .ja v a 2 s .co m public Writer get() { try { return new BufferedWriter(new OutputStreamWriter(res.getOutputStream(), UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } }); this.reader = Suppliers.memoize(new Supplier<Reader>() { @Override public Reader get() { try { return new BufferedReader(new InputStreamReader(req.getInputStream(), UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } }); this.gson = gson; setLfsResponseType(); }
From source file:julie.com.mikaelson.file.controller.FileInfoController.java
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST) @ResponseBody/*from w w w . jav a 2s .c o m*/ public Map<String, Object> handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("image_file"); fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); String overFlg = request.getParameter("over"); // 0:go on;1:over System.out.println("get: " + fileName); byte[] buf = new byte[1024]; File file = new File("./" + /* * "[" + * UUID.randomUUID().toString() + * "]" + */fileName); InputStream is = null; BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file, true)); try { is = request.getInputStream(); while (true) { int bytesIn = is.read(buf, 0, 1024); System.out.println(bytesIn); if (bytesIn == -1) { break; } else { fileOut.write(buf, 0, bytesIn); } } fileOut.flush(); fileOut.close(); System.out.println(file.getAbsolutePath()); } catch (IOException e) { System.out.println("error info"); } Map<String, Object> map = new HashMap<String, Object>(); map.put("over", overFlg); map.put("data", fileName); return map; }
From source file:com.wx.CoacherWXServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from ww w . j a va 2s .c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sToken = "testToken1"; String sCorpID = "wxe706b25abb1216c0"; String sEncodingAESKey = "R5zQRNXirEIQsSGL5Hs5ydZdSuu7EkRLWLViul1P7si"; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String msg_signature = request.getParameter("msg_signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); InputStream inputStream = request.getInputStream(); String postData = IOUtils.toString(inputStream, "UTF-8"); System.out.println(postData); String msg = ""; WXBizMsgCrypt wxcpt = null; try { wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID); //? msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, postData); } catch (AesException e) { e.printStackTrace(); } System.out.println("msg=" + msg); BaseMessage respMessage = CoreService.processRequest(msg, classService); String resMsg = null; /** if (request.getSession().getAttribute("accessToken") == null) { try { String accessToken = CoreService.getAccessToken(config.getInitParameter("corpid"), config.getInitParameter("corpsecret")); request.getSession().setAttribute("accessToken", accessToken); QyWxURLUtil.applyAccessToken(accessToken); } catch (Exception ex) { Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, null, ex); } } **/ /** * UploadMediaReturnMessage uploadMediaReturnMsg; try { * uploadMediaReturnMsg = WXUtils.send("image", * "/root/WXMedia/anranhui520/1.jpg"); * if("null".equals(uploadMediaReturnMsg.getErrcode())){ * System.out.println("Media_id:"+uploadMediaReturnMsg.getMedia_id()); * }else{ System.out.println("Upload error * message:"+uploadMediaReturnMsg.getErrmsg()+" error * code:"+uploadMediaReturnMsg.getErrcode()); * * } * } catch (Exception ex) { * Logger.getLogger(TestWXServlet.class.getName()).log(Level.SEVERE, * null, ex); } * */ if (respMessage instanceof TextMessage) { /*try { TextMessage txtMsg = (TextMessage) respMessage; String command = txtMsg.getContent(); CheckCommandReturnMessage ccReturnMsg = CMDService.processCheckingCommand(command); Set<UserInfo> userInfoSet = ccReturnMsg.getUserInfos(); UserInfo userif = null; for (UserInfo userInfo : userInfoSet) { userif = userInfo; } System.out.println("msgContent:" + ccReturnMsg.getContent()); System.out.println("weixinid:" + userif.getWeixinid()); try { UploadMediaReturnMessage uploadMediaReturnMsg = null; try { QRCodeGenerator.encode(ccReturnMsg.getContent(), "/root/WXMedia/"+userif.getWeixinid()); uploadMediaReturnMsg = WXUtils.send("image", "/root/WXMedia/"+userif.getWeixinid()+"/qrcode.jpg"); if ("null".equals(uploadMediaReturnMsg.getErrcode())) { System.out.println("Media_id:" + uploadMediaReturnMsg.getMedia_id()); } else { System.out.println("Upload error message:" + uploadMediaReturnMsg.getErrmsg() + " error code:" + uploadMediaReturnMsg.getErrcode()); } } catch (Exception ex) { Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex); }*/ /** * TextSendMessage textMsg = new TextSendMessage(); String * msgtxt = ccReturnMsg.getContent(); * textMsg.setTextContent(msgtxt); * textMsg.setMsgtype("text"); * textMsg.setTouser(userif.getWeixinid()); * textMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); * */ /* ImageSendMessage imgMsg = new ImageSendMessage(); imgMsg.setImageMedia(uploadMediaReturnMsg.getMedia_id()); imgMsg.setMsgtype("image"); imgMsg.setTouser(userif.getWeixinid()); imgMsg.setAgentid(Long.parseLong(config.getInitParameter("checkingAgentId"))); AccessTokenReturnMessage returnMsg = CoreService.sendMessage(imgMsg); } catch (Exception ex) { Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex); } } catch (Exception ex) { Logger.getLogger(CustomerWXServlet.class.getName()).log(Level.SEVERE, null, ex); }*/ } else if (respMessage instanceof NewsMessage) { System.out.println("enter NewsMessage."); NewsMessage newsMsg = (NewsMessage) respMessage; resMsg = MessageUtil.newsMessageToXml(newsMsg); System.out.println("ResMsg:" + resMsg); } PrintWriter out = response.getWriter(); out.print(resMsg); out.flush(); out.close(); }
From source file:com.mobicage.rogerthat.CallbackApiServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json-rpc; charset=utf-8"); // Validate incomming request final String contentType = req.getHeader("Content-type"); if (contentType == null || !contentType.startsWith("application/json-rpc")) { resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); return;// w ww.j ava2 s .co m } final String sikKey = req.getHeader("X-Nuntiuz-Service-Key"); if (!validateSIK(sikKey)) { resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); return; } // Parse final InputStream is = req.getInputStream(); final JSONObject request; try { request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8"))); } finally { is.close(); } if (logTraffic) log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey, request.toJSONString())); final String id = (String) request.get("id"); if (callbackDedup != null) { byte[] response = callbackDedup.getResponse(id); if (response != null) { ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(response); outputStream.flush(); return; } } final JSONObject result = new JSONObject(); final RequestContext requestContext = new RequestContext(id, sikKey); try { processor.process(request, result, requestContext); } finally { String jsonString = result.toJSONString(); if (logTraffic) log.info("Returning result:\n" + jsonString); byte[] response = jsonString.getBytes("UTF-8"); if (callbackDedup != null) { callbackDedup.storeResponse(id, response); } ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(response); outputStream.flush(); } }
From source file:com.google.sampling.experiential.server.EventServlet.java
private void processJsonUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException { String postBodyString = org.apache.commons.io.IOUtils.toString(req.getInputStream()); if (postBodyString.equals("")) { resp.getWriter().write("Empty Post body"); } else {// ww w . j av a 2s . c o m log.info(postBodyString); JSONObject currentEvent = null; try { boolean isDevInstance = isDevInstance(req); if (postBodyString.startsWith("[")) { JSONArray posts = new JSONArray(postBodyString); for (int i = 0; i < posts.length(); i++) { currentEvent = posts.getJSONObject(i); postEvent(isDevInstance, currentEvent); } } else { currentEvent = new JSONObject(postBodyString); postEvent(isDevInstance, currentEvent); } resp.getWriter().write("Success"); } catch (JSONException e) { e.printStackTrace(); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter() .write("Paco says: Invalid JSON Input: " + postBodyString + "\nError: " + e.getMessage()); } catch (ParseException e) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().write("Paco says: Invalid Date in an Event Input: " + postBodyString + "\nError: " + e.getMessage()); } catch (Exception t) { log.log(Level.SEVERE, "Caught throwable in doPost!", t); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().write("Paco says: Something generic went wrong in an Event Input: " + postBodyString + "\nError: " + t.getMessage()); } } }
From source file:edu.txstate.dmlab.clusteringwiki.rest.ClusterController.java
/** * Update paths for a given cluster edit * @param qid Query id of the executed query * @param algo Algorithm used for clustering * @param request HttpServletRequest//from w w w. ja v a2 s . c om * @param response HttpServletResponse * @param model Model * @throws Exception */ @RequestMapping("/clusterUpdate/{queryId}/{clusteringAlgo}") public void savePaths(@PathVariable("queryId") String qid, @PathVariable("clusteringAlgo") String algo, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { try { Integer queryId = Integer.valueOf(_cleanExtensions(qid)); Integer clusteringAlgo = Integer.valueOf(_cleanExtensions(algo)); String data = null; InputStream is = request.getInputStream(); if (is != null) { try { StringBuilder sb = new StringBuilder(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } data = sb.toString(); } finally { is.close(); } } if (data == null) { sendOutput(response, "{\"error\":\"No data received.\"}"); return; } JSONArray paths = new JSONArray(data); for (int i = 0; i < paths.length(); i++) { JSONObject j = paths.getJSONObject(i); Integer cardinality = j.getInt("cardinality"); JSONArray path = j.getJSONArray("lPath"); clusterEditDao.updatePath(queryId, clusteringAlgo, path.optString(1).trim(), path.optString(2).trim(), path.optString(3).trim(), path.optString(4).trim(), path.optString(5).trim(), cardinality); } sendOutput(response, "{\"success\":true}"); } catch (Exception e) { sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}"); return; } }