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:com.st.qunar.order.web.order.OrderController.java

@RequestMapping(value = "export")
public void mockQnOrderExportServer(HttpServletResponse resp) throws IOException {
    resp.setCharacterEncoding("UTF-8");
    PrintWriter pw = resp.getWriter();
    String xml = FileUtils.readFileToString(new File("qn?50?.xml"));
    System.out.println("getFile:" + xml);
    pw.write(xml);/*ww  w.j a va2  s .  c  o  m*/
    pw.close();
}

From source file:gov.nih.nci.cabig.caaers.tools.spring.tabbedflow.SimpleFormAjaxableController.java

protected void respondAjaxFreeText(ModelAndView modelAndView, HttpServletResponse response) throws Exception {
    PrintWriter pr = response.getWriter();
    pr.println(modelAndView.getModel().get(getFreeTextModelName()));
    pr.flush();//from www.  j a v a2s  .  com
    pr.close();
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Get a response Writer depending on acceptable encodings
 * //ww  w . j a v  a2 s.  com
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
public static Writer getWriter(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    Writer out;
    String encodings = request.getHeader("Accept-Encoding");
    if (debug) {
        log.debug("encodings=" + encodings);
    }
    if (encodings != null && encodings.indexOf("gzip") != -1) {
        response.setHeader("Content-Encoding", "gzip");
        out = new OutputStreamWriter(new GZIPOutputStream(response.getOutputStream()), "UTF-8");
    } else if (encodings != null && encodings.indexOf("deflate") != -1) {
        response.setHeader("Content-Encoding", "deflate");
        out = new OutputStreamWriter(new DeflaterOutputStream(response.getOutputStream()), "UTF-8");
    } else {
        out = response.getWriter();
    }
    return out;
}

From source file:de.knurt.fam.template.controller.json.PublicDocController.java

@Override
public ModelAndView handleRequest(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;/*from  ww  w  .j ava  2  s .  com*/
    try {
        rs.setContentType("application/json");
        pw = rs.getWriter();
        String result = "{}";
        if (rq.getParameter("doc") != null && this.isAllowedToShow(rq, rq.getParameter("doc"))) {
            result = FamCouchDBDao.getInstance().getContentAsString(rq.getParameter("doc"));
        }
        IOUtils.write(result, pw);
    } catch (IOException ex) {
        FamLog.exception(ex, 201204191241l);
    } finally {
        IOUtils.closeQuietly(pw);
    }
    return null;
}

From source file:Buffering.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setBufferSize(8 * 1024); // 8K 
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    int size = res.getBufferSize(); // returns 8096 or greater

    log("The default buffer size is " + size);

    out.println("The client won't see this");
    res.reset();//w w w. j  ava  2  s  . co m
    out.println("Nor will the client see this!");
    res.reset();
    out.println("And this won't be seen if sendError() is called");
    if (req.getParameter("param") == null) {
        res.sendError(res.SC_BAD_REQUEST, "param needed");
    }
}

From source file:UrlRewrite.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    String contextPath = request.getContextPath();
    String encodedUrl = response.encodeURL(contextPath + "/default.jsp");

    out.println("<html>");
    out.println("<head>");
    out.println("<title>URL Rewriter</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>This page will use URL rewriting if necessary</h2>");
    out.println("Go to the default.jsp page <a href=\"" + encodedUrl + "\">here</a>.");
    out.println("</body>");
    out.println("</html>");

}

From source file:com.ijuru.kumva.sms.web.SearchServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w  w  w . java2 s. c om
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String query = request.getParameter("q");

    if (query == null || query.length() == 0)
        return;

    query = query.trim();

    String keyword = Context.getOptions().getInputKeyword();

    // Strip keyword if one is specified
    if (StringUtils.isNotEmpty(keyword) && query.toLowerCase().startsWith(keyword + " ")) {
        query = query.substring((keyword + " ").length());
    }

    int timeout = Context.getOptions().getConnectionTimeout();
    String searchRef = Context.getOptions().getSearchRef();

    try {
        Search search = new RemoteSearch(Context.getDictionary(), timeout);
        SearchResult result = search.execute(query, 10, searchRef);
        String message = Messages.searchResult(result, query);

        out.write(message);
    } catch (Exception ex) {
        out.write(Messages.errorOccurred());

        log.warn("Remote search failed");
    }
}

From source file:com.qwazr.webapps.exception.WebappException.java

private void sendQuietlyHTML(HttpServletResponse response) throws IOException {
    PrintWriter printWriter = response.getWriter();
    String message = StringEscapeUtils.escapeHtml4(error.message);
    response.setStatus(error.status);/* w w w  .jav a  2s  .c  o  m*/
    response.setContentType("text/html");
    printWriter.print("<html><head><title>");
    printWriter.print(error.title.title);
    printWriter.println("</title></head>");
    printWriter.print("<body><h3>");
    printWriter.print(error.title.title);
    printWriter.println("</h3>");
    printWriter.print("<pre>");
    printWriter.print(message);
    printWriter.println("</pre></body></html>");
}

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

