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.mapfish.print.servlet.MapPrinterServlet.java

protected String getSpecFromPostBody(HttpServletRequest httpServletRequest) throws IOException {
    if (httpServletRequest.getParameter("spec") != null) {
        return httpServletRequest.getParameter("spec");
    }/*from www  . ja  va  2 s . co  m*/
    BufferedReader data = httpServletRequest.getReader();
    try {
        StringBuilder spec = new StringBuilder();
        String cur;
        while ((cur = data.readLine()) != null) {
            spec.append(cur).append("\n");
        }
        return spec.toString();
    } finally {
        if (data != null) {
            data.close();
        }
    }
}

From source file:com.recomdata.datasetexplorer.proxy.XmlHttpProxyServlet.java

public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;/*from  w  w  w . jav a 2s . c  o m*/
    PrintWriter writer = null;
    String serviceKey = null;

    try {
        BufferedReader in = req.getReader();
        String line = null;
        while ((line = in.readLine()) != null) {
            if (bodyContent == null)
                bodyContent = new StringBuffer();
            bodyContent.append(line);
        }
    } catch (Exception e) {
    }
    try {
        if (requireSession) {
            // check to see if there was a session created for this request
            // if not assume it was from another domain and blow up
            // Wrap this to prevent Portlet exeptions
            HttpSession session = req.getSession(false);
            if (session == null) {
                res.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }
        serviceKey = req.getParameter("id");
        // only to preven regressions - Remove before 1.0
        if (serviceKey == null)
            serviceKey = req.getParameter("key");
        // check if the services have been loaded or if they need to be reloaded
        if (services == null || configUpdated()) {
            getServices(res);
        }
        String urlString = null;
        String xslURLString = null;
        String userName = null;
        String password = null;
        String format = "json";
        String callback = req.getParameter("callback");
        String urlParams = req.getParameter("urlparams");
        String countString = req.getParameter("count");
        // encode the url to prevent spaces from being passed along
        if (urlParams != null) {
            urlParams = urlParams.replace(' ', '+');
        }

        try {
            if (services.has(serviceKey)) {
                JSONObject service = services.getJSONObject(serviceKey);
                // default to the service default if no url parameters are specified
                if (urlParams == null && service.has("defaultURLParams")) {
                    urlParams = service.getString("defaultURLParams");
                }
                String serviceURL = service.getString("url");
                // build the URL
                if (urlParams != null && serviceURL.indexOf("?") == -1) {
                    serviceURL += "?";
                } else if (urlParams != null) {
                    serviceURL += "&";
                }
                String apikey = "";
                if (service.has("username"))
                    userName = service.getString("username");
                if (service.has("password"))
                    password = service.getString("password");
                if (service.has("apikey"))
                    apikey = service.getString("apikey");
                urlString = serviceURL + apikey;
                if (urlParams != null)
                    urlString += "&" + urlParams;
                if (service.has("xslStyleSheet")) {
                    xslURLString = service.getString("xslStyleSheet");
                }
            }
            //code for passing the url directly through instead of using configuration file
            else if (req.getParameter("url") != null) {
                String serviceURL = req.getParameter("url");
                // build the URL
                if (urlParams != null && serviceURL.indexOf("?") == -1) {
                    serviceURL += "?";
                } else if (urlParams != null) {
                    serviceURL += "&";
                }
                urlString = serviceURL;
                if (urlParams != null)
                    urlString += urlParams;
            } else {
                writer = res.getWriter();
                if (serviceKey == null)
                    writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
                else
                    writer.write("XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
                writer.flush();
                return;
            }
        } catch (Exception ex) {
            getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
        }

        Map paramsMap = new HashMap();
        paramsMap.put("format", format);
        // do not allow for xdomain unless the context level setting is enabled.
        if (callback != null && allowXDomain) {
            paramsMap.put("callback", callback);
        }
        if (countString != null) {
            paramsMap.put("count", countString);
        }

        InputStream xslInputStream = null;

        if (urlString == null) {
            writer = res.getWriter();
            writer.write(
                    "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
            writer.flush();
            return;
        }
        // default to JSON
        res.setContentType(responseContentType);
        out = res.getOutputStream();
        // get the stream for the xsl stylesheet
        if (xslURLString != null) {
            // check the web root for the resource
            URL xslURL = null;
            xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
            // if not in the web root check the classpath
            if (xslURL == null) {
                xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
            }
            if (xslURL != null) {
                xslInputStream = xslURL.openStream();
            } else {
                String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey
                        + ". Please check the XMLHttpProxy configuration.";
                getLogger().severe(message);
                try {
                    out.write(message.getBytes());
                    out.flush();
                    return;
                } catch (java.io.IOException iox) {
                }
            }
        }
        if (!isPost) {
            xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
        } else {
            if (bodyContent == null)
                getLogger().info(
                        "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content");
            xhp.doPost(urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(),
                    userName, password);
        }
    } catch (Exception iox) {
        iox.printStackTrace();
        getLogger().severe("XmlHttpProxyServlet: caught " + iox);
        try {
            writer = res.getWriter();
            writer.write(iox.toString());
            writer.flush();
        } catch (java.io.IOException ix) {
            ix.printStackTrace();
        }
        return;
    } finally {
        try {
            if (out != null)
                out.close();
            if (writer != null)
                writer.close();
        } catch (java.io.IOException iox) {
        }
    }
}

From source file:com.flipkart.poseidon.core.PoseidonServlet.java

protected void doRequest(HttpMethod method, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException {
    PoseidonRequest request = new PoseidonRequest(httpRequest);
    request.setAttribute(METHOD, method);

    if (ServletFileUpload.isMultipartContent(httpRequest)) {
        handleFileUpload(request, httpRequest);
    } else {// w  w w  .  ja va 2s  . c  o m
        StringBuffer requestBuffer = new StringBuffer();
        String line;
        try {
            BufferedReader reader = httpRequest.getReader();
            while ((line = reader.readLine()) != null)
                requestBuffer.append(line);
        } catch (Exception e) {
            logger.debug("301: Couldn't read body" + e.getMessage());
        }
        request.setAttribute(BODY, requestBuffer.toString());
    }

    PoseidonResponse response = new PoseidonResponse();
    response.setContentType(application.getDefaultMediaType());

    try {
        buildResponse(request, response, httpResponse);
    } catch (ProcessingException exception) {
        logger.warn("301: " + exception.getMessage());
        redirect(response, httpResponse);
    } catch (BadRequestException exception) {
        badRequest(response, httpResponse, exception);
    } catch (ElementNotFoundException exception) {
        elementNotFound(response, httpResponse, exception);
    } catch (Throwable exception) {
        internalError(response, httpResponse, exception);
    }
}

From source file:com.googlesource.gerrit.plugins.github.notification.WebhookServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (Strings.emptyToNull(config.webhookUser) == null) {
        logger.error("No webhookUser defined: cannot process GitHub events");
        resp.sendError(SC_INTERNAL_SERVER_ERROR);
        return;//from   w w  w . j av a 2 s. co m
    }

    WebhookEventHandler<?> handler = getWebhookHandler(req.getHeader("X-Github-Event"));
    if (handler == null) {
        resp.sendError(SC_NOT_FOUND);
        return;
    }

    try (BufferedReader reader = req.getReader()) {
        String body = Joiner.on("\n").join(CharStreams.readLines(reader));
        if (!validateSignature(req.getHeader("X-Hub-Signature"), body, req.getCharacterEncoding())) {
            logger.error("Signature mismatch to the payload");
            resp.sendError(SC_FORBIDDEN);
            return;
        }

        session.get().setUserAccountId(Account.Id.fromRef(config.webhookUser));
        GitHubLogin login = loginProvider.get(config.webhookUser);
        if (login == null || !login.isLoggedIn()) {
            logger.error("Cannot login to github as {}. {}.webhookUser is not correctly configured?",
                    config.webhookUser, GitHubConfig.CONF_SECTION);
            resp.setStatus(SC_INTERNAL_SERVER_ERROR);
            return;
        }
        requestScopedLoginProvider.get(req).login(login.getToken());

        if (callHander(handler, body)) {
            resp.setStatus(SC_NO_CONTENT);
        } else {
            resp.sendError(SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:org.geoserver.opensearch.rest.ProductsController.java

@PutMapping(path = "{product:.+}/description", consumes = MediaType.TEXT_HTML_VALUE)
public void putProductDescription(@PathVariable(name = "collection", required = true) String collection,
        @PathVariable(name = "product", required = true) String product, HttpServletRequest request)
        throws IOException {
    // check the product exists
    queryProduct(collection, product, q -> {
    });/* w  w  w.j  a va2 s. c o  m*/

    String description = IOUtils.toString(request.getReader());

    updateDescription(collection, product, description);
}

From source file:org.openhab.io.neeo.internal.servletservices.ThingDashboardService.java

/**
 * Handles the post for the 'updatedevice', 'restoredevice' or 'refreshdevice'.
 *
 * @see DefaultServletService#handlePost(HttpServletRequest, String[], HttpServletResponse)
 *///from   w  w  w.j av a 2 s  .  c  om
@Override
public void handlePost(HttpServletRequest req, String[] paths, HttpServletResponse resp) throws IOException {
    Objects.requireNonNull(req, "req cannot be null");
    Objects.requireNonNull(paths, "paths cannot be null");
    Objects.requireNonNull(resp, "resp cannot be null");
    if (paths.length == 0) {
        throw new IllegalArgumentException("paths cannot be empty");
    }

    try {
        if (StringUtils.equalsIgnoreCase(paths[0], "updatedevice")) {
            final NeeoDevice device = gson.fromJson(req.getReader(), NeeoDevice.class);
            context.getDefinitions().put(device);

            for (NeeoBrainServlet servlet : service.getServlets()) {
                servlet.getBrainApi().restart(); // restart so brain will query changes
            }

            NeeoUtil.write(resp, gson.toJson(ReturnStatus.SUCCESS));
        } else if (StringUtils.equalsIgnoreCase(paths[0], "restoredevice")) {
            final NeeoThingUID uid = new NeeoThingUID(IOUtils.toString(req.getReader()));
            context.getDefinitions().remove(uid);
            final NeeoDevice device = context.getDefinitions().getDevice(uid);
            if (device == null) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Device no longer exists in openHAB!")));
            } else {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus(device)));
            }
        } else if (StringUtils.equalsIgnoreCase(paths[0], "refreshdevice")) {
            final NeeoThingUID uid = new NeeoThingUID(IOUtils.toString(req.getReader()));
            final NeeoDevice device = context.getDefinitions().getDevice(uid);
            if (device == null) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Device no longer exists in openHAB!")));
            } else {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus(device)));
            }
        } else if (StringUtils.equalsIgnoreCase(paths[0], "deletedevice")) {
            final NeeoThingUID uid = new NeeoThingUID(IOUtils.toString(req.getReader()));
            final boolean deleted = context.getDefinitions().remove(uid);
            NeeoUtil.write(resp, gson.toJson(new ReturnStatus(
                    deleted ? null : "Device " + uid + " was not found (possibly already deleted?)")));
        } else if (StringUtils.equalsIgnoreCase(paths[0], "exportrules")) {
            final NeeoThingUID uid = new NeeoThingUID(IOUtils.toString(req.getReader()));
            final NeeoDevice device = context.getDefinitions().getDevice(uid);
            if (device == null) {
                NeeoUtil.write(resp, gson.toJson(new ReturnStatus("Device " + uid + " was not found")));
            } else {
                writeExampleRules(resp, device);
            }
        } else {
            logger.debug("Unknown post path: {}", StringUtils.join(paths, ','));
        }
    } catch (JsonParseException | IllegalArgumentException | NullPointerException e) {
        logger.debug("Exception handling post: {}", e.getMessage(), e);
        NeeoUtil.write(resp, gson.toJson(new ReturnStatus(e.getMessage())));
    }
}

