Example usage for javax.servlet.http HttpServletRequest getReader

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

Introduction

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

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:ostepu.cconfig.control.java

/**
 * setzt die Konfiguration der Komponente anhand der eingehenden Daten
 *
 * @param context  der Kontext des Servlet
 * @param request  die eingehende Anfrage
 * @param response das Antwortobjekt/*from w  w  w .  j ava 2s.  c  o  m*/
 */
public static void setControl(ServletContext context, HttpServletRequest request,
        HttpServletResponse response) {
    PrintWriter out;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(control.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
        return;
    }

    Path cconfigPath = Paths.get(context.getRealPath("/data/CConfig.json"));

    try {
        String q = IOUtils.toString(request.getReader());
        JsonElement obj = new JsonParser().parse(q);
        JsonObject newObject = obj.getAsJsonObject();

        if (newObject.has("prefix")) {
            newObject.remove("prefix");
            newObject.add("prefix", (JsonElement) new JsonPrimitive(context.getAttribute("prefix").toString()));
        } else {
            newObject.add("prefix", (JsonElement) new JsonPrimitive(context.getAttribute("prefix").toString()));
        }
        Files.write(cconfigPath, newObject.toString().getBytes());
        cconfig.myConf = null;
        response.setStatus(201);
    } catch (IOException | JsonSyntaxException e) {
        try {
            response.sendError(500);
        } catch (IOException ex) {
            Logger.getLogger(control.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.acciente.commons.htmlform.Parser.java

private static Map parsePOSTParams(HttpServletRequest oRequest) throws ParserException, IOException {
    return Parser.parseForm(oRequest.getReader(), true);
}

From source file:network.thunder.server.etc.Tools.java

/**
 * Gets the message./*from  www  . j a  va 2  s . c o m*/
 *
 * @param httpExchange the http exchange
 * @return the message
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static Message getMessage(HttpServletRequest httpExchange) throws IOException {
    String data = IOUtils.toString(httpExchange.getReader()).split("=")[1];
    data = java.net.URLDecoder.decode(data, "UTF-8");
    //        System.out.println(data);
    //      System.out.println(data);
    Gson gson = new Gson();
    Message message = gson.fromJson(data, Message.class);
    return message;
}

From source file:password.pwm.util.ServletHelper.java

public static String readRequestBody(final HttpServletRequest request, final int maxChars) throws IOException {
    final StringBuilder inputData = new StringBuilder();
    String line;/*from  w  w  w .j a  v  a 2 s  .co m*/
    try {
        final BufferedReader reader = request.getReader();
        while (((line = reader.readLine()) != null) && inputData.length() < maxChars) {
            inputData.append(line);
        }
    } catch (Exception e) {
        LOGGER.error("error reading request body stream: " + e.getMessage());
    }
    return inputData.toString();
}

From source file:org.b3log.latke.servlet.RequestContext.java

/**
 * Gets the request json object with the specified request.
 *
 * @param request  the specified request
 * @param response the specified response, sets its content type with "application/json"
 * @return a json object/*from   w  w w  .  j  a v a 2  s.  c  o  m*/
 */
private static JSONObject parseRequestJSONObject(final HttpServletRequest request,
        final HttpServletResponse response) {
    response.setContentType("application/json");

    try {
        BufferedReader reader;
        try {
            reader = request.getReader();
        } catch (final IllegalStateException illegalStateException) {
            reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        }

        String tmp = IOUtils.toString(reader);
        if (StringUtils.isBlank(tmp)) {
            tmp = "{}";
        }

        return new JSONObject(tmp);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR,
                "Parses request JSON object failed [" + e.getMessage() + "], returns an empty json object");

        return new JSONObject();
    }
}

From source file:org.b3log.latke.util.Requests.java

/**
 * Gets the request json object with the specified request.
 *
 * @param request the specified request/*from   www.  j av a2s . c  o  m*/
 * @param response the specified response, sets its content type with "application/json"
 * @return a json object
 * @throws ServletException servlet exception
 * @throws IOException io exception
 */
public static JSONObject parseRequestJSONObject(final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");

    final StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;

    final String errMsg = "Can not parse request[requestURI=" + request.getRequestURI() + ", method="
            + request.getMethod() + "], returns an empty json object";

    try {
        try {
            reader = request.getReader();
        } catch (final IllegalStateException illegalStateException) {
            reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        }

        String line = reader.readLine();

        while (null != line) {
            sb.append(line);
            line = reader.readLine();
        }
        reader.close();

        String tmp = sb.toString();

        if (Strings.isEmptyOrNull(tmp)) {
            tmp = "{}";
        }

        return new JSONObject(tmp);
    } catch (final Exception ex) {
        LOGGER.log(Level.SEVERE, errMsg, ex);

        return new JSONObject();
    }
}

From source file:com.xqdev.jam.MLJAM.java

private static String getBody(HttpServletRequest req) {
    try {/*from www  .  j a v  a  2s  . c o m*/
        // Try reading the post body using characters.
        // This might throw an exception if something on the
        // server side already called getInputStream().
        // In that case we'll pull as bytes.
        Reader reader = null;
        try {
            reader = new BufferedReader(req.getReader());
        } catch (IOException e) {
            reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
        }

        StringBuffer sbuf = new StringBuffer();
        char[] cbuf = new char[4096];
        int count = 0;
        while ((count = reader.read(cbuf)) != -1) {
            sbuf.append(cbuf, 0, count);
        }
        return sbuf.toString();
    } catch (IOException e2) {
        throw new ServerProblemException("IOException in reading POST body: " + e2.getMessage());
    }
}

From source file:org.opendaylight.sloth.filter.SlothSecurityFilter.java

private static Request getRequest(HttpServletRequest httpServletRequest, String externalJson) {
    LOG.info(String.format("create request, method: %s, request-url: %s, query-string: %s",
            httpServletRequest.getMethod(), httpServletRequest.getRequestURI(),
            httpServletRequest.getQueryString()));
    RequestBuilder requestBuilder = new RequestBuilder();
    requestBuilder.setMethod(HttpType.valueOf(httpServletRequest.getMethod()))
            .setRequestUrl(httpServletRequest.getRequestURI())
            .setQueryString(httpServletRequest.getQueryString());
    if (externalJson == null || externalJson.isEmpty()) {
        try {//from  ww w.  j a va  2 s  .  co m
            if (httpServletRequest.getContentType() != null
                    && Objects.equals(httpServletRequest.getContentType(), JSON_CONTENT_TYPE)) {
                requestBuilder.setJsonBody(IOUtils.toString(httpServletRequest.getReader()));
            }
        } catch (IOException e) {
            LOG.error("failed to get json body from http servlet request: " + e.getMessage());
        }
    } else {
        requestBuilder.setJsonBody(externalJson);
    }
    return requestBuilder.build();
}

From source file:UTF8.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//from   w w  w.  ja va2  s .c om
        BufferedReader reader = req.getReader();

        res.setContentType("text/html; charset=UTF-8");
        PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

        // Read and write 4K chars at a time
        // (Far more efficient than reading and writing a line at a time)
        char[] buf = new char[4 * 1024]; // 4Kchar buffer
        int len;
        while ((len = reader.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
    } catch (Exception e) {
        getServletContext().log(e, "Problem filtering page to UTF-8");
    }
}

From source file:de.hybris.eventtracking.ws.controllers.rest.EventsController.java

protected String extractBody(final HttpServletRequest request) throws IOException {
    return IOUtils.toString(request.getReader());
}