private static void sendXQueryResponse(HttpServletResponse res, Object o) throws IOException {
    // Make sure to leave the status code alone.  It defaults to 200, but sometimes
    // callers of this method will have set it to a custom code.
    res.setContentType("x-marklogic/xquery; charset=UTF-8");
    //res.setContentType("text/plain");
    Writer writer = res.getWriter(); // care to handle errors later?

    if (o == null) {
        writer.write("()");
    }//  ww w  . j a  va  2  s  .c  o  m

    else if (o instanceof byte[]) {
        writer.write("binary {'");
        writer.write(hexEncode((byte[]) o));
        writer.write("'}");
    }

    else if (o instanceof Object[]) {
        Object[] arr = (Object[]) o;
        writer.write("(");
        for (int i = 0; i < arr.length; i++) {
            sendXQueryResponse(res, arr[i]);
            if (i + 1 < arr.length)
                writer.write(", ");
        }
        writer.write(")");
    }

    else if (o instanceof String) {
        writer.write("'");
        writer.write(escapeSingleQuotes(o.toString()));
        writer.write("'");
    } else if (o instanceof Integer) {
        writer.write("xs:int(");
        writer.write(o.toString());
        writer.write(")");
    } else if (o instanceof Long) {
        writer.write("xs:integer(");
        writer.write(o.toString());
        writer.write(")");
    } else if (o instanceof Float) {
        Float flt = (Float) o;
        writer.write("xs:float(");
        if (flt.equals(Float.POSITIVE_INFINITY)) {
            writer.write("'INF'");
        } else if (flt.equals(Float.NEGATIVE_INFINITY)) {
            writer.write("'-INF'");
        } else if (flt.equals(Float.NaN)) {
            writer.write("fn:number(())"); // poor man's way to write NaN
        } else {
            writer.write(o.toString());
        }
        writer.write(")");
    } else if (o instanceof Double) {
        Double dbl = (Double) o;
        writer.write("xs:double(");
        if (dbl.equals(Double.POSITIVE_INFINITY)) {
            writer.write("'INF'");
        } else if (dbl.equals(Double.NEGATIVE_INFINITY)) {
            writer.write("'-INF'");
        } else if (dbl.equals(Double.NaN)) {
            writer.write("fn:number(())"); // poor man's way to write NaN
        } else {
            writer.write(o.toString());
        }
        writer.write(")");
    } else if (o instanceof Boolean) {
        writer.write("xs:boolean('");
        writer.write(o.toString());
        writer.write("')");
    } else if (o instanceof BigDecimal) {
        writer.write("xs:decimal(");
        writer.write(o.toString());
        writer.write(")");
    } else if (o instanceof Date) {
        // We want something like: 2006-04-30T01:28:30.499-07:00
        // We format to get:       2006-04-30T01:28:30.499-0700
        // Then we add in the colon
        writer.write("xs:dateTime('");
        String d = dateFormat.format((Date) o);
        writer.write(d.substring(0, d.length() - 2));
        writer.write(":");
        writer.write(d.substring(d.length() - 2));
        writer.write("')");
    } else if (o instanceof XMLGregorianCalendar) {
        XMLGregorianCalendar greg = (XMLGregorianCalendar) o;
        QName type = greg.getXMLSchemaType();
        if (type.equals(DatatypeConstants.DATETIME)) {
            writer.write("xs:dateTime('");
        } else if (type.equals(DatatypeConstants.DATE)) {
            writer.write("xs:date('");
        } else if (type.equals(DatatypeConstants.TIME)) {
            writer.write("xs:time('");
        } else if (type.equals(DatatypeConstants.GYEARMONTH)) {
            writer.write("xs:gYearMonth('");
        } else if (type.equals(DatatypeConstants.GMONTHDAY)) {
            writer.write("xs:gMonthDay('");
        } else if (type.equals(DatatypeConstants.GYEAR)) {
            writer.write("xs:gYear('");
        } else if (type.equals(DatatypeConstants.GMONTH)) {
            writer.write("xs:gMonth('");
        } else if (type.equals(DatatypeConstants.GDAY)) {
            writer.write("xs:gDay('");
        }
        writer.write(greg.toXMLFormat());
        writer.write("')");
    } else if (o instanceof Duration) {
        Duration dur = (Duration) o;
        /*
        // The following fails on Xerces
        QName type = dur.getXMLSchemaType();
        if (type.equals(DatatypeConstants.DURATION)) {
          writer.write("xs:duration('");
        }
        else if (type.equals(DatatypeConstants.DURATION_DAYTIME)) {
          writer.write("xdt:dayTimeDuration('");
        }
        else if (type.equals(DatatypeConstants.DURATION_YEARMONTH)) {
          writer.write("xdt:yearMonthDuration('");
        }
        */
        // If no years or months, must be DURATION_DAYTIME
        if (dur.getYears() == 0 && dur.getMonths() == 0) {
            writer.write("xdt:dayTimeDuration('");
        }
        // If has years or months but nothing else, must be DURATION_YEARMONTH
        else if (dur.getDays() == 0 && dur.getHours() == 0 && dur.getMinutes() == 0 && dur.getSeconds() == 0) {
            writer.write("xdt:yearMonthDuration('");
        } else {
            writer.write("xs:duration('");
        }
        writer.write(dur.toString());
        writer.write("')");
    }

    else if (o instanceof org.jdom.Element) {
        org.jdom.Element elt = (org.jdom.Element) o;
        writer.write("xdmp:unquote('");
        // Because "&lt;" in XQuery is the same as "<" I need to double escape any ampersands
        writer.write(new org.jdom.output.XMLOutputter().outputString(elt).replaceAll("&", "&amp;")
                .replaceAll("'", "''"));
        writer.write("')/*"); // make sure to return the root elt
    } else if (o instanceof org.jdom.Document) {
        org.jdom.Document doc = (org.jdom.Document) o;
        writer.write("xdmp:unquote('");
        writer.write(new org.jdom.output.XMLOutputter().outputString(doc).replaceAll("&", "&amp;")
                .replaceAll("'", "''"));
        writer.write("')");
    } else if (o instanceof org.jdom.Text) {
        org.jdom.Text text = (org.jdom.Text) o;
        writer.write("text {'");
        writer.write(escapeSingleQuotes(text.getText()));
        writer.write("'}");
    } else if (o instanceof org.jdom.Attribute) {
        // <fake xmlns:pref="http://uri.com" pref:attrname="attrvalue"/>/@*:attrname
        // <fake xmlns="http://uri.com" attrname="attrvalue"/>/@*:attrname
        org.jdom.Attribute attr = (org.jdom.Attribute) o;
        writer.write("<fake xmlns");
        if ("".equals(attr.getNamespacePrefix())) {
            writer.write("=\"");
        } else {
            writer.write(":" + attr.getNamespacePrefix() + "=\"");
        }
        writer.write(attr.getNamespaceURI());
        writer.write("\" ");
        writer.write(attr.getQualifiedName());
        writer.write("=\"");
        writer.write(escapeSingleQuotes(attr.getValue()));
        writer.write("\"/>/@*:");
        writer.write(attr.getName());
    } else if (o instanceof org.jdom.Comment) {
        org.jdom.Comment com = (org.jdom.Comment) o;
        writer.write("comment {'");
        writer.write(escapeSingleQuotes(com.getText()));
        writer.write("'}");
    } else if (o instanceof org.jdom.ProcessingInstruction) {
        org.jdom.ProcessingInstruction pi = (org.jdom.ProcessingInstruction) o;
        writer.write("processing-instruction ");
        writer.write(pi.getTarget());
        writer.write(" {'");
        writer.write(escapeSingleQuotes(pi.getData()));
        writer.write("'}");
    }

    else if (o instanceof QName) {
        QName q = (QName) o;
        writer.write("fn:expanded-QName('");
        writer.write(escapeSingleQuotes(q.getNamespaceURI()));
        writer.write("','");
        writer.write(q.getLocalPart());
        writer.write("')");
    }

    else {
        writer.write("error('XQuery tried to retrieve unsupported type: " + o.getClass().getName() + "')");
    }

    writer.flush();
}

