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:com.kysoft.cpsi.audit.controller.SelfCheckAjaxUploadController.java

/**
 * @param request//  www. j a v a  2 s . co m
 * @param files
 * @return
 */
@RequestMapping(value = "selfCheckUpload", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> ajaxUpload(HttpServletRequest request, HttpServletResponse response, String owner,
        String col, String ownerKey, String hcrwId, String hcclName, String hcsxmc, Integer nd) {

    Map<String, Object> result = new HashedMap();

    InputStream is = null;

    String filename = request.getHeader("X-File-Name");
    try {
        is = request.getInputStream();
        String mongoId = null;

        Map<String, Object> params = new HashedMap();
        params.put("dxnType", 2);
        Map<String, Object> dxnHccl2 = selfCheckService.getDXNHccl(params);
        params.put("dxnType", 1);
        Map<String, Object> dxnHccl1 = selfCheckService.getDXNHccl(params);
        if (hcclName.equals(dxnHccl2.get("NAME").toString())
                && hcsxmc.equals(dxnHccl2.get("HCSXMC").toString())) {
            //?
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            // ?
            InputStream is1 = new ByteArrayInputStream(baos.toByteArray());
            InputStream is2 = new ByteArrayInputStream(baos.toByteArray());
            //?
            selfCheckService.uploadSelfCheckData(is2, hcrwId, filename, nd);

            //?MONGODB
            mongoId = FileUploadUtils.mongoUpload(is1, filename, owner, ownerKey);
        } else if (hcclName.equals(dxnHccl1.get("NAME").toString())
                && hcsxmc.equals(dxnHccl1.get("HCSXMC").toString())) {
            //???
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();

            // ?
            InputStream is1 = new ByteArrayInputStream(baos.toByteArray());
            InputStream is2 = new ByteArrayInputStream(baos.toByteArray());

            //?
            if (filename.endsWith("xls") || filename.endsWith("xlsx")) {
                selfCheckService.judgeRepeatExcle(is2, 5, 2, filename);
            }

            //?MONGODB
            mongoId = FileUploadUtils.mongoUpload(is1, filename, owner, ownerKey);
        } else {
            mongoId = FileUploadUtils.mongoUpload(is, filename, owner, ownerKey);
        }

        FileUploadUtils.updateOwner(owner, col, ownerKey, mongoId);

        response.setStatus(HttpServletResponse.SC_OK);
        result.put("status", 1);
        result.put("mongoId", mongoId);
        result.put("message", "??");

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_OK);
        ex.printStackTrace();
        result.put("status", -1);
        result.put("mongoId", "");
        result.put("message", "??" + ex.getMessage());
        MongoLogger.warn("??", ExceptionUtils.getStackTrace(ex), hcrwId);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
    return result;
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.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}
 *//*from  w w  w. j a  va2s .co  m*/
@SuppressWarnings("unchecked")
private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) {
    try {
        postMethodProxyRequest.setRequestBody(httpServletRequest.getInputStream());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:be.fedict.trust.service.ocsp.OCSPResponderServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getContentType();
    if (false == OCSP_REQUEST_CONTENT_TYPE.equals(contentType)) {
        LOG.error("incorrect content type: " + contentType);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from   w w w  .j a v  a2s .  com*/
    }

    InputStream ocspRequestInputStream = request.getInputStream();
    OCSPReq ocspReq = new OCSPReq(ocspRequestInputStream);

    Req[] requestList = ocspReq.getRequestList();
    if (1 != requestList.length) {
        LOG.error("OCSP request list size not 1: " + requestList.length);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    Req ocspRequest = requestList[0];

    CertificateID certificateID = ocspRequest.getCertID();
    LOG.debug("certificate Id hash algo OID: " + certificateID.getHashAlgOID());
    if (false == CertificateID.HASH_SHA1.equals(certificateID.getHashAlgOID())) {
        LOG.debug("only supporting SHA1 hash algo");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    BigInteger serialNumber = certificateID.getSerialNumber();
    byte[] issuerNameHash = certificateID.getIssuerNameHash();
    byte[] issuerKeyHash = certificateID.getIssuerKeyHash();
    LOG.debug("serial number: " + serialNumber);
    LOG.debug("issuer name hash: " + new String(Hex.encodeHex(issuerNameHash)));
    LOG.debug("issuer key hash: " + new String(Hex.encodeHex(issuerKeyHash)));

    Date revocationDate = this.validationService.validate(serialNumber, issuerNameHash, issuerKeyHash);

    PrivateKeyEntry privateKeyEntry = this.validationService.getPrivateKeyEntry();
    if (null == privateKeyEntry) {
        LOG.debug("missing service identity");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PublicKey publicKey = certificate.getPublicKey();
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    try {
        BasicOCSPRespGenerator basicOCSPRespGenerator = new BasicOCSPRespGenerator(publicKey);
        CertificateStatus certificateStatus;
        if (null == revocationDate) {
            certificateStatus = CertificateStatus.GOOD;
        } else {
            certificateStatus = new RevokedStatus(revocationDate, CRLReason.unspecified);
        }
        basicOCSPRespGenerator.addResponse(certificateID, certificateStatus);
        BasicOCSPResp basicOCSPResp = basicOCSPRespGenerator.generate("SHA1WITHRSA", privateKey, null,
                new Date(), BouncyCastleProvider.PROVIDER_NAME);
        OCSPRespGenerator ocspRespGenerator = new OCSPRespGenerator();
        OCSPResp ocspResp = ocspRespGenerator.generate(OCSPRespGenerator.SUCCESSFUL, basicOCSPResp);
        response.setContentType("application/ocsp-response");
        response.getOutputStream().write(ocspResp.getEncoded());
    } catch (Exception e) {
        LOG.error("OCSP generator error: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
}

From source file:platform.filter.HttpPutDeleteFormContentFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (("PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())
            || "PATCH".equals(request.getMethod())) && isFormContentType(request)) {
        HttpInputMessage inputMessage = new ServletServerHttpRequest(request) {
            @Override//from w ww  .java 2  s  .  com
            public InputStream getBody() throws IOException {
                return request.getInputStream();
            }
        };
        MultiValueMap<String, String> formParameters = formConverter.read(null, inputMessage);
        HttpServletRequest wrapper = new HttpPutFormContentRequestWrapper(request, formParameters);
        filterChain.doFilter(wrapper, response);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:com.ids.servlets.OctetStreamReader.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*  w  w w  . jav a  2 s .  c om*/
 * @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 {

    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    String filename = request.getHeader("X-File-Name");
    filename.trim();
    try {
        is = request.getInputStream();
        System.out.println("Realpath = " + realPath + filename);
        fos = new FileOutputStream(new File(realPath + filename.trim()));
        IOUtils.copy(is, fos);
        //                        response.setHeader("X-File-Name", filename);
        response.setStatus(response.SC_OK);
        //      request.getSession().setAttribute("filename", filename);
        writer.print("{success: true    }");
    } catch (FileNotFoundException ex) {
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        writer.print("{success: false}");
        log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (IOException ex) {
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        writer.print("{success: false}");
        log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    } finally {
        try {
            fos.close();
            is.close();
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
    }

    writer.flush();
    writer.close();
}

From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    out.println();/*from  w ww  . j  a  va  2s  .c o m*/
    int fileSize = request.getContentLength();
    byte[] buf = new byte[fileSize];
    try {
        ServletInputStream is = request.getInputStream();
        is.read(buf);
        File file = new File(destinationDir, "LogisticNetwork.mxe");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buf);
        fos.close();
        out.close();
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

}

From source file:org.attribyte.api.pubsub.impl.server.BroadcastServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    long startNanos = System.nanoTime();

    byte[] broadcastContent = ByteStreams.toByteArray(request.getInputStream());

    long endNanos = System.nanoTime();

    String topicURL = request.getPathInfo();

    if (maxBodyBytes > 0 && broadcastContent.length > maxBodyBytes) {
        logNotification(request, topicURL, NOTIFICATION_TOO_LARGE.statusCode, null);
        Bridge.sendServletResponse(NOTIFICATION_TOO_LARGE, response);
        return;//www.j a  v  a 2  s .co  m
    }

    Response endpointResponse;
    if (topicURL != null) {
        if (filters.size() > 0) {
            String checkHeader = request.getHeader(BasicAuthScheme.AUTH_HEADER);
            for (BasicAuthFilter filter : filters) {
                if (filter.reject(topicURL, checkHeader)) {
                    logNotification(request, topicURL, Response.Code.UNAUTHORIZED, broadcastContent);
                    response.sendError(Response.Code.UNAUTHORIZED, "Unauthorized");
                    return;
                }
            }
        }

        try {

            Topic topic = topicCache != null ? topicCache.getIfPresent(topicURL) : null;
            if (topic == null) {
                topic = datastore.getTopic(topicURL, autocreateTopics);
                if (topicCache != null && topic != null) {
                    topicCache.put(topicURL, topic);
                }
            }

            if (topic != null) {
                NotificationMetrics globalMetrics = endpoint.getGlobalNotificationMetrics();
                NotificationMetrics metrics = endpoint.getNotificationMetrics(topic.getId());
                metrics.notificationSize.update(broadcastContent.length);
                globalMetrics.notificationSize.update(broadcastContent.length);
                long acceptTimeNanos = endNanos - startNanos;
                metrics.notifications.update(acceptTimeNanos, TimeUnit.NANOSECONDS);
                globalMetrics.notifications.update(acceptTimeNanos, TimeUnit.NANOSECONDS);
                Notification notification = new Notification(topic, null, broadcastContent); //No custom headers...

                final boolean queued = endpoint.enqueueNotification(notification);
                if (queued) {
                    if (replicationTopic != null) {
                        final boolean replicationQueued = endpoint
                                .enqueueNotification(new Notification(replicationTopic,
                                        Collections.singleton(
                                                new Header(REPLICATION_TOPIC_HEADER, topic.getURL())),
                                        broadcastContent));
                        if (!replicationQueued) { //What to do?
                            logger.error("Replication failure due to notification capacity limits!");
                        }
                    }
                    if (!jsonEnabled) {
                        endpointResponse = ACCEPTED_RESPONSE;
                    } else {
                        ResponseBuilder builder = new ResponseBuilder();
                        builder.setStatusCode(ACCEPTED_RESPONSE.statusCode);
                        builder.addHeader("Content-Type", ServerUtil.JSON_CONTENT_TYPE);
                        ObjectNode responseNode = JsonNodeFactory.instance.objectNode();
                        ArrayNode idsNode = responseNode.putArray("messageIds");
                        idsNode.add(Long.toString(notification.getCreateTimestampMicros()));
                        builder.setBody(responseNode.toString().getBytes(Charsets.UTF_8));
                        endpointResponse = builder.create();
                    }
                } else {
                    endpointResponse = CAPACITY_ERROR_RESPONSE;
                }
            } else {
                endpointResponse = UNKNOWN_TOPIC_RESPONSE;
            }
        } catch (DatastoreException de) {
            logger.error("Problem selecting topic", de);
            endpointResponse = INTERNAL_ERROR_RESPONSE;
        }
    } else {
        endpointResponse = NO_TOPIC_RESPONSE;
    }

    logNotification(request, topicURL, endpointResponse.statusCode, broadcastContent);
    Bridge.sendServletResponse(endpointResponse, response);
}

From source file:com.mockey.storage.file.FileUploadOctetStreamReaderServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * /*  w ww.j  a  v a 2  s  .  com*/
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(FileUploadOctetStreamReaderServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    try {
        String filename = URLDecoder.decode(request.getHeader("X-File-Name"), "UTF-8");
        is = request.getInputStream();
        FileSystemManager fsm = new FileSystemManager();
        File fileToWriteTo = fsm.getImageFile(filename);
        fos = new FileOutputStream(fileToWriteTo);

        IOUtils.copy(is, fos);
        response.setStatus(HttpServletResponse.SC_OK);
        writer.print("{success: true}");
    } catch (FileNotFoundException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        writer.print("{success: false}");
        log(FileUploadOctetStreamReaderServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (IOException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        writer.print("{success: false}");
        log(FileUploadOctetStreamReaderServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }

        } catch (IOException ignored) {
        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ignored) {
        }
    }

    writer.flush();
    writer.close();
}