List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:org.grails.plugin.platform.events.push.EventsPushHandler.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { InputStream stream = req.getInputStream(); final String topic = readPacket(stream); if (topic == null || topic.isEmpty()) { return;//from w ww. j av a 2s . c o m } final String type = readPacket(stream); if (type == null || type.isEmpty()) { return; } if (type.equals(TYPE_STRING)) { grailsEvents.event(topic, readPacket(stream), EventsPushConstants.FROM_BROWSERS, null, null, null); } else if (type.equals(TYPE_JSON)) { grailsEvents.event(topic, new JsonSlurper().parse(new BufferedReader(new InputStreamReader(stream))), EventsPushConstants.FROM_BROWSERS, null, null, null); } else if (type.equals(TYPE_BINARY)) { PipedOutputStream pipeOut = new PipedOutputStream(); PipedInputStream pipeIn = new PipedInputStream(pipeOut, 4096); grailsEvents.event(topic, pipeIn, EventsPushConstants.FROM_BROWSERS, null, null, null); IOUtils.copy(stream, pipeOut); pipeOut.close(); } else if (type.equals(TYPE_REGISTER)) { AtmosphereResource targetResource = null; for (AtmosphereResource r : broadcasterFactory.lookup(EventsPushConstants.GLOBAL_TOPIC) .getAtmosphereResources()) { if (r.uuid().equalsIgnoreCase(((AtmosphereRequest) req).resource().uuid())) { targetResource = r; break; } } if (targetResource != null) { targetResource.addEventListener( new AtmosphereRegistrationsHandler(registerTopics(topic, targetResource))); } } else if (type.equals(TYPE_UNREGISTER)) { } }
From source file:com.datatorrent.lib.io.HttpInputOperatorTest.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test//from w ww. j av a 2 s.c o m public void testHttpInputModule() throws Exception { final List<String> receivedMessages = new ArrayList<String>(); Handler handler = new AbstractHandler() { int responseCount = 0; @Override 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("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Transfer-Encoding", "chunked"); try { JSONObject json = new JSONObject(); json.put("responseId", "response" + ++responseCount); byte[] bytes = json.toString().getBytes(); response.getOutputStream().println(bytes.length); response.getOutputStream().write(bytes); response.getOutputStream().println(); response.getOutputStream().println(0); response.getOutputStream().flush(); } catch (JSONException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating response: " + e.toString()); } ((Request) request).setHandled(true); } }; Server server = new Server(0); server.setHandler(handler); server.start(); String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext"; System.out.println(url); final AbstractHttpInputOperator operator = new HttpJsonChunksInputOperator(); CollectorTestSink sink = new CollectorTestSink(); operator.outputPort.setSink(sink); operator.setName("testHttpInputNode"); 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 emmitted", sink.collectedTuples.size() > 0); Map<String, String> tuple = (Map<String, String>) sink.collectedTuples.get(0); Assert.assertEquals("", tuple.get("responseId"), "response1"); operator.deactivate(); operator.teardown(); server.stop(); }
From source file:com.datatorrent.lib.io.HttpJsonChunksInputOperatorTest.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test//from w w w . j av a 2s . c o m public void testHttpInputModule() throws Exception { final List<String> receivedMessages = new ArrayList<String>(); Handler handler = new AbstractHandler() { int responseCount = 0; @Override 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("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Transfer-Encoding", "chunked"); try { JSONObject json = new JSONObject(); json.put("responseId", "response" + ++responseCount); byte[] bytes = json.toString().getBytes(); response.getOutputStream().println(bytes.length); response.getOutputStream().write(bytes); response.getOutputStream().println(); response.getOutputStream().println(0); response.getOutputStream().flush(); } catch (JSONException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating response: " + e.toString()); } ((Request) request).setHandled(true); } }; Server server = new Server(0); server.setHandler(handler); server.start(); String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext"; final AbstractHttpInputOperator operator = new HttpJsonChunksInputOperator(); CollectorTestSink sink = new CollectorTestSink(); operator.outputPort.setSink(sink); 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); Map<String, String> tuple = (Map<String, String>) sink.collectedTuples.get(0); Assert.assertEquals("", tuple.get("responseId"), "response1"); operator.deactivate(); operator.teardown(); server.stop(); }
From source file:com.jaspersoft.jasperserver.rest.services.RESTJob.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { try {//w w w. jav a 2s. c om StringWriter sw = new StringWriter(); Job job = restUtils.unmarshal(Job.class, req.getInputStream()); if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserDetails) { UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); job.setUsername(userDetails.getUsername()); } try { job = reportSchedulerService.scheduleJob(job); } catch (AxisFault axisFault) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "could not schedule job to report: " + job.getReportUnitURI() + ". check job parameters\n" + axisFault.getMessage()); } restUtils.getMarshaller(Job.class).marshal(job, sw); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, sw.toString()); // job is a unique case where we return the descriptor } catch (AxisFault axisFault) { throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, axisFault.getMessage()); } catch (IOException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (JAXBException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "please check the request job descriptor"); } }
From source file:com.intel.cosbench.driver.handler.TriggerHandler.java
@Override protected Response process(HttpServletRequest req, HttpServletResponse res) throws Exception { scriptLog = ""; Scanner scanner = new Scanner(req.getInputStream()); String trigger = getTrigger(scanner); runTrigger(trigger);/*from w w w . j a v a2s . co m*/ return createResponse(); }
From source file:org.eclipse.jgit.lfs.server.fs.ObjectUploadListener.java
/** * @param repository/*w w w . ja v a 2 s .c o m*/ * the repository storing large objects * @param context * @param request * @param response * @param id * @throws FileNotFoundException * @throws IOException */ public ObjectUploadListener(FileLfsRepository repository, AsyncContext context, HttpServletRequest request, HttpServletResponse response, AnyLongObjectId id) throws FileNotFoundException, IOException { this.context = context; this.response = response; this.in = request.getInputStream(); this.inChannel = Channels.newChannel(in); this.out = repository.getOutputStream(id); this.channel = Channels.newChannel(out); response.setContentType(Constants.CONTENT_TYPE_GIT_LFS_JSON); }
From source file:com.examples.abelanav2.BucketNotificationServlet.java
@Override public final void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { // Decode the name and bucket of the notification BucketNotification notification;// ww w. j av a 2 s .c o m try { String jsonString = IOUtils.toString(req.getInputStream()); notification = new Gson().fromJson(jsonString, BucketNotification.class); } catch (IOException e) { log("Failed to decode the notification: " + e.getMessage()); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { if (!req.getHeader("X-Goog-Channel-Token").equals(ConfigurationConstants.SECRET_NOTIF_TOKEN)) { resp.setStatus(HttpStatusCodes.STATUS_CODE_FORBIDDEN); return; } if (!req.getHeader("X-Goog-Resource-State").equals("exists")) { resp.getWriter().write("This is not a new photo addition."); resp.setStatus(HttpStatusCodes.STATUS_CODE_OK); return; } // Handle duplicated notifications, drop keys after 5 minutes Boolean inCache = false; Cache cache = null; try { CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory(); Map<Object, Object> properties = new HashMap<>(); properties.put(GCacheFactory.EXPIRATION_DELTA, TimeUnit.MINUTES.toSeconds(5)); properties.put(MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT, true); cache = cacheFactory.createCache(properties); inCache = (Boolean) cache.get(notification.getName()); } catch (CacheException e) { log("Failed to instantiate the Memcache, risk of duplicate notifications: " + e.getMessage()); } if (inCache == null || !inCache) { // Add a new task to the queue Queue queue = QueueFactory.getDefaultQueue(); queue.add(TaskOptions.Builder.withUrl("/notice/incoming-image") .param("bucket", notification.getBucket()).param("name", notification.getName())); if (cache != null) { cache.put(notification.getName(), true); } resp.getWriter().write("Task added to the queue"); log("Task created for bucket " + notification.getBucket() + " and file " + notification.getName()); } else { resp.getWriter().write("This is a duplicate notification"); log("Duplicate notification for bucket " + notification.getBucket() + " and file " + notification.getName()); } resp.setStatus(HttpStatusCodes.STATUS_CODE_OK); } catch (IOException e) { log("Error while writing the response"); resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } }
From source file:io.robusta.rra.controller.SpringController.java
/** * set the entity to a request attribut/*from w w w. jav a 2 s .c o m*/ * * @param request * @return * @throws IOException */ @ModelAttribute("representation") String representation(HttpServletRequest request) throws IOException { String contentType = request.getContentType(); if (contentType != null && contentType.contains("application/json")) { InputStream in = request.getInputStream(); StringBuffer stringBuffer = new StringBuffer(); int d; while ((d = in.read()) != -1) { stringBuffer.append((char) d); } System.out.println(stringBuffer.toString()); System.out.println(Rra.defaultRepresentation instanceof GsonRepresentation); request.setAttribute("representation", stringBuffer.toString()); } return "representation"; }
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private HttpEntity createHttpEntity(HttpServletRequest request) throws FileUploadException, IOException { if (ServletFileUpload.isMultipartContent(request)) { return createMultipartEntity(request); } else {/*from ww w . j a v a2 s . c o m*/ return new BufferedHttpEntity( new InputStreamEntity(request.getInputStream(), request.getContentLength())); } }
From source file:org.fusesource.restygwt.examples.server.PizzaServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Processing Pizza Order..."); try {//from ww w.ja v a 2 s .c o m ObjectMapper mapper = new ObjectMapper(); PizzaOrder order = mapper.readValue(req.getInputStream(), PizzaOrder.class); StringWriter sw = new StringWriter(); mapper.writeValue(sw, order); System.out.println("Request: " + sw.toString()); OrderConfirmation confirmation = new OrderConfirmation(); confirmation.order_id = 123123; confirmation.order = order; confirmation.price = 27.54; confirmation.ready_time = System.currentTimeMillis() + 1000 * 60 * 30; // in // 30 // min. sw = new StringWriter(); mapper.writeValue(sw, confirmation); System.out.println("Response: " + sw.toString()); resp.setContentType(Resource.CONTENT_TYPE_JSON); mapper.writeValue(resp.getOutputStream(), confirmation); System.out.println("Pizza Order Confirimed: " + confirmation.order_id); } catch (Throwable e) { e.printStackTrace(); } finally { System.out.flush(); System.err.flush(); } }