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.infoscoop.web.MenuLatestCheckServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    StringBuffer buf = new StringBuffer();
    BufferedReader reader = req.getReader();
    String s = null;//from  ww w . j av a 2s .c  om
    while ((s = reader.readLine()) != null) {
        buf.append(s);
    }

    String uid = (String) req.getSession().getAttribute("Uid");
    if (uid == null)
        return;//The alert is unnecessary in the case of non-login.

    String url = (String) req.getParameter("url");
    try {
        res.setHeader("Content-Type", "text/xml; charset=UTF-8");
        Writer w = res.getWriter();
        MenuCacheDAO dao = MenuCacheDAO.newInstance();
        MenuCache cache = dao.get(uid, url);
        if (cache != null && cache.getMenuIds() != null) {
            Set oldIds = new HashSet(Arrays.asList(new String(cache.getMenuIds()).split(",")));
            Set newIds = new HashSet(Arrays.asList(buf.toString().split(",")));
            newIds.removeAll(oldIds);
            JSONArray array = new JSONArray();
            for (Iterator it = newIds.iterator(); it.hasNext();) {
                String id = (String) it.next();
                array.put(id);
            }
            w.write(array.toString());
        } else {
            cache = new MenuCache(new MENUCACHEPK(Crypt.getHash(url), uid));
            w.write("[]");
        }
        cache.setMenuIds(buf.toString().getBytes());
        dao.insertOrUpdate(cache);

        w.flush();
        w.close();
    } catch (Exception e) {
        log.error("unexcepted error", e);
        res.sendError(500, e.getMessage());
    }
}

From source file:com.github.achatain.catalog.servlet.CollectionServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String userId = getUserId(req);
    final CollectionDto collectionDto = gson.fromJson(req.getReader(), CollectionDto.class);
    Preconditions.checkArgument(collectionDto != null, "Request body is missing");
    LOG.info(format("User [%s] to create the collection [%s]", userId, gson.toJson(collectionDto)));
    collectionService.createCollection(userId, collectionDto);
}

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/reader", produces = MediaType.TEXT_PLAIN_VALUE)
public void reader(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    try (PrintWriter writer = response.getWriter()) {
        CharStreams.copy(request.getReader(), writer);
    }/*from   www  .  j  av  a2  s .c om*/
}

From source file:org.sipfoundry.sipxconfig.cmcprov.LoginServlet.java

protected Map<String, String> getParameterMapFromBody(HttpServletRequest req) throws java.io.IOException {
    Hashtable<String, String> parameters = new Hashtable<String, String>();
    BufferedReader br = req.getReader();
    String line = br.readLine();/*w ww.  jav  a2 s .co  m*/
    if (line == null) {
        return parameters;
    }
    String[] pairs = line.split("\\&");
    for (int i = 0; i < pairs.length; i++) {
        String[] fields = pairs[i].split("=");
        if (fields.length == 2) {
            String name = URLDecoder.decode(fields[0], PARAMETER_ENCODING);
            String value = URLDecoder.decode(fields[1], PARAMETER_ENCODING);
            parameters.put(name.toLowerCase(), value);
        }
    }
    return parameters;
}

