Example usage for javax.servlet.http HttpServletRequest getInputStream

List of usage examples for javax.servlet.http HttpServletRequest getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getInputStream.

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:edu.umn.msi.tropix.transfer.http.server.HttpTransferControllerImpl.java

private void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    LOG.info("doPost called");
    final String uploadKey = request.getParameter(ServerConstants.KEY_PARAMETER_NAME);
    LOG.info("Key is " + uploadKey);
    try {/*  w w w.ja va2s  . co m*/
        fileKeyResolver.handleUpload(uploadKey, request.getInputStream());
        response.flushBuffer();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTJob.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//from  w w  w .j  a v a2s  . co  m
        long jobId = getJobId(restUtils.extractRepositoryUri(req.getPathInfo()));

        Job job = restUtils.unmarshal(Job.class, req.getInputStream());

        if (job.getId() != jobId) {
            if (log.isDebugEnabled()) {
                log.debug("job descriptor id " + job.getId() + " and request id " + jobId
                        + "do not match. assigning the request id to as the job id");
            }
            job.setId(jobId);
        }

        if (job.getVersion() == DISREGARD_VERSION && reportSchedulerService.getJob(jobId) != null) {
            Job oldJob = reportSchedulerService.getJob(jobId);
            job.setVersion(oldJob.getVersion());

        }
        reportSchedulerService.updateJob(job);
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, axisFault.getMessage());
    } catch (IOException e) {
        throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    }

}

From source file:com.google.sampling.experiential.server.ExperimentServlet.java

private void readExperimentDefinitions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String postBodyString;/*from w  ww.j ava 2  s .c  o m*/
    try {
        postBodyString = org.apache.commons.io.IOUtils.toString(req.getInputStream(), "UTF-8");
    } catch (IOException e) {
        final String msg = "IO Exception reading post data stream: " + e.getMessage();
        log.info(msg);
        List<Outcome> outcomes = createErrorOutcome(msg);
        resp.getWriter().println(ExperimentJsonUploadProcessor.toJson(outcomes));
        return;
    }

    if (postBodyString.equals("")) {
        List<Outcome> outcomes = createErrorOutcome("Empty Post body");
        resp.getWriter().println(ExperimentJsonUploadProcessor.toJson(outcomes));
        return;
    }

    String appIdHeader = req.getHeader("http.useragent");
    String pacoVersion = req.getHeader("paco.version");
    log.info("Paco version = " + pacoVersion);
    DateTimeZone timezone = TimeUtil.getTimeZoneForClient(req);
    final User whoFromLogin = AuthUtil.getWhoFromLogin();
    String results = ExperimentJsonUploadProcessor.create().processJsonExperiments(postBodyString, whoFromLogin,
            appIdHeader, pacoVersion, timezone);
    resp.getWriter().write(results);
}

From source file:com.portfolio.data.attachment.ConvertCSV.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try {//from   w  ww  .  j a  v  a  2 s .co  m
            request.getInputStream().close();
            response.setStatus(417);
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    initialize(request);
    response.setContentType("application/json");

    JSONObject data = new JSONObject();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        List<String[]> meta = new ArrayList<String[]>();
        List<List<String[]>> linesData = new ArrayList<List<String[]>>();

        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                if ("uploadfile".equals(fieldname)) // name="uploadfile"
                {
                    InputStreamReader isr = new InputStreamReader(item.getInputStream());
                    CSVReader reader = new CSVReader(isr, ';');
                    String[] headerLine;
                    String[] dataLine;

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    dataLine = reader.readNext();
                    if (dataLine == null)
                        break;

                    for (int i = 0; i < headerLine.length; ++i) {
                        data.put(headerLine[i], dataLine[i]);
                    }

                    headerLine = reader.readNext();
                    if (headerLine == null)
                        break;

                    JSONArray lines = new JSONArray();
                    while ((dataLine = reader.readNext()) != null) {
                        JSONObject lineInfo = new JSONObject();
                        for (int i = 0; i < headerLine.length; ++i) {
                            lineInfo.put(headerLine[i], dataLine[i]);
                        }
                        lines.put(lineInfo);
                    }

                    data.put("lines", lines);

                    isr.close();
                }
            }
        }
    } catch (Exception e) {

    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
        out.print(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
    }

}

From source file:de.elomagic.mag.ServletMock.java

@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    received = false;/*w w w  .  j  a va2s  .  c o  m*/

    lastContentLength = request.getContentLength();
    requestedUri = request.getRequestURI();

    if (lastContentLength > 0) {
        lastContent = IOUtils.readFully(request.getInputStream(), lastContentLength);
    }

    LOGGER.info("contentLength=" + FileUtils.byteCountToDisplaySize(lastContentLength));
    LOGGER.info("content" + lastContent);

    response.setStatus(HttpServletResponse.SC_CREATED);

    received = true;
}

