Example usage for javax.servlet.http HttpServletResponse setCharacterEncoding

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

Introduction

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

Prototype

public void setCharacterEncoding(String charset);

Source Link

Document

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

Usage

From source file:net.solarnetwork.web.support.JSONView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    PropertyEditorRegistrar registrar = this.propertyEditorRegistrar;
    Enumeration<String> attrEnum = request.getAttributeNames();
    while (attrEnum.hasMoreElements()) {
        String key = attrEnum.nextElement();
        Object val = request.getAttribute(key);
        if (val instanceof PropertyEditorRegistrar) {
            registrar = (PropertyEditorRegistrar) val;
            break;
        }/*from   www .j  av a2s .  c o m*/
    }

    response.setCharacterEncoding(UTF8_CHAR_ENCODING);
    response.setContentType(getContentType());
    Writer writer = response.getWriter();
    if (this.includeParentheses) {
        writer.write('(');
    }
    JsonGenerator json = new JsonFactory().createGenerator(writer);
    json.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (indentAmount > 0) {
        json.useDefaultPrettyPrinter();
    }
    json.writeStartObject();
    for (String key : model.keySet()) {
        Object val = model.get(key);
        writeJsonValue(json, key, val, registrar);
    }
    json.writeEndObject();
    json.close();
    if (this.includeParentheses) {
        writer.write(')');
    }
}