From source file:edu.lafayette.metadb.web.projectman.imagesettings.ShowDerivativeSettings.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///  w w  w. jav a  2  s .c o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String projname = (String) request.getSession(false).getAttribute(Global.SESSION_PROJECT);
    JSONObject output = new JSONObject();
    try {
        DerivativeSetting deriv = DerivativeDAO.getDerivativeSetting(projname, Global.DERIV_THUMB_SETTING);
        output.put(Global.DERIV_THUMB_SETTING, this.extractDerivSettings(deriv));

        deriv = DerivativeDAO.getDerivativeSetting(projname, Global.DERIV_CUSTOM_SETTING);
        output.put(Global.DERIV_CUSTOM_SETTING, this.extractDerivSettings(deriv));

        deriv = DerivativeDAO.getDerivativeSetting(projname, Global.DERIV_ZOOM_SETTING);
        output.put("zoom", this.extractDerivSettings(deriv));

        deriv = DerivativeDAO.getDerivativeSetting(projname, Global.DERIV_FULLSIZE_SETTING);
        output.put(Global.DERIV_FULLSIZE_SETTING, this.extractDerivSettings(deriv));

        output.put("hostname", ProjectsDAO.getProjectData(projname).getBaseUrl());
    } catch (JSONException e) {
        MetaDbHelper.logEvent(this.getClass().toString(), "doPost", MetaDbHelper.getStackTrace(e));
    }
    response.setContentType("application/x-json");
    out.print(output);
}