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.mockey.model.RequestFromClient.java

private void parseRequestBody(HttpServletRequest rawRequest) {

    try {//from  ww  w  .  j  a  va 2  s . c o m
        InputStream is = rawRequest.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        requestBody = sb.toString();

    } catch (IOException e) {
        log.error("Unable to parse body from incoming request", e);
    }

}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Before
@Override//from w ww .  java 2s  . c  o m
public void setUp() throws Exception {
    super.setUp();

    Tomcat tomcat = getTomcatInstance();

    // Must have a real docBase - just use temp
    org.apache.catalina.Context context = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    Tomcat.addServlet(context, "hello-servlet", new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            System.out.println(req.getRequestURL());
            IoUtils2.flush(req.getInputStream(), System.out);
            Enumeration<String> headers = req.getHeaderNames();
            while (headers.hasMoreElements()) {
                String header = headers.nextElement();
                System.out.println("   " + header + ": " + req.getHeader(header));
            }
            resp.addHeader("x-response", "hello");
            resp.getWriter().println("Hello world!");
        }
    });
    context.addServletMapping("/*", "hello-servlet");

    privateAppValve = new PrivateAppValve();
    privateAppValve.setSecretKey(secretKey);

    context.getPipeline().addValve(privateAppValve);

    tomcat.start();

    httpClient = new DefaultHttpClient();
    httpHost = new HttpHost("localhost", getPort());
}

From source file:cat.calidos.morfeu.webapp.GenericHttpServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String path = req.getPathInfo();
    log.trace("GenericMorfeuServlet::doPost {}", path);

    Map<String, String> params = normaliseParams(req.getParameterMap());
    params.put(METHOD, req.getMethod());
    String content = IOUtils.toString(req.getInputStream(), Config.DEFAULT_CHARSET);
    params.put(POST_VALUE, content);/* w  w w . j a  v a 2s. com*/
    params = processParams(params);

    ControlComponent controlComponent = putControl(path, params);
    handleResponse(resp, controlComponent);

}

From source file:com.google.gwt.benchmark.dashboard.server.servlets.AddBenchmarkResultServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String auth = req.getHeader("auth");
    if (!authController.validateAuth(auth)) {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;//  www. j  a va2  s  .  c  o  m
    }

    BenchmarkRunJson benchmarkRunJSON = null;
    String json = null;
    try {
        json = IOUtils.toString(req.getInputStream(), "UTF-8");
        AutoBean<BenchmarkRunJson> bean = AutoBeanCodex.decode(JsonFactory.get(), BenchmarkRunJson.class, json);
        benchmarkRunJSON = bean.as();
    } catch (Exception e) {
        logger.log(Level.WARNING, "Can not deserialize JSON", e);
        if (json != null) {
            logger.warning(json);
        }
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Can't parse JSON, see App Engine log for details.");
        return;
    }

    try {

        benchmarkController.addBenchmarkResult(benchmarkRunJSON);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Can not add benchmark results", e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

private void performRunScript(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String script = toString(request.getInputStream(), charset);
    try {/*from ww w  .  j  a v  a 2 s . c om*/
        ScriptEngine engine = prepareEngine(request, response);
        engine.eval(script);
        response.setStatus(200);
        // Post and run won't return evaluate result to client
    } catch (ScriptException e) {
        log.log(Level.SEVERE, "Error while running script:" + script, e);
        response.setStatus(500);
        e.getCause().printStackTrace(response.getWriter());
    }
}

From source file:org.apache.hadoop.gateway.dispatch.HttpClientDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;/*from   w  ww .  ja  va  2s . c  om*/
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }

    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {

        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (!delegationTokenPresent && getReplayBufferSize() > 0) {
            entity = new CappedBufferHttpEntity(entity, getReplayBufferSize() * 1024);
        }
    }

    return entity;
}

From source file:de.devbliss.apitester.dummyserver.DummyRequestHandler.java

private void handlePostPatchPut(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {//from  w  ww .  j  a va2  s  .  c  o  m
        int desiredResponseCode = parseDesiredResponseCode(target);
        response.setStatus(desiredResponseCode);
        response.setContentType(CONTENT_TYPE);

        if (desiredResponseCode == HttpServletResponse.SC_OK) {
            String requestBody = IOUtils.toString(request.getInputStream());
            response.getWriter().write(requestBody);
        }
    } catch (Exception e) {
        handleException(e, response);
    }
}