From source file:com.panet.imeta.www.GetJobStatusServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!request.getContextPath().equals(CONTEXT_PATH))
        return;//from   w w w.ja  va 2  s .  c  o m

    if (log.isDebug())
        log.logDebug(toString(), Messages.getString("GetJobStatusServlet.Log.JobStatusRequested"));

    String jobName = request.getParameter("name");
    boolean useXML = "Y".equalsIgnoreCase(request.getParameter("xml"));

    response.setStatus(HttpServletResponse.SC_OK);

    if (useXML) {
        response.setContentType("text/xml");
        response.setCharacterEncoding(Const.XML_ENCODING);
    } else {
        response.setContentType("text/html");
    }

    PrintWriter out = response.getWriter();

    Job job = jobMap.getJob(jobName);
    if (job != null) {
        String status = job.getStatus();

        if (useXML) {
            response.setContentType("text/xml");
            response.setCharacterEncoding(Const.XML_ENCODING);
            out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));

            SlaveServerJobStatus jobStatus = new SlaveServerJobStatus(jobName, status);

            Log4jStringAppender appender = (Log4jStringAppender) jobMap.getAppender(jobName);
            if (appender != null) {
                // The log can be quite large at times, we are going to put a base64 encoding around a compressed stream
                // of bytes to handle this one.

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(appender.getBuffer().toString().getBytes());
                gzos.close();

                String loggingString = new String(Base64.encodeBase64(baos.toByteArray()));
                jobStatus.setLoggingString(loggingString);
            }

            // Also set the result object...
            //
            jobStatus.setResult(job.getResult()); // might be null

            out.println(jobStatus.getXML());
        } else {
            response.setContentType("text/html");

            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("<TITLE>" + Messages.getString("GetJobStatusServlet.KettleJobStatus") + "</TITLE>");
            out.println("<META http-equiv=\"Refresh\" content=\"10;url=/kettle/jobStatus?name="
                    + URLEncoder.encode(jobName, "UTF-8") + "\">");
            out.println("</HEAD>");
            out.println("<BODY>");
            out.println("<H1>" + Messages.getString("GetJobStatusServlet.JobStatus") + "</H1>");

            try {
                out.println("<table border=\"1\">");
                out.print("<tr> <th>" + Messages.getString("GetJobStatusServlet.Jobname") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.TransStatus") + "</th> </tr>");

                out.print("<tr>");
                out.print("<td>" + jobName + "</td>");
                out.print("<td>" + status + "</td>");
                out.print("</tr>");
                out.print("</table>");

                out.print("<p>");

                if (job.isFinished()) {
                    out.print("<a href=\"/kettle/startJob?name=" + URLEncoder.encode(jobName, "UTF-8") + "\">"
                            + Messages.getString("GetJobStatusServlet.StartJob") + "</a>");
                    out.print("<p>");
                } else {
                    out.print("<a href=\"/kettle/stopJob?name=" + URLEncoder.encode(jobName, "UTF-8") + "\">"
                            + Messages.getString("GetJobStatusServlet.StopJob") + "</a>");
                    out.print("<p>");
                }

                out.println("<p>");

                out.print("<a href=\"/kettle/jobStatus/?name=" + URLEncoder.encode(jobName, "UTF-8")
                        + "&xml=y\">" + Messages.getString("TransStatusServlet.ShowAsXml") + "</a><br>");
                out.print("<a href=\"/kettle/status\">"
                        + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><br>");
                out.print("<p><a href=\"/kettle/jobStatus?name=" + URLEncoder.encode(jobName, "UTF-8") + "\">"
                        + Messages.getString("TransStatusServlet.Refresh") + "</a>");

                // Put the logging below that.
                Log4jStringAppender appender = (Log4jStringAppender) jobMap.getAppender(jobName);
                if (appender != null) {
                    out.println("<p>");
                    /*
                    out.println("<pre>");
                    out.println(appender.getBuffer().toString());
                    out.println("</pre>");
                    */
                    out.println(
                            "<textarea id=\"joblog\" cols=\"120\" rows=\"20\" wrap=\"off\" name=\"Job log\" readonly=\"readonly\">"
                                    + appender.getBuffer().toString() + "</textarea>");

                    out.println("<script type=\"text/javascript\"> ");
                    out.println("  joblog.scrollTop=joblog.scrollHeight; ");
                    out.println("</script> ");
                    out.println("<p>");
                }
            } catch (Exception ex) {
                out.println("<p>");
                out.println("<pre>");
                ex.printStackTrace(out);
                out.println("</pre>");
            }

            out.println("<p>");
            out.println("</BODY>");
            out.println("</HTML>");
        }
    } else {
        if (useXML) {
            out.println(new WebResult(WebResult.STRING_ERROR,
                    Messages.getString("StartJobServlet.Log.SpecifiedJobNotFound", jobName)));
        } else {
            out.println("<H1>Job '" + jobName + "' could not be found.</H1>");
            out.println("<a href=\"/kettle/status\">"
                    + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><p>");
        }
    }
}

From source file:au.org.ala.biocache.web.ExploreController.java

/**
 * Returns the species that only have occurrences in the supplied WKT.
 * @return/*from www  .j  av a 2 s  .c om*/
 */
@RequestMapping(value = "/explore/endemic/species.csv", method = RequestMethod.GET)
public void getEndemicSpeciesCSV(SpatialSearchRequestParams requestParams, HttpServletResponse response)
        throws Exception {
    requestParams.setFacets(new String[] { SearchDAOImpl.NAMES_AND_LSID });
    requestParams.setFq((String[]) ArrayUtils.add(requestParams.getFq(), "species_guid:[* TO *]"));
    List<FieldResultDTO> list = getSpeciesOnlyInWKT(requestParams, response);
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/plain");
    java.io.PrintWriter writer = response.getWriter();
    writer.write("Family,Scientific name,Common name,Taxon rank,LSID,# Occurrences");
    for (FieldResultDTO item : list) {
        String s = item.getLabel();
        if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 2)
            s = s.substring(1, s.length() - 1);
        String[] values = s.split("\\|", 6);
        if (values.length >= 5) {
            writer.write("\n" + values[4] + ",\"" + values[0] + "\",\"" + values[2] + "\",," + values[1] + ","
                    + item.getCount());
        }
    }
    writer.flush();
    writer.close();
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles empty get call this will return a list of projects that are
 * visible to the current user Not yet implemented.
 * //  www  . j av  a  2  s .c o m
 * @param mimeType
 * @param modifiedSince
 * @param request
 * @throws IOException
 * @throws BizPolicyException
 */
@RequestMapping(method = { RequestMethod.GET })
public void handleEmptyGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp)
        throws ServletException, IOException, BizPolicyException {

    Person user = getAuthenticatedUser();

    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        Set<Project> projects = projectBizService.findByAdmin(user);
        Bop bop = new Bop();
        bop.setProjects(projects);

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/xml");
        objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
    }
}

