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:org.biokoframework.http.fields.impl.JsonFieldsParser.java

@Override
public Fields safelyParse(HttpServletRequest request) throws RequestNotSupportedException {
    Reader reader;//from w  w  w.j  av  a2  s.c om
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("utf-8");
        }
        reader = request.getReader();
        Writer writer = new StringWriter();
        IOUtils.copy(reader, writer);
        return Fields.fromJson(writer.toString());
    } catch (IOException exception) {
        // TODO log exception
        throw new RequestNotSupportedException(exception);
    }
}

From source file:com.bosch.cr.examples.jwt.auth.ImAuthenticationServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {//  w  ww  . j a  v a 2  s.  c  o m
        final String body = req.getReader().lines().collect(Collectors.joining());

        final JsonObject jsonObject = JsonFactory.newObject(body);

        final String tenantNameOrId = jsonObject.getValue(TENANT_NAME_OR_ID).map(JsonValue::asString)
                .orElse(configurationProperties.getPropertyAsString(ConfigurationProperty.IM_DEFAULT_TENANT));

        final String userName = jsonObject.getValue(USERNAME).map(JsonValue::asString)
                .orElseThrow(() -> new JsonMissingFieldException(USERNAME.getPointer()));

        final String password = jsonObject.getValue(PASSWORD).map(JsonValue::asString)
                .orElseThrow(() -> new JsonMissingFieldException(PASSWORD.getPointer()));

        final AuthenticationDto authenticationDto = authenticationHelper.authenticate(tenantNameOrId, userName,
                password);
        final AuthorizationDto authorizationDto = authenticationHelper.authorize(authenticationDto);
        final String authorizationToken = authorizationDto.getAuthorizationToken();

        final boolean secure = configurationProperties
                .getPropertyAsBoolean(ConfigurationProperty.SECURE_COOKIE);
        final int maxAge = -1; // cookie is deleted when browser is closed
        final Cookie cookie = CookieUtil.getJwtAuthenticationCookie(authorizationToken, secure, maxAge);

        resp.addCookie(cookie);
        resp.setStatus(HttpStatus.SC_NO_CONTENT);
    } catch (final IOException e) {
        resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    } catch (final JsonMissingFieldException e) {
        resp.setStatus(HttpStatus.SC_BAD_REQUEST);
        resp.getOutputStream().print(e.getMessage());
    } catch (final AuthenticationDeniedException e) {
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
        resp.getOutputStream().print(e.getMessage());
    }
}

