Example usage for javax.servlet.http HttpServletResponse getWriter

List of usage examples for javax.servlet.http HttpServletResponse getWriter

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getWriter.

Prototype

public PrintWriter getWriter() throws IOException;

Source Link

Document

Returns a PrintWriter object that can send character text to the client.

Usage

From source file:org.chtijbug.drools.platform.web.filter.DynamicBaseFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug(">> doFilterInternal()");
    try {//from ww  w.  java2s  .  c o m
        PrintWriter out = response.getWriter();
        CharResponseWrapper wrapper = new CharResponseWrapper(response);
        filterChain.doFilter(request, wrapper);

        String baseHref = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/";
        logger.debug("About to replace the base href element with {}", baseHref);
        String modifiedHtml = baseElementPattern.matcher(wrapper.toString())
                .replaceAll("<base href=\"" + baseHref + "\"");
        logger.debug("Modified HTML content : {}", modifiedHtml);
        // Write our modified text to the real response
        response.setContentLength(modifiedHtml.getBytes().length);
        out.write(modifiedHtml);
        out.close();
    } catch (Throwable t) {
        logger.error(t.getMessage());
    } finally {
        logger.debug("<< doFilterInternal()");
    }
}

From source file:ProductServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try (PrintWriter out = response.getWriter()) {
        Connection conn = getConnection();
        Statement stmt = conn.createStatement();

        if (!request.getParameterNames().hasMoreElements()) {
            out.println(getResults("SELECT * FROM product"));
        } else {//from   w ww. j a  v a2s  . co  m
            if (request.getParameter("productID") == null) {
                out.println(getResults("SELECT * FROM product ORDER BY productID DESC LIMIT 1"));
            } else {
                int id = Integer.parseInt(request.getParameter("productID"));
                out.println(getResults("SELECT * FROM product WHERE productID = ?", String.valueOf(id)));
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(ProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.imagelake.android.settings.Servlet_PrivilegeSetting.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {/*from w  w  w .  jav a  2 s  .  c o m*/
        String type = request.getParameter("type");

        if (type != null && !type.equals("")) {

            if (type.equals("AllUserTypes")) {
                String k = inf.listPrivilages();
                System.out.println(k);
                out.write(k);
            } else if (type.equals("AddUserTypes")) {
                String ustype = request.getParameter("ustype");
                if (ustype != null && !ustype.trim().equals("")) {
                    boolean k = udi.addUsertType(ustype);
                    if (k) {
                        out.write("msg=Add_User_Type_Successfully...");
                    } else {
                        out.write("msg=Unable to complete the action.");
                    }
                } else {
                    out.write("msg=Internal server error,Please try again later.");
                }
            } else if (type.equals("TypePrivilege")) {
                String id = request.getParameter("userType");
                List<Privilages> li = pdi.listAll(Integer.parseInt(id));
                List<Interfaces> lf = inf.listAll((ArrayList<Privilages>) li);
                ja = new JSONArray();
                for (int i = 0; i < lf.size(); i++) {
                    Interfaces in = lf.get(i);
                    JSONObject jo = new JSONObject();
                    jo.put("id", in.getInterface_id());
                    jo.put("name", in.getDisplay_name());
                    jo.put("state", in.getState());
                    ja.add(jo);
                }
                out.write("json=" + ja.toJSONString());
            } else if (type.equals("remvinf")) {
                String id = request.getParameter("userType");
                String infid = request.getParameter("infid");

                boolean k = pdi.updatePrivilage(Integer.parseInt(id), Integer.parseInt(infid), 2);
                if (k) {
                    out.write("msg=Remve_Successfully...");
                } else {
                    out.write("msg=Unable to complete the action.");
                }
            } else if (type.equals("AllInterface")) {
                String k = inf.listInterfaces();
                System.out.println(type);
                System.out.println(k);
                out.write(k);
            } else if (type.equals("addinf")) {
                String id = request.getParameter("userType");
                String infid = request.getParameter("intfid");
                if (id != null && !id.trim().equals("") && Integer.parseInt(id) != 0 && infid != null
                        && !infid.trim().equals("") && Integer.parseInt(infid) != 0) {
                    boolean k = pdi.addPrivilage(Integer.parseInt(id), Integer.parseInt(infid), 1);
                    if (k) {
                        out.write("msg=Int_Add_Successfully...");
                    } else {
                        out.write("msg=Unable to complete the action.");
                    }
                } else {
                    out.write("msg=Internal server error,Please try again later.");
                }
            }
        } else {
            out.write("msg=Internal server error,Please try again later.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:controler.purchaseServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww . ja va 2 s.c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    DbModules dm = new DbModules();
    HttpSession session = request.getSession(true);

    try {
        String myValues[] = request.getParameterValues("myValues");
        Object attribValue = session.getAttribute("customerID");
        String value = " " + attribValue;
        value = value.trim();
        String message = null;
        if ("null".equals(value) || "".equals(value)) {
            message = "Please log in first to make any purchases";
        } else {
            try {
                message = dm.UpdatePurchase(myValues, value);
            } catch (ParseException ex) {
                Logger.getLogger(purchaseServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        out.print(message);

    } finally {
        out.close();
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.admin.SparqlQueryController.java

private void do400BadRequest(String message, HttpServletResponse resp) throws IOException {
    resp.setStatus(400);/*from w w  w .j av  a 2s .  c om*/
    resp.getWriter().println(message);
}

From source file:me.uni.sushilkumar.geodine.util.WhatsCooking.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//from  w  w  w  .j  a 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    try {
        JSONObject obj = new JSONObject();
        JSONArray array = new JSONArray();
        DBConnection con = new DBConnection();
        ArrayList<String> cuisineList = con.getCuisineList();
        Random generator = new Random();
        int size = cuisineList.size();
        for (int i = 0; i < 10; i++) {
            JSONObject temp = new JSONObject();
            String title = cuisineList.get(generator.nextInt(size));
            //title=WordUtils.capitalize(title);
            temp.put("title", title);
            title = title.replaceAll("\\s+", "-");
            String link = "cuisine/" + title;
            temp.put("link", link);
            array.add(temp);
        }
        obj.put("links", array);
        out.println(obj.toJSONString());
    } catch (SQLException ex) {
        Logger.getLogger(WhatsCooking.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:checkCoupon.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww  . j  a va  2  s.co 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String deviceId = request.getParameter("deviceId");
        String couponId = request.getParameter("couponId");

        String url = "https://tgl.standardchartered.com/bridgeheadi18n/mcoupon/check?deviceId=" + deviceId
                + "&couponId=" + couponId;
        HttpClient client = new DefaultHttpClient();
        HttpGet req = new HttpGet(url);
        HttpResponse res = client.execute(req);
        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        String line = "";
        String total = "";
        while ((line = rd.readLine()) != null) {
            total += line;
        }

        total = total.substring(0, total.length());
        out.println(total);
    }
}

From source file:com.facebook.tsdb.tsdash.server.DataEndpoint.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {/*w ww  . j av a 2s . c o  m*/
        long ts = System.currentTimeMillis();
        // decode parameters
        String jsonParams = request.getParameter("params");
        if (jsonParams == null) {
            throw new Exception("Parameters not specified");
        }
        JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams);
        long tsFrom = (Long) jsonParamsObj.get("tsFrom");
        long tsTo = (Long) jsonParamsObj.get("tsTo");
        JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics");
        if (metricsArray.size() == 0) {
            throw new Exception("No metrics to fetch");
        }
        MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()];
        for (int i = 0; i < metricsArray.size(); i++) {
            metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i));
        }

        TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
        Metric[] metrics = new Metric[metricQueries.length];
        for (int i = 0; i < metrics.length; i++) {
            MetricQuery q = metricQueries[i];
            metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders);
            metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator);
            if (q.rate) {
                metrics[i].computeRate();
            }
        }
        long loadTime = System.currentTimeMillis() - ts;
        JSONObject responseObj = new JSONObject();
        JSONArray encodedMetrics = new JSONArray();
        for (Metric metric : metrics) {
            encodedMetrics.add(metric.toJSONObject());
        }
        responseObj.put("metrics", encodedMetrics);
        responseObj.put("loadtime", loadTime);
        DataTable dataTable = new DataTable(metrics);
        responseObj.put("datatable", dataTable.toJSONObject());
        out.println(responseObj.toJSONString());
        long encodingTime = System.currentTimeMillis() - ts - loadTime;
        logger.info("[Data] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, "
                + "encoding time: " + encodingTime + "ms");
    } catch (Exception e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}

From source file:controller.UploadServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet UploadServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet UploadServlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }/*from  w  w  w.  java 2s  .  co m*/
}

From source file:com.commercehub.dropwizard.BuildInfoServlet.java

private void writeAllJson(HttpServletResponse response) throws IOException {
    response.setContentType(MediaType.APPLICATION_JSON);
    objectWriter.writeValue(response.getWriter(), manifestAttributes);
}