From source file:com.mmj.app.common.interceptor.ExportFileAnnotationInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    if (handler == null || response == null) {
        return;//from   w w  w . j a v  a 2  s . com
    }

    HandlerMethod hm = (HandlerMethod) handler;

    ExportWordFile exportWordFile = hm.getMethodAnnotation(ExportWordFile.class);
    // word,
    if (exportWordFile != null) {
        String wordName = exportWordFile.value();
        if (StringUtils.isEmpty(wordName)) {
            return;
        }
        String contentDis = "attachment;filename=" + wordName + ".doc";
        response.setHeader("content-disposition", contentDis);
        response.setContentType("application/msword;");
        response.setCharacterEncoding("UTF-8");
    }

    ExportExcelFile exportExcelFile = hm.getMethodAnnotation(ExportExcelFile.class);
    // excel,
    if (exportExcelFile != null) {
        String xlsName = exportExcelFile.value();
        if (StringUtils.isEmpty(xlsName)) {
            return;
        }
        List<?> list = (List<?>) modelAndView.getModel().get("list");
        String[] head = (String[]) modelAndView.getModel().get("head");
        modelAndView.clear();

        HSSFWorkbook workbook = ExcelUtils.defBuildExcel(list, xlsName, head);

        if (workbook == null) {
            try {
                response.getOutputStream().print("Not conform to the requirements of data");
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            return;
        }

        response.setHeader("content-disposition", "attachment;filename=" + xlsName + ".xls");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        //  response
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();
    }
}

From source file:com.rmn.qa.servlet.StatusServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int refresh = -1;

    if (request.getParameter("refresh") != null) {
        try {//w  ww.  ja va  2  s .co m
            refresh = Integer.parseInt(request.getParameter("refresh"));
        } catch (NumberFormatException e) {
            // ignore wrong param
        }

    }

    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(200);

    StringBuilder builder = new StringBuilder();

    builder.append("<html>");
    builder.append("<head>");

    if (refresh != -1) {
        builder.append(String.format("<meta http-equiv='refresh' content='%d' />", refresh));
    }
    builder.append("<title>Grid overview</title>");

    builder.append("<style>");
    builder.append(".busy {");
    builder.append(" opacity : 0.4;");
    builder.append("filter: alpha(opacity=40);");
    builder.append("}");
    builder.append("</style>");
    builder.append("</head>");

    builder.append("<body>");
    builder.append("<H1>Grid Hub ");
    builder.append(coreVersion).append(coreRevision);
    builder.append("</H1>");
    int chromeThreads = requestMatcher.getNumFreeThreadsForParameters(getRegistry().getAllProxies(),
            new AutomationRunRequest(StatusServlet.class.getSimpleName(), null, BrowserType.CHROME));
    int firefoxThreads = requestMatcher.getNumFreeThreadsForParameters(getRegistry().getAllProxies(),
            new AutomationRunRequest(StatusServlet.class.getSimpleName(), null, BrowserType.FIREFOX));
    int ieThreads = requestMatcher.getNumFreeThreadsForParameters(getRegistry().getAllProxies(),
            new AutomationRunRequest(StatusServlet.class.getSimpleName(), null, "internetexplorer"));
    builder.append("<H2>Free Threads - Chrome: ").append(chromeThreads).append(" Firefox: ")
            .append(firefoxThreads).append(" IE: ").append(ieThreads).append("</H2>");

    for (RemoteProxy proxy : getRegistry().getAllProxies()) {
        StringBuilder localBuilder = new StringBuilder();

        localBuilder.append("<fieldset>");
        localBuilder.append("<legend>").append(proxy.getClass().getSimpleName()).append("</legend>");
        localBuilder.append("listening on ").append(proxy.getRemoteHost());

        Object instanceId = proxy.getConfig().custom.get(AutomationConstants.INSTANCE_ID);
        if (instanceId != null) {
            AutomationDynamicNode node = AutomationContext.getContext().getNode((String) instanceId);
            if (node != null) {
                localBuilder.append("<br>EC2 dynamic node " + node.getInstanceId());
                if (!StringUtils.isEmpty(node.getInstanceType())) {
                    localBuilder.append("<br>Instance Type " + node.getInstanceType());
                }
                localBuilder.append("<br>Start time " + node.getStartDate());
                localBuilder.append("<br>Current shutdown time ").append(node.getEndDate());
                localBuilder.append("<br>Requested test run ").append(node.getUuid());
            }
        }
        if (((DefaultRemoteProxy) proxy).isDown()) {
            localBuilder.append("(cannot be reached at the moment)");
        }
        localBuilder.append("<br />");
        if (proxy.getTimeOut() > 0) {
            int inSec = proxy.getTimeOut() / 1000;
            localBuilder.append("test session time out after ").append(inSec).append(" sec.<br />");
        }

        localBuilder.append("Supports up to <b>").append(proxy.getMaxNumberOfConcurrentTestSessions())
                .append("</b> concurrent tests from: <br />");

        localBuilder.append("");
        for (TestSlot slot : proxy.getTestSlots()) {
            TestSession session = slot.getSession();

            String icon = getIcon(slot.getCapabilities(), proxy);
            if (icon != null) {
                localBuilder.append("<img ");
                localBuilder.append("src='").append(icon).append("' ");
            } else {
                localBuilder.append("<a href='#' ");
            }

            if (session != null) {
                localBuilder.append(" class='busy' ");
                localBuilder.append(" title='").append(session.get("lastCommand")).append("' ");
            } else {
                localBuilder.append(" title='").append(slot.getCapabilities())
                        .append("type=" + slot.getProtocol()).append("' ");
            }

            if (icon != null) {
                localBuilder.append("/>");
            } else {
                localBuilder.append(">");
                localBuilder.append(slot.getCapabilities().get(CapabilityType.BROWSER_NAME));
                localBuilder.append("</a>");
            }

        }
        localBuilder.append("</fieldset>");
        builder.append(localBuilder);
    }

    int numUnprocessedRequests = getRegistry().getNewSessionRequestCount();

    if (numUnprocessedRequests > 0) {
        builder.append(String.format("%d requests waiting for a slot to be free.", numUnprocessedRequests));
    }

    builder.append("<ul>");
    for (DesiredCapabilities req : getRegistry().getDesiredCapabilities()) {
        builder.append("<li>").append(req.asMap()).append("</li>");
    }
    builder.append("</ul>");

    if (request.getParameter("config") != null) {
        builder.append(getConfigInfo(request.getParameter("configDebug") != null));
    } else {
        builder.append("<a href='?config=true&configDebug=true'>view config</a>");
    }

    builder.append("</body>");
    builder.append("</html>");

    try (InputStream in = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));) {
        ByteStreams.copy(in, response.getOutputStream());
    } finally {
        response.flushBuffer();
    }
}