From source file:com.pokerweb.Area.SendNewPersent.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww w . j a  va2 s  . com*/
 * @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 {
    try {
        StringBuilder jb = new StringBuilder();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        JSONObject jsonObject = new JSONObject(jb.toString());
        TableStatus.GetInstance().SendPersentToServer(jsonObject.getInt("persent"));
    } catch (JSONException ex) {
        Logger.getLogger(SendNewPersent.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:se.vgregion.pubsub.loadtesting.LoadtestingServlet.java

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

    // find the ID in the feed content
    BufferedReader reader = req.getReader();
    String line = reader.readLine();
    while (line != null) {
        int start = line.indexOf("uuid:");
        if (start > -1) {
            int end = line.indexOf("<", start);
            String id = line.substring(start + 5, end);
            UUID uuid = UUID.fromString(id);

            // found id, now try to count down latch
            CountDownLatch latch = publications.get(uuid);
            if (latch != null) {
                latch.countDown();/*  ww w  .j av  a2 s . co m*/

                publications.remove(id);
                return;
            } else {
                throw new RuntimeException("Could not find latch");
            }
        }
        line = reader.readLine();
    }
}

From source file:com.pokerweb.servlets.holdem.SitThisUser.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w w  .j a va 2  s  .c  o  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 {
    try {
        StringBuilder jb = new StringBuilder();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        JSONObject jsonObject = new JSONObject(jb.toString());
        int IdTable = jsonObject.getInt("IdTable");
        int plaseId = jsonObject.getInt("plaseId");
        double summ = jsonObject.getDouble("summ");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        TableStatus.GetInstance().SendSitThisRequest(IdTable, plaseId, summ, auth.getName());
    } catch (JSONException ex) {
        Logger.getLogger(SitThisUser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.locosoft.fold.channel.fold.internal.FoldFinder.java

void receiveFoldPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    JsonObject jsonObject = JsonObject.readFrom(request.getReader());

    String senderName = jsonObject.getString("senderName", null);
    String message = jsonObject.getString("message", null);

    if ((senderName != null) && (message != null)) {
        String senderIpAddr = request.getRemoteAddr();
        IChatterChannel chatterChannel = _foldChannel.getChannelService().getChannel(IChatterChannel.class);
        JsonObject chatterData = new JsonObject();
        chatterData.add("senderIpAddr", senderIpAddr);
        chatterData.add("senderName", senderName);
        chatterData.add("message", message);

        long chatterItemOrdinal = chatterChannel
                .createChatterItem("received FoldFinder post from ${senderIpAddr}", "foldFinder", chatterData);

        HierarchyNode foldChannelNode = new HierarchyNode(_foldChannel.getChannelNodeId());
        long subnetsNodeId = foldChannelNode.getSubId("subnets", true);
        HierarchyNode subnetsNode = new HierarchyNode(subnetsNodeId);
        long ipAddrPrefixNodeId = subnetsNode.getSubId(getIpAddrPrefix(senderIpAddr), true);
        HierarchyNode ipAddrPrefixNode = new HierarchyNode(ipAddrPrefixNodeId);
        long ipAddrSuffixNodeId = ipAddrPrefixNode.getSubId(getIpAddrSuffix(senderIpAddr), true);
        PropertyAccessNode props = new PropertyAccessNode(ipAddrSuffixNodeId);
        props.setValue("lastReceive_senderName", senderName);
        props.setValue("lastReceive_chatterItemOrdinal", chatterItemOrdinal);
    }/*from   w w w .  j  av a2s  .  co  m*/
}

From source file:com.pokerweb.servlets.holdem.ExitUserTable.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w w . j  av  a2  s .  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 {

    try {
        StringBuilder jb = new StringBuilder();
        String line = null;
        BufferedReader reader = request.getReader();
        DBManager DBM = DBManager.GetInstance();
        while ((line = reader.readLine()) != null)
            jb.append(line);
        JSONObject jsonObject = new JSONObject(jb.toString());
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        TableStatus.GetInstance().ExitTable(jsonObject.getInt("IdTable"), auth.getName());
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write("{error:null}");
    } catch (JSONException ex) {
        Logger.getLogger(GetTableInfo.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:eu.freme.common.rest.RestHelper.java

/**
 * Get NIFParameterSet from a HttpServletRequest. Throws an
 * BadRequestException in case the input is not valid NIF.
 * /*from  ww  w .  j a va 2 s . c  om*/
 * @param request
 *            the request
 * @param allowEmptyInput
 *            Specifies if it is allowed to send empty input text.
 * @return the new NifParameterSet
 */
public NIFParameterSet normalizeNif(HttpServletRequest request, boolean allowEmptyInput) {

    try {
        BufferedReader reader = request.getReader();
        StringBuilder bldr = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            bldr.append(line);
            bldr.append("\n");
        }

        String postBody = bldr.toString();
        String acceptHeader = request.getHeader("accept");
        String contentTypeHeader = request.getHeader("content-type");

        Map<String, String> parameters = new HashMap<>();
        for (String key : request.getParameterMap().keySet()) {
            parameters.put(key, request.getParameter(key));
        }
        return normalizeNif(postBody, acceptHeader, contentTypeHeader, parameters, allowEmptyInput);
    } catch (IOException e) {
        logger.error(e);
        throw new InternalServerErrorException();
    }

}

From source file:com.turn.splicer.SplicerServlet.java

private void doPostWork(HttpServletRequest request, HttpServletResponse response) throws IOException {
    BufferedReader reader = request.getReader();
    String line;/*from   ww  w .  j  a v  a  2  s  .  com*/

    StringBuilder builder = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    String jsonPostRequest = builder.toString();

    TsQuery tsQuery = TsQuerySerializer.deserializeFromJson(jsonPostRequest);
    tsQuery.validateAndSetQuery();

    LOG.info("Serving query={}", tsQuery);

    LOG.info("Original TsQuery Start time={}, End time={}", Const.tsFormat(tsQuery.startTime()),
            Const.tsFormat(tsQuery.endTime()));

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");

    try (RegionChecker checker = REGION_UTIL.getRegionChecker()) {

        List<TSSubQuery> subQueries = new ArrayList<>(tsQuery.getQueries());
        SplicerQueryRunner queryRunner = new SplicerQueryRunner();

        if (subQueries.size() == 1) {
            TsdbResult[] results = queryRunner.sliceAndRunQuery(tsQuery, checker);
            if (results == null || results.length == 0) {
                response.getWriter().write("[]");
            } else {
                response.getWriter().write(TsdbResult.toJson(results));
            }
            response.getWriter().flush();
        } else {
            List<TsdbResult[]> resultsFromAllSubQueries = new ArrayList<>();
            for (TSSubQuery subQuery : subQueries) {
                TsQuery tsQueryCopy = TsQuery.validCopyOf(tsQuery);
                tsQueryCopy.addSubQuery(subQuery);
                TsdbResult[] results = queryRunner.sliceAndRunQuery(tsQueryCopy, checker);
                resultsFromAllSubQueries.add(results);
            }
            response.getWriter().write(TsdbResult.toJson(SplicerUtils.flatten(resultsFromAllSubQueries)));
        }
    }
}

From source file:net.proest.librepilot.web.handler.ObjectHandler.java

public void handlePost(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    BufferedReader br = request.getReader();
    String json = "";
    while (br.ready()) {
        json += br.readLine();/* w w  w  .j  a v a  2  s  .  co  m*/
    }
    System.out.println(json);
    json = json.replaceFirst("json=", "");
    System.out.println(json);
    json = URLDecoder.decode(json, "utf-8");
    System.out.println(json);
    System.out.println();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(json);
    out.println(actualObj.asText());
    out.println(mapper.toString());
}