From source file:servlets.Install_servlets.java

private void installPostHandler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w  w w . j  a  va  2s  .  com*/
        JsonObject settings = (JsonObject) new JsonParser().parse(request.getReader());
        response = install(settings, response);
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Install_servlets.class.getName(), "userLoginPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:admin.controller.ServletAddHtmlTemplate.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww w. j  av  a2 s .c o 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
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Layout layout = new Layout();
    String fileName = null, filePath = null, fieldName = null, uploadPath = null, uploadType = null;
    StringBuffer string_buffer = new StringBuffer();

    try {
        /* TODO output your page here. You may use following sample code. */
        uploadPath = AppConstants.BASE_HTML_TEMPLATE_UPLOAD_PATH;
        BufferedReader reader = request.getReader();
        String line = null;
        while ((line = reader.readLine()) != null) {
            string_buffer.append(line);
        }

        JSONParser parser = new JSONParser();
        JSONObject json_html_template = null;
        json_html_template = (JSONObject) parser.parse(string_buffer.toString());
        String type = (String) json_html_template.get("type");

        //            BufferedReader txtfile = new BufferedReader(new FileReader("c:\\test.txt"));
        String model_id = (String) json_html_template.get("model_id");
        String model_name = (String) json_html_template.get("model_name");
        String html_content = (String) json_html_template.get("html_content");

        fileName = model_name + ".html";
        filePath = uploadPath + File.separator + fileName;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        OutputStream htmlfile = new FileOutputStream(new File(filePath));

        PrintStream printhtml = new PrintStream(htmlfile);

        layout.editModel(Integer.parseInt(model_id), fileName);

        printhtml.print(html_content);

        printhtml.close();
        htmlfile.close();
        out.write("true");
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
        out.write(getSqlMethodsInstance().error);
    }
}