From source file:es.tid.cep.esperanza.Events.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w  w  .j  a v a 2s . co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("events doPost");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json;charset=UTF-8");
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        sis.close();
        String eventText = new String(b);
        logger.debug("event as text:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> otro = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + otro);
        epService.getEPRuntime().sendEvent(otro, "iotEvent");
        logger.debug("event was sent: " + otro);
    } catch (JSONException je) {
        logger.debug("error: " + je.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:com.dreamwork.web.FrontJsonController.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestID = request.getHeader("RequestID");
    response.addHeader("RequestID", requestID);
    response.setContentType("text/json; charset=UTF-8");
    ServletInputStream in = request.getInputStream();
    ServletOutputStream out = response.getOutputStream();
    String req = "";
    try {/*from w w  w  . j a  va 2s.  com*/
        req = new String(read(in), "UTF-8");

        JSONObject jsonObject = new JSONObject(req);
        JSONObject requestJson = jsonObject.getJSONObject("request");
        String to = requestJson.getString("to");
        String date = requestJson.getString("date");
        String message = requestJson.getString("message");
        ServiceHolder.getService().receiveMessage(to, df.parse(date), message);

    } catch (JSONException e) {

    } catch (IOException e) {

    } catch (RuntimeException e) {

    } catch (Exception e) {

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.erudika.para.security.JWTRestfulAuthFilter.java

@SuppressWarnings("unchecked")
private boolean newTokenHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Response res = RestUtils.getEntity(request.getInputStream(), Map.class);
    if (res.getStatusInfo() != Response.Status.OK) {
        RestUtils.returnStatusResponse(response, res.getStatus(), res.getEntity().toString());
        return false;
    }// w  w w  .  j a  v a 2 s  .c  om
    Map<String, Object> entity = (Map<String, Object>) res.getEntity();
    String provider = (String) entity.get("provider");
    String appid = (String) entity.get("appid");
    String token = (String) entity.get("token");

    if (provider != null && appid != null && token != null) {
        App app = new App(appid);
        UserAuthentication userAuth = getOrCreateUser(app.getAppIdentifier(), provider, token);
        User user = SecurityUtils.getAuthenticatedUser(userAuth);
        if (user != null) {
            app = Para.getDAO().read(app.getId());
            if (app != null) {
                // issue token
                SignedJWT newJWT = SecurityUtils.generateJWToken(user, app);
                if (newJWT != null) {
                    succesHandler(response, user, newJWT);
                    return true;
                }
            } else {
                RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
                        "User belongs to an app that does not exist.");
                return false;
            }
        } else {
            RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
                    "Failed to authenticate user with " + provider);
            return false;
        }
    }
    RestUtils.returnStatusResponse(response, HttpServletResponse.SC_BAD_REQUEST,
            "Some of the required query parameters 'provider', 'appid', 'token', are missing.");
    return false;
}

From source file:ch.sportchef.business.event.boundary.EventImageResource.java

@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadImage(@Context HttpServletRequest request) throws IOException, ServletException {
    final String contentType = request.getContentType();
    final byte[] boundary = contentType.substring(contentType.indexOf("boundary=") + 9).getBytes();

    try (final BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream(), 8192)) {
        final MultipartStream multipartStream = new MultipartStream(inputStream, boundary, 8192, null);
        boolean nextPart = multipartStream.skipPreamble();
        while (nextPart) {
            multipartStream.readHeaders(); // don't remove, strips headers off
            try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8192)) {
                multipartStream.readBodyData(outputStream);
                nextPart = multipartStream.readBoundary();
                final byte[] image = outputStream.toByteArray();
                eventImageService.uploadImage(eventId, image);
                return Response.ok().build();
            }/*w  ww . jav  a 2s  .c o m*/
        }
    }

    return Response.status(BAD_REQUEST).build();
}

From source file:de.betterform.agent.web.servlet.XFormsPostServlet.java

/**
 * read from the inputStream and parse that as DOM. The result is passed into a request attribute for
 * processing by the XFormsFilter./* w ww  . ja  va  2  s . c  o  m*/
 *
 * @param request  servlet request
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.debug("hit XFormsPostServlet");

    request.setCharacterEncoding("UTF-8");
    WebUtil.nonCachingResponse(response);

    Document doc;
    try {
        //parse it
        doc = DOMUtil.parseInputStream(request.getInputStream(), true, false);
    } catch (ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (SAXException e) {
        throw new ServletException(e);
    }

    //do the Filter twist
    request.setAttribute(WebFactory.XFORMS_NODE, doc);
    request.setAttribute(XFormsPostServlet.INIT_BY_POST, doc);
    response.getOutputStream().close();
}