List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:com.github.vatbub.vatbubgitreports.Main.java
public void doPost(HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/json"); PrintWriter writer;// ww w .ja v a 2 s .c o m Gson gson = new GsonBuilder().setPrettyPrinting().create(); StringBuilder requestBody = new StringBuilder(); String line; try { writer = response.getWriter(); } catch (IOException e) { Internet.sendErrorMail("getWriter", "Unable not read request", e, gMailUsername, gMailPassword); e.printStackTrace(); response.setStatus(500); return; } try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { requestBody.append(line); } } catch (IOException e) { Error error = new Error(e.getClass().getName() + " occurred while reading the request", ExceptionUtils.getFullStackTrace(e)); writer.write(gson.toJson(error)); response.setStatus(500); Internet.sendErrorMail("ReadRequestBody", requestBody.toString(), e, gMailUsername, gMailPassword); return; } // parse the request if (!request.getContentType().equals("application/json")) { // bad content type Error error = new Error("content type must be application/json"); writer.write(gson.toJson(error)); } GitHubIssue gitHubIssue; try { System.out.println("Received request:"); System.out.println(requestBody.toString()); System.out.println("Request encoding is: " + request.getCharacterEncoding()); gitHubIssue = gson.fromJson(requestBody.toString(), GitHubIssue.class); } catch (Exception e) { Internet.sendErrorMail("ParseJSON", requestBody.toString(), e, gMailUsername, gMailPassword); Error error = new Error(e.getClass().getName() + " occurred while parsing the request", ExceptionUtils.getFullStackTrace(e)); writer.write(gson.toJson(error)); response.setStatus(500); return; } // Authenticate on GitHub GitHubClient client = new GitHubClient(); client.setOAuth2Token(System.getenv("GITHUB_ACCESS_TOKEN")); // Convert the issue object Issue issue = new Issue(); issue.setTitle(gitHubIssue.getTitle()); String body = ""; boolean metadataGiven = false; if (!gitHubIssue.getReporterName().equals("")) { body = "Reporter name: " + gitHubIssue.getReporterName() + "\n"; metadataGiven = true; } if (!gitHubIssue.getReporterEmail().equals("")) { body = body + "Reporter email: " + gitHubIssue.getReporterEmail() + "\n"; metadataGiven = true; } if (gitHubIssue.getLogLocation() != null) { body = body + "Log location: " + gitHubIssue.getLogLocation() + "\n"; metadataGiven = true; } if (gitHubIssue.getScreenshotLocation() != null) { body = body + "Screenshot location: " + gitHubIssue.getScreenshotLocation() + "\n"; metadataGiven = true; } if (gitHubIssue.getThrowable() != null) { body = body + "Exception stacktrace:\n" + ExceptionUtils.getFullStackTrace(gitHubIssue.getThrowable()) + "\n"; metadataGiven = true; } if (metadataGiven) { body = body + "----------------------------------" + "\n\nDESCRIPTION:\n"; } body = body + gitHubIssue.getBody(); issue.setBody(body); // send the issue to GitHub try { new IssueService(client).createIssue(gitHubIssue.getToRepo_Owner(), gitHubIssue.getToRepo_RepoName(), issue); } catch (IOException e) { e.printStackTrace(); Error error = new Error(e.getClass().getName() + " occurred while parsing the request", ExceptionUtils.getFullStackTrace(e)); writer.write(gson.toJson(error)); response.setStatus(500); Internet.sendErrorMail("ForwardToGitHub", requestBody.toString(), e, gMailUsername, gMailPassword); return; } writer.write(gson.toJson(issue)); }
From source file:io.druid.server.AsyncManagementForwardingServletTest.java
private static Server makeTestServer(int port, ExpectedRequest expectedRequest) { Server server = new Server(port); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(new ServletHolder(new HttpServlet() { @Override//from w w w. j a v a 2 s. com protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { handle(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { handle(req, resp); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { handle(req, resp); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { handle(req, resp); } private void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException { boolean passed = expectedRequest.path.equals(req.getRequestURI()); passed &= expectedRequest.query == null || expectedRequest.query.equals(req.getQueryString()); passed &= expectedRequest.method.equals(req.getMethod()); if (expectedRequest.headers != null) { for (Map.Entry<String, String> header : expectedRequest.headers.entrySet()) { passed &= header.getValue().equals(req.getHeader(header.getKey())); } } passed &= expectedRequest.body == null || expectedRequest.body.equals(IOUtils.toString(req.getReader())); expectedRequest.called = true; resp.setStatus(passed ? 200 : 400); } }), "/*"); server.setHandler(handler); return server; }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same content POST * data (JSON, XML, etc.) as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */// www. j a va 2s . com private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException, ServletException { StringBuilder content = new StringBuilder(); BufferedReader reader = httpServletRequest.getReader(); for (;;) { String line = reader.readLine(); if (line == null) break; content.append(line); } String contentType = httpServletRequest.getContentType(); String postContent = content.toString(); if (contentType.startsWith("text/x-gwt-rpc")) { String clientHost = httpServletRequest.getLocalName(); if (clientHost.equals("127.0.0.1")) { clientHost = "localhost"; } int clientPort = httpServletRequest.getLocalPort(); String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : ""); String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "") + httpServletRequest.getServletPath(); //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")"); postContent = postContent.replace(clientUrl, serverUrl); } String encoding = httpServletRequest.getCharacterEncoding(); debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent); StringRequestEntity entity; try { entity = new StringRequestEntity(postContent, contentType, encoding); } catch (UnsupportedEncodingException e) { throw new ServletException(e); } // Set the proxy request POST data postMethodProxyRequest.setRequestEntity(entity); }
From source file:org.apache.marmotta.platform.sparql.webservices.SparqlWebService.java
/** * Execute a SPARQL 1.1 tuple query on the LMF triple store using the query passed in the body of the * POST request. Result will be formatted using the result type passed as argument (either "html", "json" or "xml"). * <p/>//from www . j a v a 2 s . co m * see SPARQL 1.1 Query syntax at http://www.w3.org/TR/sparql11-query/ * * @param request the servlet request (to retrieve the SPARQL 1.1 Query passed in the body of the POST request) * @param resultType the format for serializing the query results ("html", "json", or "xml") * @HTTP 200 in case the query was executed successfully * @HTTP 500 in case there was an error during the query evaluation * @return the query result in the format passed as argument */ @POST @Path(SELECT) public Response selectPost(@QueryParam("output") String resultType, @Context HttpServletRequest request) { try { if (resultType != null && outputMapper.containsKey(resultType)) resultType = outputMapper.get(resultType); if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("utf-8"); } String query = CharStreams.toString(request.getReader()); //String query = IOUtils.toString(request.getInputStream(),"utf-8"); log.debug("Query: {}", query); return select(query, resultType, request); } catch (IOException e) { log.error("body not found", e); return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } }
From source file:org.alfresco.repo.webdav.auth.BaseAuthenticationFilter.java
/** * Handles the login form directly, allowing management of the session user. * //from w w w.j a va2 s . co m * @param req * the request * @param res * the response * @throws IOException * Signals that an I/O exception has occurred. * @throws ServletException * on error */ protected boolean handleLoginForm(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (getLogger().isDebugEnabled()) getLogger().debug("Handling the login form."); // Invalidate current session HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); } StringBuilder out = new StringBuilder(1024); Reader in = req.getReader(); char[] buff = new char[1024]; int charsRead; while ((charsRead = in.read(buff)) != -1) { out.append(buff, 0, charsRead); } in.close(); try { JSONObject json = new JSONObject(out.toString()); String username = json.getString("username"); String password = json.getString("password"); if (username == null || username.length() == 0) { if (getLogger().isDebugEnabled()) getLogger().debug("Username not specified in the login form."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username not specified"); return false; } if (password == null) { if (getLogger().isDebugEnabled()) getLogger().debug("Password not specified in the login form."); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Password not specified"); return false; } authenticationService.authenticate(username, password.toCharArray()); session = req.getSession(); createUserEnvironment(session, username, authenticationService.getCurrentTicket(), false); res.setStatus(HttpServletResponse.SC_NO_CONTENT); return true; } catch (AuthenticationException e) { if (getLogger().isDebugEnabled()) getLogger().debug("Login failed", e); res.sendError(HttpServletResponse.SC_FORBIDDEN, "Login failed"); } catch (JSONException jErr) { if (getLogger().isDebugEnabled()) getLogger().debug("Unable to parse JSON POST body", jErr); res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse JSON POST body: " + jErr.getMessage()); } return false; }
From source file:com.centurylink.mdw.hub.servlet.RestServlet.java
protected String handleRequest(HttpServletRequest request, HttpServletResponse response, Map<String, String> metaInfo) throws ServiceException, IOException { if (logger.isMdwDebugEnabled()) { logger.mdwDebug(/*from w w w .j a v a 2 s. c om*/ getClass().getSimpleName() + " " + request.getMethod() + ":\n " + request.getRequestURI() + (request.getQueryString() == null ? "" : ("?" + request.getQueryString()))); } String requestString = null; // DELETE can have a body in some containers if (!"GET".equalsIgnoreCase(request.getMethod())) { BufferedReader reader = request.getReader(); StringBuffer requestBuffer = new StringBuffer( request.getContentLength() < 0 ? 0 : request.getContentLength()); String line; while ((line = reader.readLine()) != null) requestBuffer.append(line).append('\n'); // log request requestString = requestBuffer.toString(); if (logger.isMdwDebugEnabled()) { logger.mdwDebug( getClass().getSimpleName() + " " + request.getMethod() + " Request:\n" + requestString); } } authenticate(request, metaInfo, requestString); if (metaInfo.containsKey(Listener.METAINFO_REQUEST_PAYLOAD)) { requestString = metaInfo.get(Listener.METAINFO_REQUEST_PAYLOAD); metaInfo.remove(Listener.METAINFO_REQUEST_PAYLOAD); } Set<String> reqHeaderKeys = new HashSet<String>(metaInfo.keySet()); String responseString = new ListenerHelper().processEvent(requestString, metaInfo); populateResponseHeaders(reqHeaderKeys, metaInfo, response); if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) == null) response.setContentType("application/json"); else response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE)); if (metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE) != null && !metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE).equals("0")) response.setStatus(Integer.parseInt(metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE))); if (logger.isMdwDebugEnabled()) { logger.mdwDebug( getClass().getSimpleName() + " " + request.getMethod() + " Response:\n" + responseString); } return responseString; }
From source file:org.o3project.odenos.remoteobject.rest.servlet.SubscriptionsServlet.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); // this "obj" separated for casting warning avoidance. Object obj = session.getAttribute(Attributes.SUBSCRIPTION_TABLE); @SuppressWarnings("unchecked") Map<String, Set<String>> origTable = (Map<String, Set<String>>) obj; if (origTable == null) { this.logger.debug("A Subscription Table is not found. /{}", session.getId()); resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/*from w w w .ja v a 2 s . c o m*/ } String reqBody = IOUtils.toString(req.getReader()); Map<String, Set<String>> reqTable = this.deserialize(reqBody); if (reqTable == null) { this.logger.debug("Failed to deserialize the request body. /{}", reqBody); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } Map<String, Collection<String>> addedMap = new HashMap<String, Collection<String>>(); Map<String, Collection<String>> removedMap = new HashMap<String, Collection<String>>(); for (Entry<String, Set<String>> reqEntry : reqTable.entrySet()) { String objectId = reqEntry.getKey(); Set<String> reqEvents = reqEntry.getValue(); Set<String> origEvents = origTable.get(objectId); if (origEvents == null) { // All events are unregistered yet. addedMap.put(objectId, reqEvents); origTable.put(objectId, reqEvents); continue; } // generating diff. @SuppressWarnings("unchecked") Collection<String> added = (Collection<String>) CollectionUtils.subtract(reqEvents, origEvents); addedMap.put(objectId, added); @SuppressWarnings("unchecked") Collection<String> removed = (Collection<String>) CollectionUtils.subtract(origEvents, reqEvents); removedMap.put(objectId, removed); } session.setAttribute(Attributes.SUBSCRIPTION_TABLE, reqTable); RESTTranslator translator = (RESTTranslator) req.getServletContext() .getAttribute(Attributes.REST_TRANSLATOR); translator.modifyDistributionSetting(this.subscriptionId, addedMap, removedMap); resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().write(toJsonStringFrom(reqTable)); }
From source file:org.nunux.poc.portal.ProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same content POST data * (JSON, XML, etc.) as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the POST data to be sent via the {@link PostMethod} *///ww w.ja va 2 s .c om private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws IOException, ServletException { StringBuilder content = new StringBuilder(); BufferedReader reader = httpServletRequest.getReader(); for (;;) { String line = reader.readLine(); if (line == null) { break; } content.append(line); } String contentType = httpServletRequest.getContentType(); String postContent = content.toString(); if (contentType.startsWith("text/x-gwt-rpc")) { String clientHost = httpServletRequest.getLocalName(); if (clientHost.equals("127.0.0.1")) { clientHost = "localhost"; } int clientPort = httpServletRequest.getLocalPort(); String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : ""); String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "") + httpServletRequest.getServletPath(); //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")"); postContent = postContent.replace(clientUrl, serverUrl); } String encoding = httpServletRequest.getCharacterEncoding(); debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent); StringRequestEntity entity; try { entity = new StringRequestEntity(postContent, contentType, encoding); } catch (UnsupportedEncodingException e) { throw new ServletException(e); } // Set the proxy request POST data postMethodProxyRequest.setRequestEntity(entity); }
From source file:fsi_admin.JPacConn.java
private void ingresarRegistroFallido(String IP, String host, String servidor, String usuario, String password, HttpServletRequest request, String error, int nivelError) { StringBuffer sb = new StringBuffer(); BufferedReader bufferedReader = null; try {// ww w. jav a2 s. c o m bufferedReader = request.getReader(); char[] charBuffer = new char[128]; int bytesRead; while ((bytesRead = bufferedReader.read(charBuffer)) != -1) { sb.append(charBuffer, 0, bytesRead); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } //System.out.println(sb.toString()); Calendar cal = GregorianCalendar.getInstance(); String SQL = "INSERT INTO TBL_PAC_REGISTROS_FALLIDOS\n"; SQL += "VALUES(default,'" + JUtil.q(IP) + "','" + JUtil.q(host) + "','" + JUtil.obtFechaHoraSQL(cal) + "','" + (servidor != null ? JUtil.q(servidor) : "nulo") + "','" + (usuario != null ? JUtil.q(usuario) : "nulo") + "','" + (password != null ? JUtil.q(password) : "nulo") + "','" + JUtil.q(sb.toString()) + "','" + JUtil.q(error) + "','" + nivelError + "','PAC')"; try { Connection con = JAccesoBD.getConexion(); Statement s = con.createStatement(); s.executeUpdate(SQL); s.close(); JAccesoBD.liberarConexion(con); } catch (SQLException e) { e.printStackTrace(); } }
From source file:com.googlecode.noweco.calendar.CaldavServlet.java
public void doPropfind(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { Unmarshaller unMarshaller = createUnmarshaller(); Marshaller marshaller = createMarshaller(); Propfind propfind = null;/*from w w w . j a v a 2s . c o m*/ try { propfind = (Propfind) unMarshaller.unmarshal(req.getReader()); } catch (JAXBException e) { throw new CalendarException("Unable to parse request", e); } if (LOGGER.isTraceEnabled()) { try { StringWriter writer = new StringWriter(); marshaller.marshal(propfind, writer); LOGGER.trace("receive :\n{}", writer.toString()); } catch (JAXBException e) { // ignore } } Prop reqProp = propfind.getProp(); Multistatus multistatus = new Multistatus(); int status = propFind(multistatus, reqProp, req.getHeader("Depth"), req.getRequestURI()); if (status != HttpServletResponse.SC_OK) { resp.sendError(status); return; } resp.setStatus(SC_MULTI_STATUS); resp.setContentType("text/xml;charset=\"UTF-8\""); PrintWriter httpWriter = resp.getWriter(); try { Writer writer; if (LOGGER.isTraceEnabled()) { writer = new StringWriter(); } else { writer = httpWriter; } marshaller.marshal(multistatus, writer); if (LOGGER.isTraceEnabled()) { String string = writer.toString(); LOGGER.trace("send :\n{}", string); httpWriter.write(string); } } catch (JAXBException e) { throw new CalendarException("Unable to format response", e); } httpWriter.close(); }