From source file:org.apache.marmotta.platform.sparql.webservices.SparqlWebService.java

/**
 * Execute a SPARQL 1.1 Update request using update via POST directly; 
 * see details at http://www.w3.org/TR/sparql11-protocol/\#update-operation
 * /*from ww  w  . j a v a  2 s . c o  m*/
 * @param request the servlet request (to retrieve the SPARQL 1.1 Update query passed in the
 *            body of the POST request)
 * @HTTP 200 in case the update was carried out successfully
 * @HTTP 400 in case the update query is missing or invalid
 * @HTTP 500 in case the update was not successful
 * @return empty content in case the update was successful, the error message in case an error
 *         occurred
 */
@POST
@Path(UPDATE)
@Consumes("application/sparql-update")
public Response updatePostDirectly(@Context HttpServletRequest request,
        @QueryParam("output") String resultType) {
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("utf-8");
        }
        String q = CharStreams.toString(request.getReader());
        return update(q, resultType, request);
    } catch (IOException e) {
        return Response.serverError().entity(WebServiceUtil.jsonErrorResponse(e)).build();
    }
}

From source file:thinwire.render.web.WebServlet.java

private void handlePostEvent(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    HttpSession httpSession = request.getSession();
    ApplicationHolder holder = (ApplicationHolder) httpSession.getAttribute("instance");
    response.setContentType("text/plain; charset=utf-8");
    response.setHeader("Cache-Control", "no-store");
    if (holder == null || holder.app == null)
        return;/* www. ja v  a2 s  .  c  om*/
    holder.app.processActionEvents(request.getReader(), response.getWriter());

    if (holder.app.state == WebApplication.State.TERMINATED) {
        holder.app = null;
        httpSession.invalidate();
    }
}