List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:io.druid.server.AsyncQueryForwardingServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(request.getContentType()) || APPLICATION_SMILE.equals(request.getContentType()); final ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper; request.setAttribute(OBJECTMAPPER_ATTRIBUTE, objectMapper); final String requestURI = request.getRequestURI(); final String method = request.getMethod(); final Server targetServer; // The Router does not have the ability to look inside SQL queries and route them intelligently, so just treat // them as a generic request. final boolean isQueryEndpoint = requestURI.startsWith("/druid/v2") && !requestURI.startsWith("/druid/v2/sql"); final boolean isAvatica = requestURI.startsWith("/druid/v2/sql/avatica"); if (isAvatica) { Map<String, Object> requestMap = objectMapper.readValue(request.getInputStream(), JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT); String connectionId = getAvaticaConnectionId(requestMap); targetServer = hostFinder.findServerAvatica(connectionId); byte[] requestBytes = objectMapper.writeValueAsBytes(requestMap); request.setAttribute(AVATICA_QUERY_ATTRIBUTE, requestBytes); } else if (isQueryEndpoint && HttpMethod.DELETE.is(method)) { // query cancellation request targetServer = hostFinder.pickDefaultServer(); for (final Server server : hostFinder.getAllServers()) { // send query cancellation to all brokers this query may have gone to // to keep the code simple, the proxy servlet will also send a request to the default targetServer. if (!server.getHost().equals(targetServer.getHost())) { // issue async requests Response.CompleteListener completeListener = result -> { if (result.isFailed()) { log.warn(result.getFailure(), "Failed to forward cancellation request to [%s]", server.getHost()); }//from ww w .j av a 2 s. c o m }; Request broadcastReq = broadcastClient .newRequest(rewriteURI(request, server.getScheme(), server.getHost())) .method(HttpMethod.DELETE).timeout(CANCELLATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); copyRequestHeaders(request, broadcastReq); broadcastReq.send(completeListener); } interruptedQueryCount.incrementAndGet(); } } else if (isQueryEndpoint && HttpMethod.POST.is(method)) { // query request try { Query inputQuery = objectMapper.readValue(request.getInputStream(), Query.class); if (inputQuery != null) { targetServer = hostFinder.pickServer(inputQuery); if (inputQuery.getId() == null) { inputQuery = inputQuery.withId(UUID.randomUUID().toString()); } } else { targetServer = hostFinder.pickDefaultServer(); } request.setAttribute(QUERY_ATTRIBUTE, inputQuery); } catch (IOException e) { log.warn(e, "Exception parsing query"); final String errorMessage = e.getMessage() == null ? "no error message" : e.getMessage(); requestLogger .log(new RequestLogLine(DateTimes.nowUtc(), request.getRemoteAddr(), null, new QueryStats( ImmutableMap.<String, Object>of("success", false, "exception", errorMessage)))); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType(MediaType.APPLICATION_JSON); objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage)); return; } catch (Exception e) { handleException(response, objectMapper, e); return; } } else { targetServer = hostFinder.pickDefaultServer(); } request.setAttribute(HOST_ATTRIBUTE, targetServer.getHost()); request.setAttribute(SCHEME_ATTRIBUTE, targetServer.getScheme()); doService(request, response); }
From source file:com.thinkberg.webdav.LockHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = VFSBackend.resolveFile(request.getPathInfo()); try {/*from w ww .ja v a2 s .co m*/ final LockManager manager = LockManager.getInstance(); final LockManager.EvaluationResult evaluation = manager.evaluateCondition(object, getIf(request)); if (!evaluation.result) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } else { if (!evaluation.locks.isEmpty()) { LOG.debug(String.format("discovered locks: %s", evaluation.locks)); sendLockAcquiredResponse(response, evaluation.locks.get(0)); return; } } } catch (LockConflictException e) { List<Lock> locks = e.getLocks(); for (Lock lock : locks) { if (Lock.EXCLUSIVE.equals(lock.getType())) { response.sendError(SC_LOCKED); return; } } } catch (ParseException e) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } try { SAXReader saxReader = new SAXReader(); Document lockInfo = saxReader.read(request.getInputStream()); //log(lockInfo); Element rootEl = lockInfo.getRootElement(); String lockScope = null, lockType = null; Object owner = null; Iterator elIt = rootEl.elementIterator(); while (elIt.hasNext()) { Element el = (Element) elIt.next(); if (TAG_LOCKSCOPE.equals(el.getName())) { lockScope = el.selectSingleNode("*").getName(); } else if (TAG_LOCKTYPE.equals(el.getName())) { lockType = el.selectSingleNode("*").getName(); } else if (TAG_OWNER.equals(el.getName())) { // TODO correctly handle owner Node subEl = el.selectSingleNode("*"); if (subEl != null && TAG_HREF.equals(subEl.getName())) { owner = new URL(el.selectSingleNode("*").getText()); } else { owner = el.getText(); } } } LOG.debug("LOCK(" + lockType + ", " + lockScope + ", " + owner + ")"); Lock requestedLock = new Lock(object, lockType, lockScope, owner, getDepth(request), getTimeout(request)); try { LockManager.getInstance().acquireLock(requestedLock); sendLockAcquiredResponse(response, requestedLock); } catch (LockConflictException e) { response.sendError(SC_LOCKED); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } } catch (DocumentException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java
public void handlePut(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws ServletException, IOException { boolean exists = resource != null && resource.exists(); if (exists && !passConditionalHeaders(request, response, resource)) return;/* w w w. ja v a 2 s. c om*/ if (pathInContext.endsWith("/")) { if (!exists) { if (!resource.getFile().mkdirs()) response.sendError(HttpResponse.__403_Forbidden, "Directories could not be created"); else { response.setStatus(HttpResponse.__201_Created); response.flushBuffer(); } } else { response.setStatus(HttpResponse.__200_OK); response.flushBuffer(); } } else { try { int toRead = request.getContentLength(); InputStream in = request.getInputStream(); OutputStream out = resource.getOutputStream(); if (toRead >= 0) IO.copy(in, out, toRead); else IO.copy(in, out); out.close(); response.setStatus(exists ? HttpResponse.__200_OK : HttpResponse.__201_Created); response.flushBuffer(); } catch (Exception ex) { log.warn(LogSupport.EXCEPTION, ex); response.sendError(HttpResponse.__403_Forbidden, ex.getMessage()); } } }
From source file:me.ywork.ticket.suite.controller.DingServiceController.java
/** * ?URL??//from w w w . j a va 2 s. c o m */ @RequestMapping(value = "/orgchange/{suiteid}", method = RequestMethod.POST) public void orgchange(@PathVariable("suiteid") String sid, HttpServletRequest request, HttpServletResponse response) { // ? String msgSignature = request.getParameter("signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); if (StringUtils.isEmpty(sid)) { logger.error( "??IDding_suite_main??"); return; } else if (sid.indexOf("?") > 0) { sid = sid.substring(0, sid.indexOf("?")); } // POST? try { InputStream inputStream = request.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String buffer = null; StringBuffer sb = new StringBuffer(); while ((buffer = br.readLine()) != null) { sb.append(buffer + "\n"); } br.close(); inputStream.close(); JSONObject json = JSON.parseObject(sb.toString()); String encryptStr = json.getString("encrypt"); DingSuiteMain suite = dingSuiteMainService.getDingSuiteFromCache(sid); DingTalkEncryptor dingTalkEncryptor = dmap.get(suite.getSuiteId()); if (dingTalkEncryptor == null) { dingTalkEncryptor = new DingTalkEncryptor(suite.getToken(), suite.getEncodingAESKey(), suite.getSuiteId()); dmap.put(suite.getSuiteId(), dingTalkEncryptor); } // ?????,SUCCESS doSuccessResponse(dingTalkEncryptor, response, "success", msgSignature, timeStamp, nonce); // encrypt String plainText = null; plainText = dingTalkEncryptor.getDecryptMsg(msgSignature, timeStamp, nonce, encryptStr); logger.info("???{}", plainText); // ?json JSONObject plainTextJson = JSONObject.parseObject(plainText); String eventType = plainTextJson.getString("EventType"); if (eventType.equals("check_url")) { // url, return; } // ??? String corpId = plainTextJson.getString("CorpId"); JSONArray userIds = plainTextJson.getJSONArray("UserId"); String[] userIdArray = null; if (userIds != null && userIds.size() > 0) { userIdArray = new String[userIds.size()]; for (int i = 0; i < userIds.size(); i++) { userIdArray[i] = userIds.getString(i); } } JSONArray deptIds = plainTextJson.getJSONArray("DeptId"); String[] deptIdArray = null; if (deptIds != null && deptIds.size() > 0) { deptIdArray = new String[deptIds.size()]; for (int i = 0; i < deptIds.size(); i++) { deptIdArray[i] = deptIds.getString(i); } } //org? DingOrgModifyMessage orgModifyMessage = new DingOrgModifyMessage(); orgModifyMessage.setEventType(eventType); orgModifyMessage.setSuiteId(sid); orgModifyMessage.setCorpId(corpId); orgModifyMessage.setDeptId(deptIdArray); orgModifyMessage.setUserId(userIdArray); orgModifyMessage.setChannel(KafkaTopics.DING_ORG_MANAGER_REAL.getTopic()); KafkaProducer.getInstance().sendMessage(KafkaTopics.DING_ORG_MANAGER_REAL.getTopic(), orgModifyMessage); } catch (Exception ex) { logger.error("?", ex); } }
From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java
/** * Handles a servlet request./*from w w w . j a v a 2 s . co m*/ * * @param request the {@link HttpServletRequest} * @param response the {@link HttpServletResponse} * @throws IOException on error */ public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Handing HttpServletRequest " + request.getMethod()); } // set response type response.setContentType(JSONRPC_RESPONSE_CONTENT_TYPE); // setup streams InputStream input = null; OutputStream output = response.getOutputStream(); // POST if (request.getMethod().equals("POST")) { input = request.getInputStream(); // GET } else if (request.getMethod().equals("GET")) { input = createInputStream(request.getParameter("method"), request.getParameter("id"), request.getParameter("params")); // invalid request } else { throw new IOException("Invalid request method, only POST and GET is supported"); } // service the request handle(input, output); }
From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java
private void handleJMXRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is = null;/*from w w w.java 2 s.c om*/ OutputStream os = null; try { String myPath = req.getRequestURI().substring(req.getServletPath().length() + 11); URL adminUrl = null; if (myPath.indexOf('/') > 0) { adminUrl = new URL( new StringBuilder(URLDecoder.decode(myPath.substring(0, myPath.indexOf('/')), "UTF-8")) .append("/admin/jmx").append(myPath.substring(myPath.indexOf('/'))).toString()); } else { adminUrl = new URL( new StringBuilder(URLDecoder.decode(myPath, "UTF-8")).append("/admin/jmx").toString()); } URLConnection conn = adminUrl.openConnection(); byte[] buffer = new byte[8192]; // 8k int len = 0; InputStream ris = req.getInputStream(); while ((len = ris.read(buffer)) > 0) { if (!conn.getDoOutput()) { conn.setDoOutput(true); os = conn.getOutputStream(); } os.write(buffer, 0, len); } if (os != null) os.flush(); is = conn.getInputStream(); OutputStream ros = resp.getOutputStream(); while ((len = is.read(buffer)) > 0) { ros.write(buffer, 0, len); } ros.flush(); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } finally { if (is != null) is.close(); if (os != null) os.close(); } }
From source file:com.tasktop.c2c.server.scm.web.GitHandler.java
@Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO(); String pathInfo = request.getPathInfo(); log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo); Repository repository = null;//w ww. ja v a 2 s .c o m try { // only work on Git requests Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo); if (matcher == null || !matcher.matches()) { log.info("Unexpected path: " + pathInfo); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String requestCommand = matcher.group(1); String requestPath = matcher.group(2); // sanity check on path, disallow path separator components if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) { badPathResponse(); } repository = repositoryResolver.open(request, requestPath); InputStream requestInput = request.getInputStream(); if (!containerSupportsChunkedIO) { requestInput = new ChunkedInputStream(requestInput); } MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO); // indicate that we're ok to handle the request // note that following this there will be a two-way communication with the process // that might still encounter errors. That's ok. startOkResponse(response, containerSupportsChunkedIO); // identify the git command GitCommand command = GitCommand.fromCommandName(requestCommand); if (command != null) { // permissions check if (!Security.hasOneOfRoles(command.getRoles())) { log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName() + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath); response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } switch (command) { case RECEIVE_PACK: ReceivePack rp = new ReceivePack(repository); rp.setPostReceiveHook(postReceiveHook); rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR)); break; case UPLOAD_PACK: UploadPack up = new UploadPack(repository); up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR)); break; default: response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } // at this stage we're done with IO // send the exit value and closing chunk try { int exitValue = 0; if (exitValue != 0) { log.info("Exit value: " + exitValue); } mox.writeExitCode(exitValue); mox.close(); } catch (IOException e) { // ignore log.debug("Cannot complete writing exit state", e); } // clear interrupt status Thread.interrupted(); } catch (ErrorResponseException e) { createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage()); } catch (ServiceNotAuthorizedException e) { createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage()); } catch (ServiceNotEnabledException e) { createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage()); } finally { log.info("Git request complete"); if (repository != null) { repository.close(); } } }
From source file:kornell.server.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;//w w w .ja v a 2 s . 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("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); // 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()); if (proxyResponse != null) closeQuietly(servletResponse.getOutputStream()); } }
From source file:org.redhat.jboss.httppacemaker.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(); // FIXME: the rewriteUrlFromRequest() method adds an extra trailing "slash", remove by the replace String proxyRequestUri = rewriteUrlFromRequest(servletRequest).replaceAll("/$", ""); HttpRequest proxyRequest;//w w w. j a va 2s . c om //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); if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } sendProxyRequestToBackend(proxyRequest, servletRequest, servletResponse); }
From source file:com.aliasi.demo.framework.DemoServlet.java
void generateOutput(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { InputStream in = null;//from www . j a v a2 s.co m OutputStream out = null; try { response.setContentType(mDemo.responseType()); out = response.getOutputStream(); @SuppressWarnings("unchecked") // bad inherited API from commons Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap()); String reqContentType = request.getContentType(); if (reqContentType == null || reqContentType.startsWith("text/plain")) { properties.setProperty("inputType", "text/plain"); String reqCharset = request.getCharacterEncoding(); if (reqCharset != null) properties.setProperty("inputCharset", reqCharset); in = request.getInputStream(); } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) { String codedText = request.getParameter("inputText"); byte[] bytes = codedText.getBytes("ISO-8859-1"); in = new ByteArrayInputStream(bytes); } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload uploader = new ServletFileUpload(factory); @SuppressWarnings("unchecked") // bad commons API List<FileItem> items = (List<FileItem>) uploader.parseRequest(request); Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { log("found item"); FileItem item = it.next(); if (item.isFormField()) { String key = item.getFieldName(); String val = item.getString(); properties.setProperty(key, val); } else { byte[] bytes = item.get(); in = new ByteArrayInputStream(bytes); } } } else { System.out.println("unexpected content type"); String msg = "Unexpected request content" + reqContentType; throw new ServletException(msg); } mDemo.process(in, out, properties); } catch (FileUploadException e) { throw new ServletException(e); } finally { Streams.closeQuietly(in); Streams.closeQuietly(out); } }