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:eionet.webq.web.controller.PublicPageController.java

/**
 * Gets content from request./*from  w  w  w.j a va 2s.co  m*/
 *
 * @param request request to get content from
 * @return content as byte array
 */
private byte[] getContentFromRequest(HttpServletRequest request) {
    InputStream input = null;
    try {
        input = request.getInputStream();
        return IOUtils.toByteArray(input);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:com.bennavetta.appsite.webapi.ContentController.java

@RequestMapping(value = "/upload/**", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)/*from   w  w w.j  a  v a2 s  .com*/
public void uploadFile(HttpServletRequest request) throws IOException {
    MediaType type = MediaType.parse(request.getContentType());
    String path = extractPathFromPattern(request);
    log.trace("Uploading resource {} with type {}", path, type);

    Resource old = Resource.get(path);
    if (old != null) {
        log.trace("Deleting prior resource: {}", old);
        old.delete();
    }

    try (InputStream in = request.getInputStream()) {
        ReadableByteChannel channel = Channels.newChannel(in);
        resources.create(path, type, channel);
    }
}

From source file:com.github.rabid_fish.proxy.servlet.ProxySoapServlet.java

boolean sendMockResponse(HttpServletRequest request, HttpServletResponse response) {

    String method = request.getMethod();
    String url = request.getRequestURI();

    // Don't break parent functionality
    if ("CONNECT".equalsIgnoreCase(method)) {
        return false;
    }//from w  w  w .  ja  va 2  s.  c  o m

    if (url.startsWith("/favicon.ico")) {
        return false;
    }

    try {
        String mockBody;

        if (method.equals("POST")) {

            ServletInputStream stream = request.getInputStream();
            String requestBody = IOUtils.toString(stream);

            // Need to save off the body so that the input stream can be reset later
            // by the parent class.
            request.setAttribute(ReverseProxyServlet.PROXY_REQUEST_BODY, requestBody);

            mockBody = mockMapRegexHelper.getMockBodyForBody(requestBody);
            if (mockBody != null) {
                writeMockResponse(response, mockBody);
                return true;
            }
        }

    } catch (Exception e) {
        return false;
    }

    return false;
}

From source file:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilterTest.java

private HttpServletRequest mockPostRequest() throws IOException {
    HttpServletRequest postRequest = mockRequest("POST");
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("oldValue".getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {
        @Override//from   ww  w. j  a va2s.  com
        public int read() throws IOException {
            return inputStream.read();
        }
    };
    when(postRequest.getInputStream()).thenReturn(servletInputStream);
    return postRequest;
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

@Override
protected void proxy(String targetUrl, final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final HttpMethod proxyRequest = createProxyRequest(targetUrl, request);

    if (proxyRequest instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) proxyRequest;
        RequestEntity requestEntity = new InputStreamRequestEntity(request.getInputStream(),
                request.getContentLength(), request.getContentType());
        entityEnclosingMethod.setRequestEntity(requestEntity);
    }// ww  w. j a  v  a 2 s  . c om
    int code = httpClient.executeMethod(proxyRequest);
    response.setStatus(code);
    copyProxyReponse(proxyRequest, response);

}

From source file:de.ingrid.interfaces.csw.domain.encoding.impl.XMLEncoding.java

/**
 * Extract the request body from the request. Subclasses will override this.
 *
 * @param request/*  ww  w  .  ja  v a 2 s .co m*/
 * @return Element
 */
protected Node extractRequestBody(HttpServletRequest request) {
    DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
    df.setNamespaceAware(true);
    try {
        Document requestDocument = df.newDocumentBuilder().parse(request.getInputStream());
        return requestDocument.getDocumentElement();
    } catch (Exception e) {
        throw new RuntimeException("Error parsing request: ", e);
    }
}

From source file:nl.surfnet.coin.mock.MockHandler.java

private void respond(HttpServletResponse response, HttpServletRequest request) throws IOException {
    ServletOutputStream outputStream = response.getOutputStream();
    String requestURI = request.getRequestURI();
    InputStream inputStream = getResponseInputStream(requestURI);
    logger.debug("Received Http request ('" + requestURI + "')");
    if (request.getMethod().equals(HttpMethods.POST)) {
        logger.debug("Received POST request ('" + IOUtils.toString(request.getInputStream()) + "')");
    }/*  w w  w  . j  a v a2s.  c o  m*/
    if (status != 0) {
        response.setStatus(status);
        //reset
        status = 0;
    }
    IOUtils.copy(inputStream, outputStream);
    outputStream.flush();
}

From source file:com.ritboss.controller.AddProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w  .  j a  va2 s. co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        response.setContentType("text/html;charset=UTF-8");
        String categoryUrl = request.getRequestURI().toString();
        String prodCategory = categoryUrl.substring(categoryUrl.lastIndexOf("/") + 1);
        System.out.println("Product category is" + prodCategory);
        InputStreamReader in = new InputStreamReader(request.getInputStream());
        BufferedReader bf = new BufferedReader(in);
        String line = bf.readLine();

        JSONArray jsonArray = new JSONArray(line);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            Iterator keys = json.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String value = json.getString(key);
                System.out.println("key is: " + key + "Value is " + value);
            }
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AddProductServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet AddProductServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (JSONException ex) {
        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.gamewin.weixin.web.api.ApiListController.java

private void acceptMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // ??//  w ww.  j  a v  a2s .c  o  m
    ServletInputStream in = request.getInputStream();
    // POST??XStream
    XStream xs = SerializeXmlUtil.createXstream();
    xs.processAnnotations(InputMessage.class);
    xs.processAnnotations(OutputMessage.class);
    // xml?
    xs.alias("xml", InputMessage.class);
    // ??
    StringBuilder xmlMsg = new StringBuilder();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        xmlMsg.append(new String(b, 0, n, "UTF-8"));
    }
    // xml?InputMessage
    InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());

    String servername = inputMsg.getToUserName();// ?
    String custermname = inputMsg.getFromUserName();// 
    long createTime = inputMsg.getCreateTime();// 
    Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;//
    // 

    // ??
    String msgType = inputMsg.getMsgType();

    // ?
    System.out.println("??" + inputMsg.getToUserName());
    System.out.println("????" + inputMsg.getFromUserName());
    System.out.println("?" + inputMsg.getCreateTime() + new Date(createTime * 1000l));
    System.out.println("?Event" + inputMsg.getEvent());
    System.out.println("?EventKey" + inputMsg.getEventKey());
    System.out.println("" + inputMsg.getContent());
    StringBuffer str = new StringBuffer();
    // ????
    if ("event".equals(msgType)) {

        if ("subscribe".equals(inputMsg.getEvent())) {

            if (!StringUtils.isEmpty(inputMsg.getEventKey())) {
                Long qrCodeId = null;
                try {
                    qrCodeId = Long
                            .parseLong(inputMsg.getEventKey().replaceAll("qrscene_", "").trim().toString());
                } catch (Exception e) {
                    System.out.println("" + inputMsg.getEventKey() + "------?");
                    e.printStackTrace();
                }

                ManageQRcode manageQRcode = manageQRcodeService.getManageQRcode(qrCodeId);

                Integer count = manageQRcodeService.selectHistoryWeixinBytaskId(manageQRcode.getTask().getId(),
                        inputMsg.getFromUserName());

                HistoryWeixin wxUser = new HistoryWeixin();
                wxUser.setCreateDate(new Date());
                wxUser.setToUserName(inputMsg.getToUserName());
                wxUser.setFromUserName(inputMsg.getFromUserName());
                wxUser.setMsgType(msgType);
                wxUser.setEvent(inputMsg.getEvent());
                wxUser.setEventKey(inputMsg.getEventKey());
                wxUser.setCreateTime(inputMsg.getCreateTime().toString());
                wxUser.setQrcodeId(qrCodeId);
                wxUser.setTaskId(manageQRcode.getTask().getId());

                if (count == 0) {
                    if ("Y".equals(manageQRcode.getQrState())) {
                        manageQRcode.setQrSubscribeCount(manageQRcode.getQrSubscribeCount() + 1);
                        manageQRcode.setQrSubscribeAdminCount(manageQRcode.getQrSubscribeAdminCount() + 1);
                        manageQRcodeService.saveManageQRcode(manageQRcode);
                        wxUser.setStatus("Y");
                    } else {
                        manageQRcode.setQrSubscribeAdminCount(manageQRcode.getQrSubscribeAdminCount() + 1);
                        manageQRcodeService.saveManageQRcode(manageQRcode);
                        wxUser.setStatus("N");
                    }
                }

                manageQRcodeService.saveHistoryWeixin(wxUser);

            }
            String content = "HI???????????? \n ";

            List<Game> gameList = gameService.getEffectiveGamelist();
            if (gameList != null && gameList.size() > 0) {
                for (int i = 0; i < gameList.size(); i++) {
                    Game game = gameList.get(i);
                    content += "[" + game.getXuhao() + "] " + game.getGameName() + "\n";
                }
            } else {
                content += "???";
            }

            str.append("<xml>                                              ");
            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
            str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
            str.append("<MsgType><![CDATA[text]]></MsgType>                ");
            str.append("<Content><![CDATA[" + content + "]]></Content>                     ");
            str.append("</xml>                                             ");
            System.out.println(str.toString());
            response.getWriter().write(str.toString());
        }

    } else if ("text".equals(msgType)) {

        String redurl = URLEncoder.encode(MobileContants.YM + "/weixinUser/bindUserOpenId", "utf-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + MobileContants.appID
                + "&redirect_uri=" + redurl + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

        String xxxx = inputMsg.getContent().toString();
        String content = "";
        if (xxxx.indexOf("") != -1) {

            str.append("<xml>                                              ");
            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
            str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
            str.append("<MsgType><![CDATA[news]]></MsgType>                ");
            str.append("<ArticleCount>1</ArticleCount>                     ");
            str.append("<Articles>                                         ");
            str.append("<item>                                             ");
            str.append("<Title><![CDATA[??]]></Title>                   ");
            str.append(
                    "<Description><![CDATA[??,,]]></Description> ");
            str.append("<PicUrl><![CDATA[]]></PicUrl>                ");
            str.append("<Url><![CDATA[" + url + "]]></Url>                         ");
            str.append("</item>                                            ");
            str.append("</Articles>                                        ");
            str.append("</xml>                                             ");

            System.out.println(str.toString());
            response.getWriter().write(str.toString());
        } else {
            if ("?".equals(xxxx) || "".equals(xxxx) || "".equals(xxxx) || "".equals(xxxx)) {
                List<Game> gameList = gameService.getEffectiveGamelist();
                if (gameList != null && gameList.size() > 0) {
                    for (int i = 0; i < gameList.size(); i++) {
                        Game game = gameList.get(i);
                        content += "[" + game.getXuhao() + "] " + game.getGameName() + "\n";
                    }
                    content += "??????";
                } else {
                    content = "???";
                }
            } else {
                Game game = gameService.findGameByNameOrXuhao(xxxx);
                if (game != null) {
                    Long count = gameService.getMyGameCodeCount(game.getId(), custermname);
                    System.out.println(count);
                    System.out.println(game.getMaximum());
                    if (count < game.getMaximum()) {
                        //?
                        GameCode code = gameService.getMyGameCode(game.getId());
                        gameService.updateMyGameCode(code.getId(), custermname);
                        content = "???" + code.getCode() + " \n  "
                                + game.getGameMessage() + "";

                    } else {
                        content = "????????\n ?'?'?????????";
                    }

                } else {
                    content = " ????\n ?'?'?????????";
                }

            }
            str.append("<xml>                                              ");
            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
            str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
            str.append("<MsgType><![CDATA[text]]></MsgType>                ");
            str.append("<Content><![CDATA[" + content + "]]></Content>                     ");
            str.append("</xml>                                             ");
            System.out.println(str.toString());
            response.getWriter().write(str.toString());
        }

    }

}

From source file:org.openxdata.server.servlet.FormDownloadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream os = response.getOutputStream();
    try {//from w  ww  .j ava  2s  .c  o  m
        String action = request.getParameter(OpenXDataConstants.REQUEST_PARAMETER_ACTION);

        if (action == null)
            formsServer.processConnection(request.getInputStream(), os);
        else {

            User user = authenticationService.authenticate(
                    request.getParameter(OpenXDataConstants.REQUEST_PARAM_USERNAME),
                    request.getParameter(OpenXDataConstants.REQUEST_PARAM_PASSWORD));
            if (user == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                XformSerializer formSerializer = serializationService.getFormSerializer(
                        request.getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER));
                formSerializer.serializeAccessDenied(os);
            } else {
                if (OpenXDataConstants.REQUEST_ACTION_UPLOAD_DATA.equalsIgnoreCase(action)) {
                    uploadData(request, response);
                    String serializerKey = request
                            .getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER);
                    XformSerializer formSerializer = serializationService.getFormSerializer(serializerKey);
                    formSerializer.serializeSuccess(os);
                } else if (OpenXDataConstants.REQUEST_ACTION_DOWNLOAD_FORMS.equalsIgnoreCase(action))
                    downloadForms(request, response);
                else if (OpenXDataConstants.ACTION_DOWNLOAD_STUDIES.equalsIgnoreCase(action))
                    downloadStudies(request, response);
                else if (OpenXDataConstants.REQUEST_ACTION_DOWNLOAD_USERS.equalsIgnoreCase(action))
                    downloadUsers(request, response);
            }
        }
    } catch (Exception ex) {
        try {
            String serializerKey = request.getParameter(OpenXDataConstants.REQUEST_PARAM_FORM_SERIALIZER);
            XformSerializer formSerializer = serializationService.getFormSerializer(serializerKey);
            formSerializer.serializeFailure(os, ex);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }
    }
}