From source file:com.gson.web.WeChatPayNotifyServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // post ?xml//from   w  w  w  .ja  va  2s  .  c o m
    WeChatBuyPost postData = null;
    String openid = null;
    String appsignature = null;
    try {
        ServletInputStream in = req.getInputStream();
        // ?post?xml
        XStream xs = new XStream(new DomDriver());
        xs.alias("xml", WeChatBuyPost.class);
        String xmlMsg = Tools.inputStream2String(in);
        postData = (WeChatBuyPost) xs.fromXML(xmlMsg);

        System.out.println(postData.toString());
        // OpenId=oOGf-jjDL7Kv-xT6MBD1qoyKtzeU, AppId=wx136bc734aff403df, IsSubscribe=1, TimeStamp=1392628878, NonceStr=54ah1fs5UsTZrf8s, AppSignature=02b5d8f2ccd8ca42cf13c6e44b48513c13294093, SignMethod=sha1
        // 
        long timestamp = postData.getTimeStamp();
        String noncestr = postData.getNonceStr();
        openid = postData.getOpenId();
        int issubscribe = postData.getIsSubscribe();
        appsignature = postData.getAppSignature();
        boolean temp = Pay.verifySign(timestamp, noncestr, openid, issubscribe, appsignature);
        if (!temp) {
            System.out.println("error?");
            writeString(resp, STATUC_FAIL);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // post??
    @SuppressWarnings("unchecked")
    Map<String, String[]> parasMap = req.getParameterMap();
    // ?
    Map<String, String> paraMap = new HashMap<String, String>();
    for (Entry<String, String[]> entry : parasMap.entrySet()) {
        String key = entry.getKey();
        String[] value = entry.getValue();
        System.out.println(key + ":\t" + value);
        if (null == value) {
            continue;
        } else {
            paraMap.put(key, value[0]);
        }
    }
    /*
     paraMap:   {"transport_fee":["0"],"trade_mode":["1"],"trade_state":["0"],"sign_type":["MD5"],"input_charset":["UTF-8"],"fee_type":["1"],"out_trade_no":["7805803"],"transaction_id":["1217484201201402188208911673"],"discount":["0"],"bank_billno":["201402180770175"],"sign":["F06A82B69D7819785478E34A84BE5CA0"],"attach":["yongle"],"total_fee":["1"],"time_end":["20140218095638"],"partner":["1217484201"],"notify_id":["Kl8hcMyrMFtQLMvOl_hfnEOahccJRPEf-tFuN7ctFfxVxRPLeD0kqMf_AU7ADdMF1zsRaW4FZQ9K_kvMQFc62ScV_NvEhL-D"],"bank_type":["0"],"product_fee":["1"]}
     */

    /*
    // ?
    sign_type           ?? ? MD5? RSA
    service_version     ? 1.0
    input_charset       ?,? GBK? UTF-8
    sign_key_index      ???  1
    pay_info            ? ?
    bank_billno         ??
    attach              ?
    transport_fee       ??? 0??transport_fee + product_fee = total_fee
    product_fee         ? ??   ? ? transport_fee + product_fee=total_fee
    discount             ?? ,  total_fee + discount = total_fee ??
    buyer_alias         ?
            
    
    sign                ??
    trade_mode          1-?
    trade_state         0? ??
    partner             ???partnerid, ?10 ? (120XXXXXXX)
    bank_type            WX
    total_fee           ?  ???discount   total_fee+ discount =  total_fee
    fee_type            ??,????, 1-?
    notify_id            id ?? id??
    transaction_id      ? 28??10???8??20090415?10???
    out_trade_no        ?? 
    time_end            ??yyyyMMddhhmmss  GMT+8 beijing
     */
    String trade_state = req.getParameter("trade_state");
    String totalFee = req.getParameter("total_fee");
    String orderId = req.getParameter("out_trade_no");
    String transId = req.getParameter("transaction_id");
    String timeEnd = req.getParameter("time_end");

    System.out.println("trade_state:\t" + trade_state + "totalFee:\t" + totalFee + "orderId:\t" + orderId);

    if (StringUtils.isEmpty(orderId)) {
        writeString(resp, STATUC_FAIL);
        return;
    }

    //  bg
    // ***************
    //  ed

    // ????
    try {
        String accessToken = WechatUtil.getAccessToken();//WeChat.getAccessToken();
        WeChat.message.sendText(accessToken, orderId, "??" + orderId + "???");
        //????????...
        Pay.delivernotify(accessToken, openid, transId, transId, "");
    } catch (Exception e) {
        e.printStackTrace();
    }
    writeString(resp, STATUC_SUCCESS);
}

From source file:net.sf.j2ep.requesthandlers.EntityEnclosingRequestHandler.java

/**
 * Will set the input stream and the Content-Type header to match this request.
 * Will also set the other headers send in the request.
 * /*from   w w  w  . j av  a 2s.  com*/
 * @throws IOException An exception is throws when there is a problem getting the input stream
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {

    EntityEnclosingMethod method = null;

    if (request.getMethod().equalsIgnoreCase("POST")) {
        method = new PostMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("PUT")) {
        method = new PutMethod(url);
    }

    setHeaders(method, request);

    InputStreamRequestEntity stream;
    stream = new InputStreamRequestEntity(request.getInputStream());
    method.setRequestEntity(stream);
    method.setRequestHeader("Content-type", request.getContentType());

    return method;

}

From source file:com.carolinarollergirls.scoreboard.jetty.XmlScoreBoardServlet.java

protected void set(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
    XmlListener listener = getXmlListenerForRequest(request);
    if (null == listener) {
        registrationKeyNotFound(request, response);
        return;//  ww  w. jav  a 2s  .com
    }

    Document requestDocument = editor.toDocument(request.getInputStream());
    if (null == requestDocument) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (debugSet)
        ScoreBoardManager.printMessage(
                "SET from " + listener.getKey() + "\n" + rawXmlOutputter.outputString(requestDocument));

    scoreBoardModel.getXmlScoreBoard().mergeDocument(requestDocument);

    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_OK);
}