From source file:io.resthelper.RestHelperController.java

@RequestMapping(value = "/rest-helper/detail", method = RequestMethod.GET)
public void listApis(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("package") String packageName) throws IOException {
    response.setContentType("text/html; charset=utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();

    if (packageName == null || packageName.length() == 0) {
        out.flush();/*from w w w .j a  v  a  2s .com*/
        return;
    }
    if (!restHelperService.isValidIp(request)) {
        throw new NotAllowIpException();
    }

    List<RestApi> apiList = restHelperService.getApiList(packageName);

    String requestURI = request.getRequestURI();
    String contextName = requestURI.substring(0, requestURI.indexOf("/rest-helper"));

    out.println("<!DOCTYPE html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<meta charset=\"UTF-8\">");
    out.println("<title>API LIST</title>");
    out.println("<style type='text/css'>");
    out.println("body {");
    out.println("font-family: monospace;");
    out.println("}");
    out.println("ul.httpreq {");
    out.println("border: 1px solid #AAAAAA;");
    out.println("}");
    out.println("ul.httpreq li {");
    out.println("list-style-type: none;");
    out.println("}");
    out.println("ul.comment {");
    out.println("}");
    out.println("ul.comment li {");
    out.println("list-style-type: none;");
    out.println("}");
    out.println("span.success {");
    out.println("background: #55ff55; white-space: pre;");
    out.println("}");
    out.println("span.error {");
    out.println("background: #ff5555; white-space: pre;");
    out.println("}");
    out.println("span.etc {");
    out.println("background: #ffff55; white-space: pre;");
    out.println("}");
    out.println("</style>");
    out.println("<script type='text/javascript' src='./restfuljs'></script>");
    out.println("</head>");
    out.println("<body>");
    out.println("");
    out.println("<ul class=\"apiList\">");

    int apiIndex = 0;

    for (RestApi webApi : apiList) {
        out.print("<li>" + "<a name=\"" + webApi.getApiKey() + "\"></a><b>");

        if (webApi.isDeprecated()) {
            out.print("<font color='red'>[Deprecated]</font> ");
        }

        out.println(webApi.getHttpMethod() + " " + contextName + webApi.getUriPattern() + " - "
                + webApi.getApiName() + "</b><br/> " + webApi.getMethodName());
        out.println("<ul class='httpreq'>");

        out.print("<li>");

        out.print(webApi.getHttpMethod() + " ");

        StringBuilder uriBuilder = new StringBuilder();

        String uri = contextName + webApi.getUriPattern();
        int uriParamIndex = 0;
        int openBrace = uri.indexOf('{');
        int closeBrace = -1;

        if (openBrace < 0) {
            out.print(uri);
            uriBuilder.append(uri);
        }

        while (openBrace > 0) {
            out.print(uri.substring(closeBrace + 1, openBrace));
            uriBuilder.append(uri.substring(closeBrace + 1, openBrace));

            out.print("<input type='text' id='r" + apiIndex + uriParamIndex + "' />");
            uriBuilder.append("\" + $(\"r" + apiIndex + uriParamIndex + "\").value + \"");

            closeBrace = uri.indexOf('}', openBrace);

            assert closeBrace > openBrace;

            openBrace = uri.indexOf('{', closeBrace);
            uriParamIndex++;

            if (openBrace < 0 && uri.length() > (closeBrace + 1)) {
                out.print(uri.substring(closeBrace + 1));
                uriBuilder.append(uri.substring(closeBrace + 1));
                break;
            }
        }

        QueryParam[] queryParams = webApi.getQueryParams();

        if (queryParams != null && queryParams.length > 0) {
            out.print("?");
            uriBuilder.append("\" + \"?");

            int queryIndex = 0;

            for (QueryParam queryParam : queryParams) {
                if (queryIndex > 0) {
                    out.print("&amp;");
                    uriBuilder.append("+ \"&");
                }

                out.print(queryParam.getName());
                uriBuilder.append(queryParam.getName());

                if (queryParam.isRequired()) {
                    out.print("(*)");
                }

                out.print("=<input type='text' id='q" + apiIndex + queryIndex + "' value='"
                        + queryParam.getDevaultValue() + "'/>");

                uriBuilder.append("=\" + encodeURIComponent($(\"q" + apiIndex + queryIndex + "\").value) ");

                queryIndex++;
            }
        } else {
            uriBuilder.append("\"");
        }

        out.println("</li>");

        String headers = null;
        StringBuilder headersBuilder = null;
        String[] matchingHeaders = webApi.getMatchingHeaders();

        // TODO ?? ? ?    textarea  ? ? ?.

        if (matchingHeaders != null) {
            headersBuilder = new StringBuilder();
            headersBuilder.append("{");

            for (String matchingHeader : matchingHeaders) {
                // header  ?  ?? 
                int firstEqualIndex = matchingHeader.indexOf('=');

                if (firstEqualIndex > 0) {
                    String key = matchingHeader.substring(0, firstEqualIndex);
                    String value = matchingHeader.substring(firstEqualIndex + 1);

                    out.println("<li>" + key + ": " + value + "</li>");

                    headersBuilder.append("\"" + key + "\" : \"" + value + "\", ");
                }
            }
        }

        ReqHeader[] reqHeaders = webApi.getRequestHeaders();

        if (reqHeaders != null) {
            if (headersBuilder == null) {
                headersBuilder = new StringBuilder();
                headersBuilder.append("{");
            }

            int headerIndex = 0;
            for (ReqHeader reqHeader : reqHeaders) {
                out.println("<li>" + reqHeader.getName() + ": <input type='text' id='h" + apiIndex + headerIndex
                        + "' value='" + reqHeader.getDevaultValue() + "'/>");
                headersBuilder.append(
                        "\"" + reqHeader.getName() + "\" : $(\"h" + apiIndex + headerIndex + "\").value, ");

                headerIndex++;
            }

            headersBuilder.append("}");
        }

        if (headersBuilder != null) {
            headers = headersBuilder.toString();
        }

        if ("POST".equals(webApi.getHttpMethod()) || "PUT".equals(webApi.getHttpMethod())) {
            out.println("<li><textarea id='c" + apiIndex + "' cols='80' rows='3' ></textarea></li>");
        }

        out.print("<li><input type='button' value='submit' ");
        out.print(" onclick='restful_" + webApi.getHttpMethod().toLowerCase());

        if ("POST".equals(webApi.getHttpMethod()) || "PUT".equals(webApi.getHttpMethod())) {
            out.println("(\"" + uriBuilder.toString() + ", " + headers + ", $(\"c" + apiIndex + "\").value, cb_"
                    + apiIndex + ")' />");
        } else {
            out.println("(\"" + uriBuilder.toString() + ", " + headers + ", cb_" + apiIndex + ")' />");
        }

        out.println("<div style='display: inline' id='s" + apiIndex + "'></div></li>");

        out.println("<li><textarea id='t" + apiIndex
                + "' rows='5' cols='80' style='display:none' readonly></textarea>");
        out.println("<script type='text/javascript'>");
        out.println("function cb_" + apiIndex + "(result) {");
        out.println("   if (result.status >= 200 && result.status < 300) {");
        out.println("      $('s" + apiIndex
                + "').innerHTML = '<span class=\"success\">' + result.status + ' - ' + result.statusText + '</span>';");
        out.println("   } else if (result.status >= 400) {");
        out.println("      $('s" + apiIndex
                + "').innerHTML = '<span class=\"error\">' + result.status + ' - ' + result.statusText + '</span>';");
        out.println("   } else {");
        out.println("      $('s" + apiIndex
                + "').innerHTML = '<span class=\"etc\">' + result.status + ' - ' + result.statusText + '</span>';");
        out.println("   }");
        out.println("   if (result.responseText) {");
        out.println("      $('t" + apiIndex + "').style.display = 'inline';");
        out.println("      var json = JSON.stringify(JSON.parse(result.responseText), null, 3);");
        out.println("      if (navigator.userAgent.match(/Chrome/i))");
        out.println("         $('t" + apiIndex + "').innerHTML = json;"); // innerText   chrome? \n?   
        out.println("      else");
        out.println("         $('t" + apiIndex + "').innerText = json;"); // Chrome ? innerText 
        out.println("   }");
        out.println("}");
        out.println("</script></li>");

        out.println("<li>");
        out.println("<ul class='comment'>");
        out.println("<li>" + webApi.getDescription() + "</li>");
        out.println("</ul>");
        out.println("</li>");

        out.println("</ul>");
        out.println("</li><br/>");

        apiIndex++;
    }

    out.println("</ul>");
    out.println("</body></html>");
    out.flush();
}

From source file:com.thinkberg.webdav.PropFindHandler.java

/**
 * Handle a PROPFIND request./*ww  w . java2s . co m*/
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        logXml(propDoc);

        Element propFindEl = propDoc.getRootElement();
        for (Object propElObject : propFindEl.elements()) {
            Element propEl = (Element) propElObject;
            if (VALID_PROPFIND_TAGS.contains(propEl.getName())) {
                FileObject object = VFSBackend.resolveFile(request.getPathInfo());
                if (object.exists()) {
                    // respond as XML encoded multi status
                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(SC_MULTI_STATUS);

                    Document multiStatusResponse = getMultiStatusResponse(object, propEl, getBaseUrl(request),
                            getDepth(request));
                    logXml(multiStatusResponse);

                    // write the actual response
                    XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
                    writer.write(multiStatusResponse);
                    writer.flush();
                    writer.close();

                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                break;
            }
        }
    } catch (DocumentException e) {
        LOG.error("invalid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.ankang.report.main.Report.java

@RequestMapping(value = "get")
public void get(HttpServletResponse response, String modulName) throws IOException {

    Map<String, Object> methodPools = getReportApplicationContext().getPool(MethodRegister.METHOD_ALIAS_NAME);
    JSONArray json = new JSONArray();

    List<ExecuteMethod> mothods = new ArrayList<ExecuteMethod>();

    // /* w w  w.  j a v  a 2s . c  o m*/
    if (StringUtils.isEmpty(modulName)) {

        for (Map.Entry<String, Object> pool : methodPools.entrySet()) {
            mothods.add(((ExecuteMethod) pool.getValue()));
        }
        json.addAll(mothods);
        // 
    } else if (StringUtils.isNotEmpty(modulName)) {

        mothods.add((ExecuteMethod) methodPools.get(modulName));
        json.addAll(mothods);
    }
    response.setCharacterEncoding("utf-8");
    response.getWriter().print(json);
}