List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:com.faces.controller.VerifyController.java
@RequestMapping(value = "/snapshot") public ModelAndView verifySnapshot(HttpServletRequest request, HttpServletResponse response) { mav = new ModelAndView(); try {//from www .j a v a 2 s. c o m long time = new Date().getTime(); FileOutputStream fileOutputStream = new FileOutputStream(fileStoreURL + "/" + time + ".jpg"); int res; while ((res = request.getInputStream().read()) != -1) { fileOutputStream.write(res); } fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { } return mav; }
From source file:com.google.sampling.experiential.server.PubExperimentServlet.java
private void processJsonUpload(HttpServletRequest req, HttpServletResponse resp, String email) throws IOException { String postBodyString;//from w w w. j a v a 2s. c o m try { postBodyString = org.apache.commons.io.IOUtils.toString(req.getInputStream(), "UTF-8"); } catch (IOException e) { log.info("IO Exception reading post data stream: " + e.getMessage()); throw e; } if (postBodyString.equals("")) { throw new IllegalArgumentException("Empty Post body"); } String appIdHeader = req.getHeader("http.useragent"); String pacoVersion = req.getHeader("paco.version"); log.info("Paco version = " + pacoVersion); String results = EventJsonUploadProcessor.create().processJsonEvents(postBodyString, email, appIdHeader, pacoVersion); resp.setContentType("application/json;charset=UTF-8"); resp.getWriter().write(results); }
From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java
private String readRequest(HttpServletRequest request) { try {//from w ww. ja v a 2 s . co m StringBuffer sb = new StringBuffer(); if (request.getInputStream() != null) { request.getInputStream().reset(); InputStreamReader isr = new UTF8InputStreamReaderWrapper(request.getInputStream()); BufferedReader br = new BufferedReader(isr); String thisLine; while ((thisLine = br.readLine()) != null) { sb.append(thisLine); } br.close(); } return sb.toString(); } catch (Throwable ex) { return null; } }
From source file:com.datatorrent.lib.io.HttpOutputOperatorTest.java
@Test public void testHttpOutputNode() throws Exception { final List<String> receivedMessages = new ArrayList<String>(); Handler handler = new AbstractHandler() { @Override/*from w ww .jav a 2 s . c o m*/ @Consumes({ MediaType.APPLICATION_JSON }) public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), bos); receivedMessages.add(new String(bos.toByteArray())); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Thanks</h1>"); ((Request) request).setHandled(true); receivedMessage = true; } }; Server server = new Server(0); server.setHandler(handler); server.start(); String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext"; System.out.println("url: " + url); HttpOutputOperator<Object> node = new HttpOutputOperator<Object>(); node.setResourceURL(new URI(url)); node.setup(null); Map<String, String> data = new HashMap<String, String>(); data.put("somekey", "somevalue"); node.input.process(data); // Wait till the message is received or a maximum timeout elapses int timeoutMillis = 10000; while (!receivedMessage && timeoutMillis > 0) { timeoutMillis -= 20; Thread.sleep(20); } Assert.assertEquals("number requests", 1, receivedMessages.size()); System.out.println(receivedMessages.get(0)); JSONObject json = new JSONObject(data); Assert.assertTrue("request body " + receivedMessages.get(0), receivedMessages.get(0).contains(json.toString())); receivedMessages.clear(); String stringData = "stringData"; node.input.process(stringData); Assert.assertEquals("number requests", 1, receivedMessages.size()); Assert.assertEquals("request body " + receivedMessages.get(0), stringData, receivedMessages.get(0)); node.teardown(); server.stop(); }
From source file:com.datatorrent.lib.io.HttpLinesInputOperatorTest.java
@Test public void testHttpInputModule() throws Exception { final List<String> receivedMessages = new ArrayList<String>(); Handler handler = new AbstractHandler() { @Override//from ww w .j av a 2s. c o m public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), bos); receivedMessages.add(new String(bos.toByteArray())); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().println("Hello"); response.getOutputStream().println("World,"); response.getOutputStream().println("Big"); response.getOutputStream().println("Data!"); response.getOutputStream().flush(); ((Request) request).setHandled(true); } }; Server server = new Server(0); server.setHandler(handler); server.start(); String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext"; final HttpLinesInputOperator operator = new HttpLinesInputOperator(); CollectorTestSink<String> sink = TestUtils.setSink(operator.outputPort, new CollectorTestSink<String>()); operator.setUrl(new URI(url)); operator.setup(null); operator.activate(null); int timeoutMillis = 3000; while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) { operator.emitTuples(); timeoutMillis -= 20; Thread.sleep(20); } Assert.assertTrue("tuple emitted", sink.collectedTuples.size() > 0); Assert.assertEquals("", sink.collectedTuples.get(0), "Hello"); Assert.assertEquals("", sink.collectedTuples.get(1), "World,"); Assert.assertEquals("", sink.collectedTuples.get(2), "Big"); Assert.assertEquals("", sink.collectedTuples.get(3), "Data!"); operator.deactivate(); operator.teardown(); server.stop(); }
From source file:com.google.acre.servlet.ProxyPassServlet.java
/** * Sets up the given {@link PostMethod} to send the same standard POST * data 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} */// w ww . ja v a2s . co m private void handleStandardPost(HttpPost postMethodProxyRequest, HttpServletRequest hsr) throws IOException { HttpEntity re = new InputStreamEntity(hsr.getInputStream(), hsr.getContentLength()); postMethodProxyRequest.setEntity(re); }
From source file:com.datatorrent.lib.io.HttpPostOutputOperatorTest.java
@Test public void testHttpOutputNode() throws Exception { final List<String> receivedMessages = new ArrayList<String>(); Handler handler = new AbstractHandler() { @Override/*ww w . java 2 s.c om*/ @Consumes({ MediaType.APPLICATION_JSON }) public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), bos); receivedMessages.add(new String(bos.toByteArray())); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Thanks</h1>"); ((Request) request).setHandled(true); receivedMessage = true; } }; Server server = new Server(0); server.setHandler(handler); server.start(); String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext"; HttpPostOutputOperator<Object> node = new HttpPostOutputOperator<Object>(); node.setUrl(url); node.setup(null); Map<String, String> data = new HashMap<String, String>(); data.put("somekey", "somevalue"); node.input.process(data); // Wait till the message is received or a maximum timeout elapses int timeoutMillis = 10000; while (!receivedMessage && timeoutMillis > 0) { timeoutMillis -= 20; Thread.sleep(20); } Assert.assertEquals("number requests", 1, receivedMessages.size()); JSONObject json = new JSONObject(data); Assert.assertTrue("request body " + receivedMessages.get(0), receivedMessages.get(0).contains(json.toString())); receivedMessages.clear(); String stringData = "stringData"; node.input.process(stringData); Assert.assertEquals("number requests", 1, receivedMessages.size()); Assert.assertEquals("request body " + receivedMessages.get(0), stringData, receivedMessages.get(0)); node.teardown(); server.stop(); }
From source file:com.github.thesmartenergy.sparql.generate.api.Take.java
@GET public Response doGet(@Context Request r, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("accept") String accept) throws IOException { String message = IOUtils.toString(request.getInputStream()); // if content encoding is not text-based, then use base64 encoding // use con.getContentEncoding() for this String dturi = "http://www.w3.org/2001/XMLSchema#string"; String ct = request.getContentType(); if (ct != null) { dturi = "urn:iana:mime:" + ct; }/* www . ja v a2s. c o m*/ String queryuri = request.getHeader("SPARGL-Query"); String var = request.getHeader("SPARGL-Variable"); HttpURLConnection con; String query = null; try { URL obj = new URL(queryuri); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Accept", "application/sparql-generate"); con.setInstanceFollowRedirects(true); System.out.println("GET to " + queryuri + " returned " + con.getResponseCode()); InputStream in = con.getInputStream(); query = IOUtils.toString(in); } catch (IOException e) { return Response.status(Response.Status.BAD_REQUEST) .entity("Error while trying to access query at URI <" + queryuri + ">: " + e.getMessage()) .build(); } System.out.println("got query " + query); // parse the SPARQL-Generate query and create plan PlanFactory factory = new PlanFactory(); Syntax syntax = SPARQLGenerate.SYNTAX; SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, syntax); if (q.getBaseURI() == null) { q.setBaseURI("http://example.org/"); } RootPlan plan = factory.create(q); // create the initial model Model model = ModelFactory.createDefaultModel(); QuerySolutionMap initialBinding = new QuerySolutionMap(); TypeMapper typeMapper = TypeMapper.getInstance(); RDFDatatype dt = typeMapper.getSafeTypeByName(dturi); Node arqLiteral = NodeFactory.createLiteral(message, dt); RDFNode jenaLiteral = model.asRDFNode(arqLiteral); initialBinding.add(var, jenaLiteral); // execute the plan plan.exec(initialBinding, model); System.out.println(accept); if (!accept.equals("text/turtle") && !accept.equals("application/rdf+xml")) { List<Variant> vs = Variant .mediaTypes(new MediaType("application", "rdf+xml"), new MediaType("text", "turtle")).build(); Variant v = r.selectVariant(vs); accept = v.getMediaType().toString(); } System.out.println(accept); StringWriter sw = new StringWriter(); Response.ResponseBuilder res; if (accept.equals("application/rdf+xml")) { model.write(sw, "RDF/XML", "http://example.org/"); res = Response.ok(sw.toString(), "application/rdf+xml"); res.header("Content-Disposition", "filename= message.rdf;"); return res.build(); } else { model.write(sw, "TTL", "http://example.org/"); res = Response.ok(sw.toString(), "text/turtle"); res.header("Content-Disposition", "filename= message.ttl;"); return res.build(); } }
From source file:com.jaspersoft.jasperserver.rest.services.RESTRole.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { try {// w w w . j a v a2s. c om WSRole role = restUtils.unmarshal(WSRole.class, req.getInputStream()); role = restUtils.populateServiceObject(role); if (userAndRoleManagementService.findRoles(wsRoleToWSRoleSearchCriteria(role)).length == 0) { userAndRoleManagementService.putRole(role); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, ""); } else { throw new IllegalArgumentException( "can not create new role: " + role.getRoleName() + ". it already exists"); } } catch (Exception e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage()); } }
From source file:com.collective.celos.servlet.RegisterServlet.java
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException { try {//from ww w . j a v a 2 s . c om BucketID bucket = getRequestBucketID(req); RegisterKey key = getRequestKey(req); JsonNode value = Util.JSON_READER .readTree(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8)); try (StateDatabaseConnection connection = getStateDatabase().openConnection()) { connection.putRegister(bucket, key, value); } } catch (Exception e) { throw new ServletException(e); } }