List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:com.curl.orb.servlet.DefaultInstanceManagementFilter.java
@SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // accept just HTTP. if (!((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse))) throw new ServletException("The request is not HTTP protocol."); HttpServletRequest httpRequest = (HttpServletRequest) request; InstanceManagementRequest instanceManagementRequest = null; // serialize the request object and set to the attribute try {// w ww . j av a 2s .c o m if (request.getContentLength() == -1) { // forward to requested page. request.getRequestDispatcher(httpRequest.getServletPath()).forward(request, response); return; } instanceManagementRequest = (InstanceManagementRequest) serializer .deserialize(httpRequest.getInputStream()); // debug request object (instanceManagementRequest.toString()) log.debug("Curl ORB Request object [" + instanceManagementRequest + "]"); httpRequest.setAttribute(InstanceManagementServlet.REQUEST_OBJECT, instanceManagementRequest); } catch (SerializerException e) { // NOTE: // Cannot handle the exception when "stream response" mode. // Clients cannot receive the error. setResponse((HttpServletResponse) response, new InstanceManagementException("Could not deserialize the object from Curl.", e), null); return; } try { // do filters and servlets chain.doFilter(httpRequest, response); // deserialize the object and return the response setResponse((HttpServletResponse) response, httpRequest.getAttribute(InstanceManagementServlet.RESPONSE_OBJECT), (Map<String, Object>) httpRequest .getAttribute(InstanceManagementServlet.RESPONSE_SUBORDINATE_OBJECT)); } catch (Exception e) { setResponse((HttpServletResponse) response, e, null); } }
From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Communicates with redirect url and works as a transparent proxy * // ww w . j ava 2 s .c om * @param request * the servlet request * @param response * the servlet response * @throws IOException * if an exception occurs */ private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpURLConnection httpCon = null; URL redirectURL = null; InputStream input = null; OutputStream output = null; InputStream proxyInput = null; OutputStream proxyOutput = null; try { input = request.getInputStream(); output = response.getOutputStream(); String sQueryStr = request.getQueryString(); String sAuthorization = request.getHeader("Authorization"); String requestBody = readInputCharacters(input); String requestMethod = request.getMethod(); String contentType = request.getContentType(); String encoding = request.getCharacterEncoding(); LOGGER.finer(" Request method = " + requestMethod); LOGGER.finer(" Query string = " + sQueryStr); LOGGER.finer(" Authorization header =" + sAuthorization); LOGGER.finer(" Character Encoding = " + encoding); LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr); redirectURL = new URL(this._redirectURL + "?" + sQueryStr); httpCon = (HttpURLConnection) redirectURL.openConnection(); httpCon.setDoInput(true); httpCon.setDoOutput(true); httpCon.setUseCaches(false); httpCon.setRequestMethod(requestMethod); httpCon.setRequestProperty("Content-type", contentType); if (sAuthorization != null) { httpCon.addRequestProperty("Authorization", sAuthorization); } proxyOutput = httpCon.getOutputStream(); send(requestBody, proxyOutput); String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate"); if (authenticateHdr != null) { LOGGER.finer(" WWW-Authenticate : " + authenticateHdr); response.setHeader("WWW-Authenticate", StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr))); } LOGGER.finer(" Response Code : " + httpCon.getResponseCode()); if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { proxyInput = httpCon.getInputStream(); send(proxyInput, output); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (proxyInput != null) { proxyInput.close(); } if (proxyOutput != null) { proxyOutput.close(); } if (httpCon != null) { httpCon.disconnect(); } } }
From source file:com.epam.wilma.test.server.ExampleHandler.java
@Override public void handle(final String path, final Request baseRequest, final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException, ServletException { if (PATH_TO_HANDLE.equals(path) || PATH_OK.equals(path)) { byte[] byteArray = null; String requestBody = ""; String contentEncodingHeader = httpServletRequest.getHeader(CONTENT_ENCODING); if (contentEncodingHeader != null && contentEncodingHeader.contains(GZIP_TYPE)) { byteArray = gzipDecompresser.decompress(httpServletRequest.getInputStream()).toByteArray(); requestBody = IOUtils.toString(byteArray, "utf-8"); }/*from www . j a va 2 s. c om*/ String headerField = httpServletRequest.getHeader(CONTENT_TYPE); if (headerField != null && headerField.contains(FASTINFOSET_TYPE)) { if (byteArray != null) { requestBody = fisDecompressor.decompress(new ByteArrayInputStream(byteArray)); } else { requestBody = fisDecompressor.decompress(httpServletRequest.getInputStream()); } } else if (headerField != null && headerField.contains(XML_TYPE)) { if (byteArray == null) { requestBody = inputStreamConverter.getStringFromStream(httpServletRequest.getInputStream()); } } if (PATH_OK.equals(path)) { //ok, send back the test server version requestBody = getClass().getPackage().getImplementationTitle(); } if ("".equals(requestBody)) { ByteArrayOutputStream writer = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), writer); requestBody = IOUtils.toString(writer.toByteArray(), "utf-8"); //default request body content } setAnswer(baseRequest, httpServletRequest, httpServletResponse, requestBody); } else { generateBadResponses(path, httpServletRequest, httpServletResponse, baseRequest); generateErrorCode(path, httpServletResponse); } }
From source file:org.basinmc.irc.bridge.github.TeamCityHandler.java
/** * {@inheritDoc}/*from w w w . j a va2 s . c om*/ */ @Override public void handle(@Nonnull String target, @Nonnull Request baseRequest, @Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response) throws IOException, ServletException { if (!target.startsWith("/build")) { return; } if (this.serverAddress != null && !this.serverAddress.isEmpty() && !this.serverAddress.equals(request.getRemoteAddr())) { logger.info("Access denied to build webhook from " + request.getRemoteAddr()); response.sendError(HttpServletResponse.SC_FORBIDDEN); baseRequest.setHandled(true); return; } JsonNode data; try (InputStream inputStream = request.getInputStream()) { data = reader.readTree(inputStream).get("build"); } switch (target) { default: return; case "/build/started": this.bridge.sendMessage(String.format(MESSAGE_START, data.get("buildFullName").asText(), data.get("agentName").asText(), data.get("buildStatusUrl").asText())); break; case "/build/success": this.bridge.sendMessage(String.format(MESSAGE_SUCCESS, data.get("buildFullName").asText(), data.get("buildStatusUrl").asText())); break; case "/build/failure": this.bridge.sendMessage(String.format(MESSAGE_FAILURE, data.get("buildFullName").asText(), data.get("buildStatusUrl").asText())); break; } logger.info("Handled build webhook from " + request.getRemoteAddr()); response.setStatus(HttpServletResponse.SC_NO_CONTENT); baseRequest.setHandled(true); }
From source file:org.sample.nonblocking.ReadTestServlet.java
/** * Processes requests for both HTTP//from w w w . j a v a2 s .co m * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter output = response.getWriter()) { output.println("<html>"); output.println("<head>"); output.println("<title>Servlet ReadTestServlet</title>"); output.println("</head>"); output.println("<body>"); output.println("<h1>Servlet ReadTestServlet at " + request.getContextPath() + "</h1>"); AsyncContext context = request.startAsync(); ServletInputStream input = request.getInputStream(); input.setReadListener(new MyReadListener(input, context)); output.println("</body>"); output.println("</html>"); } }
From source file:com.almende.eve.transport.http.AgentServlet.java
/** * Send a JSON-RPC message to an agent Usage: POST /servlet/{agentId} With a * JSON-RPC request as body. Response will be a JSON-RPC response. * // w w w.j ava 2s. c o m * @param req * the req * @param resp * the resp * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * the servlet exception */ @Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException { // retrieve the agent url and the request body final String body = StringUtil.streamToString(req.getInputStream()); final String agentUrl = req.getRequestURI(); String agentId; try { agentId = httpTransport.getAgentId(new URI(agentUrl)); } catch (URISyntaxException e) { throw new ServletException(AGENTURLWARNING, e); } if (agentId == null || agentId.equals("")) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url."); resp.flushBuffer(); return; } if (host.hasPrivate(agentId) && !handleSession(req, resp)) { if (!resp.isCommitted()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); } resp.flushBuffer(); return; } // Attach the claimed senderId, or null if not given. String senderUrl = req.getHeader("X-Eve-SenderUrl"); if (senderUrl == null || senderUrl.equals("")) { senderUrl = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr(); } final String tag = new UUID().toString(); final SyncCallback<String> callback = new SyncCallback<String>(); final AsyncCallbackQueue<String> callbacks = host.getCallbackQueue("HttpTransport", String.class); callbacks.push(tag, "", callback); //TODO: check if it's base64 encoded data, decode to byte[] and call receive byte[]. host.receive(agentId, body, URI.create(senderUrl), tag); try { final Object message = callback.get(); // return response resp.addHeader("Content-Type", "application/json"); resp.getWriter().println(message.toString()); resp.getWriter().close(); } catch (final Exception e) { LOG.log(Level.WARNING, "Http Sync receive raised exception.", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Receiver raised exception:" + e.getMessage()); } resp.flushBuffer(); }
From source file:com.adaptris.core.http.jetty.MessageConsumer.java
@Override public AdaptrisMessage createMessage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { AdaptrisMessage msg = null;//from w w w . j a v a 2s . c o m OutputStream out = null; try { logHeaders(request); if (getEncoder() != null) { msg = getEncoder().readMessage(request); } else { msg = defaultIfNull(getMessageFactory()).newMessage(); out = msg.getOutputStream(); if (request.getContentLength() == -1) { IOUtils.copy(request.getInputStream(), out); } else { StreamUtil.copyStream(request.getInputStream(), out, request.getContentLength()); } out.flush(); } msg.setContentEncoding(request.getCharacterEncoding()); addParamMetadata(msg, request); addHeaderMetadata(msg, request); } catch (CoreException e) { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } finally { IOUtils.closeQuietly(out); } return msg; }
From source file:com.platform.middlewares.APIProxy.java
private Request mapToOkHttpRequest(org.eclipse.jetty.server.Request baseRequest, String path, HttpServletRequest request) { Request req;/*from w ww.java2 s. c o m*/ Request.Builder builder = new Request.Builder().url(apiInstance.buildUrl(path)); Enumeration<String> headerNames = baseRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hName = headerNames.nextElement(); if (Arrays.asList(bannedSendHeaders).contains(hName.toLowerCase())) continue; builder.addHeader(hName, baseRequest.getHeader(hName)); } byte[] bodyText = new byte[0]; try { bodyText = IOUtils.toByteArray(request.getInputStream()); } catch (IOException e) { e.printStackTrace(); } String contentType = baseRequest.getContentType() == null ? null : baseRequest.getContentType(); RequestBody reqBody = RequestBody.create(contentType == null ? null : MediaType.parse(contentType), bodyText); switch (baseRequest.getMethod()) { case "GET": builder.get(); break; case "DELETE": builder.delete(); break; case "POST": builder.post(reqBody); break; case "PUT": builder.put(reqBody); break; default: Log.e(TAG, "mapToOkHttpRequest: WARNING: method: " + baseRequest.getMethod()); break; } req = builder.build(); return req; }
From source file:br.org.indt.ndg.servlets.PostSurveys.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStreamReader dis = new InputStreamReader(request.getInputStream(), "UTF-8"); DataOutputStream dos = new DataOutputStream(response.getOutputStream()); if (dis != null) { BufferedReader reader = new BufferedReader(dis); StringBuffer tempBuffer = new StringBuffer(); String line = null;// www . ja v a 2 s . c o m if (validateUser(request.getParameter("user"), request.getParameter("psw"))) { while ((line = reader.readLine()) != null) { tempBuffer.append(line + '\n'); } try { msmBD.postSurvey(request.getParameter("user"), tempBuffer, createTransactionLogVO(request), false); dos.writeBytes(SUCCESS); } catch (MSMApplicationException e) { dos.writeBytes(FAILURE); e.printStackTrace(); } catch (MSMSystemException e) { dos.writeBytes(FAILURE); e.printStackTrace(); } } else { dos.writeBytes(USERINVALID); } reader.close(); dos.close(); } else { dos.writeBytes(FAILURE); log.info("Failed processing stream from " + request.getRemoteAddr()); } }
From source file:com.sap.dirigible.runtime.registry.RepositoryServlet.java
@Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String repositoryPath = null; final OutputStream out = response.getOutputStream(); try {//from w w w. j a v a 2 s. c om repositoryPath = extractRepositoryPath(request); IEntity entity = getEntity(repositoryPath, request); if (entity == null) { doPost(request, response); } else { if (entity instanceof IResource) { ByteArrayOutputStream buff = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), buff); byte[] data = buff.toByteArray(); IResource resource = (IResource) entity; resource.setContent(data); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, THERE_IS_AN_EXISTING_COLLECTION_AT_THE_SAME_LOCATION); } } } catch (IllegalArgumentException ex) { logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()); } catch (MissingResourceException ex) { logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage()); response.sendError(HttpServletResponse.SC_NO_CONTENT, ex.getMessage()); } finally { out.flush(); out.close(); } }