From source file:com.seer.datacruncher.spring.SchemasUpdateController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String json = request.getReader().readLine();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    SchemaEntity schemaEntity = mapper.readValue(json, SchemaEntity.class);

    if (schemaEntity.getIdDatabase() > 0) {
        schemaEntity.setPublishToDb(true);
    }/*from www. j a  v  a 2s.  co m*/
    if (schemaEntity.getIdValidationDatabase() > 0) {
        schemaEntity.setInputToDb(true);
    }

    SchemaTriggerStatusEntity newSchemaTriggerStatusEntity = schemaEntity.getSchemaEvents();
    Create createTrigger = new Create();
    createTrigger.setSuccess(true);
    createTrigger.setMessage("");
    Update update;

    ReadList readTriggersList = schemaTriggerStatusDao.findByIdSchema(schemaEntity.getIdSchema());
    if (CollectionUtils.isNotEmpty(readTriggersList.getResults())) {
        if (schemaEntity.getIsEventTrigger()) {
            SchemaTriggerStatusEntity schemaTriggerStatusEntity = (SchemaTriggerStatusEntity) readTriggersList
                    .getResults().get(0);
            if (schemaTriggerStatusEntity.getIdEventTrigger() != newSchemaTriggerStatusEntity
                    .getIdEventTrigger()
                    || schemaTriggerStatusEntity.getIdStatus() != newSchemaTriggerStatusEntity.getIdStatus()) {
                schemaTriggerStatusEntity.setIdEventTrigger(newSchemaTriggerStatusEntity.getIdEventTrigger());
                schemaTriggerStatusEntity.setIdStatus(newSchemaTriggerStatusEntity.getIdStatus());
                update = schemaTriggerStatusDao.update(schemaTriggerStatusEntity);
                if (update.isSuccess()) {
                    schemaEntity.setSchemaEvents(schemaTriggerStatusEntity);
                } else {
                    createTrigger.setSuccess(false);
                    createTrigger.setMessage("Event update error:" + update.getMessage());
                }
            }

        } else {
            Destroy destroy = schemaTriggerStatusDao.destroyEventsBySchema(schemaEntity.getIdSchema());
            if (!destroy.isSuccess()) {
                createTrigger.setSuccess(false);
                createTrigger.setMessage("Event delete error:" + destroy.getMessage());
            }
        }
    } else {
        if (schemaEntity.getIsEventTrigger()) {
            newSchemaTriggerStatusEntity.setIdSchema(schemaEntity.getIdSchema());
            createTrigger = schemaTriggerStatusDao.create(newSchemaTriggerStatusEntity);
            if (createTrigger.getSuccess())
                schemaEntity.setSchemaEvents(newSchemaTriggerStatusEntity);
        }
    }

    if (createTrigger.getSuccess()) {
        update = schemasDao.update(schemaEntity);
    } else {
        update = new Update();
        update.setSuccess(createTrigger.getSuccess());
        update.setMessage("Event " + createTrigger.getMessage());
    }

    response.setContentType("application/json");
    ServletOutputStream out = response.getOutputStream();
    out.write(mapper.writeValueAsBytes(update));
    out.flush();
    out.close();
    return null;
}

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

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// www .j a v a 2s.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 {
    StringBuilder jb = new StringBuilder();
    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
        jb.append(line);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    TableStatus.GetInstance().SetButtonSettingsResponce(jb.toString(), auth.getName());
    response.setContentType("application/json; charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("{error:null}");
}

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

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w w  w  .ja  v 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, IOException {
    StringBuilder jb = new StringBuilder();
    String line = null;
    BufferedReader reader = request.getReader();
    DBManager DBM = DBManager.GetInstance();
    while ((line = reader.readLine()) != null)
        jb.append(line);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String jsMessage = TableStatus.GetInstance().GetDataTable(jb.toString(), auth.getName());
    response.setContentType("application/json; charset=utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write(jsMessage);

}

From source file:de.hybris.platform.chinesepspwechatpay.controllers.misc.ChineseWeChatPayResponseController.java

public String getPostRequestBody(final HttpServletRequest req) {
    if (RequestMethod.POST.name().equalsIgnoreCase(req.getMethod())) {
        final StringBuilder sb = new StringBuilder();
        try (BufferedReader br = req.getReader()) {
            final char[] charBuffer = new char[128];
            int bytesRead;
            while ((bytesRead = br.read(charBuffer)) != -1) {
                sb.append(charBuffer, 0, bytesRead);
            }/* w w  w  .  j a  va 2 s  . c om*/
        } catch (final IOException e) {
            LOG.warn("failed to read request body");
        }
        return sb.toString();
    }
    return "";
}

From source file:org.apache.lucene.gdata.servlet.handler.AbstractAccountHandler.java

protected GDataAccount getAccountFromRequest(final HttpServletRequest request) throws AccountHandlerException {
    try {//from w  w  w .ja va2  s  .  co m
        GDataAccount account = AccountBuilder.buildAccount(request.getReader());
        if (account == null) {
            setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "");
            throw new AccountHandlerException("unexpected value -- parsed account is null");
        }
        return account;
    } catch (IOException e) {
        setError(HttpServletResponse.SC_BAD_REQUEST, "can not read input");
        throw new AccountHandlerException("Can't read from request reader", e);
    } catch (SAXException e) {
        setError(HttpServletResponse.SC_BAD_REQUEST, "can not parse gdata account");
        throw new AccountHandlerException("Can not parse incoming gdata account", e);
    }
}

From source file:nz.net.orcon.kanban.controllers.ResourceController.java

@PreAuthorize("hasPermission(#boardId, 'BOARD', 'ADMIN')")
@RequestMapping(value = "/{resourceId}", method = RequestMethod.POST)
public @ResponseBody void createResource(@PathVariable String boardId, @PathVariable String resourceId,
        HttpServletRequest request) throws Exception {

    logger.info("Saving Resource " + boardId + "/" + resourceId);
    BufferedReader reader = request.getReader();
    reader.reset();/*w w  w  .  j a  v  a 2  s.  c  o m*/
    StringBuilder valueBuilder = new StringBuilder();

    while (true) {
        String newValue = reader.readLine();
        if (newValue != null) {
            valueBuilder.append(newValue);
            valueBuilder.append("\n");
        } else {
            break;
        }
    }

    String value = valueBuilder.toString();

    logger.info("Resource Text: " + value);

    ObjectContentManager ocm = ocmFactory.getOcm();

    try {

        listTools.ensurePresence(String.format(URI.BOARD_URI, boardId), "resources", ocm.getSession());

        Node node = ocm.getSession().getNode(String.format(URI.RESOURCE_URI, boardId, ""));
        Node addNode = node.addNode(resourceId);

        addNode.setProperty("resource", value);
        addNode.setProperty("name", resourceId);
        ocm.getSession().save();
    } finally {
        ocm.logout();
    }

    logger.info("Resource Saved " + resourceId);
}