Example usage for javax.servlet.http HttpServletResponse getCharacterEncoding

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

Introduction

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

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding (MIME charset) used for the body sent in this response.

Usage

From source file:net.nan21.dnet.core.web.controller.data.AbstractDsReadController.java

@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_PRINT)
@ResponseBody/*  w  ww  .  j a  va 2  s .c  om*/
public String print(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString,
        @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_INFO, required = true, defaultValue = "") String exportInfoString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.DS_ACTION_PRINT });
        }

        if (logger.isDebugEnabled()) {

            logger.debug("  --> request-filter: {} ", new String[] { filterString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
            logger.debug("  --> request-result-range: {} ",
                    new String[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_EXPORT, null);

        IDsService<M, F, P> service = this.findDsService(resourceName);

        IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json");

        F filter = marshaller.readFilterFromString(filterString);
        P params = marshaller.readParamsFromString(paramString);

        ExportInfo exportInfo = marshaller.readDataFromString(exportInfoString, ExportInfo.class);
        exportInfo.prepare(service.getModelClass());

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize)
                .addFilter(filter).addParams(params);

        if (orderBy != null && !orderBy.equals("")) {
            List<SortToken> sortTokens = marshaller.readListFromString(orderBy, SortToken.class);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        if (filterRulesString != null && !filterRulesString.equals("")) {
            List<FilterRule> filterRules = marshaller.readListFromString(filterRulesString, FilterRule.class);
            builder.addFilterRules(filterRules);
        }

        List<M> data = service.find(builder);

        File _tplDir = null;
        String _tplName = null;

        String _tpl = this.getSettings().getParam(SysParams_Core.CORE_PRINT_HTML_TPL);

        if (_tpl == null || "".equals(_tpl)) {
            _tpl = "print-template/print.ftl";
        }

        _tpl = Session.user.get().getWorkspace().getWorkspacePath() + "/" + _tpl;
        File _tplFile = new File(_tpl);

        _tplDir = _tplFile.getParentFile();
        _tplName = _tplFile.getName();

        if (!_tplFile.exists()) {

            // _tplDir = _tplFile.getParentFile();

            if (!_tplDir.exists()) {
                _tplDir.mkdirs();
            }

            Resource resource = new ClassPathResource("WEB-INF/freemarker/print.ftl");
            FileUtils.copyFile(resource.getFile(), _tplFile);

        }

        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
        cfg.setDirectoryForTemplateLoading(_tplDir);

        Map<String, Object> root = new HashMap<String, Object>();

        root.put("printer", new ModelPrinter());
        root.put("data", data);
        root.put("filter", filter);
        root.put("params", params);
        root.put("client", Session.user.get().getClient());

        Map<String, Object> reportConfig = new HashMap<String, Object>();
        reportConfig.put("logo", this.getSettings().getParam(SysParams_Core.CORE_LOGO_URL_REPORT));
        reportConfig.put("runBy", Session.user.get().getName());
        reportConfig.put("runAt", new Date());
        reportConfig.put("title", exportInfo.getTitle());
        reportConfig.put("orientation", exportInfo.getLayout());
        reportConfig.put("columns", exportInfo.getColumns());
        reportConfig.put("filter", exportInfo.getFilter());

        root.put("cfg", reportConfig);

        if (dataFormat.equals(Constants.DATA_FORMAT_HTML)) {
            response.setContentType("text/html; charset=UTF-8");
        }

        Template temp = cfg.getTemplate(_tplName);
        Writer out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding());
        temp.process(root, out);
        out.flush();
        return null;
    } catch (Exception e) {

        e.printStackTrace();
        return null;
        // return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:seava.j4e.web.controller.data.AbstractDsReadController.java

@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_PRINT)
@ResponseBody//from   w ww . j ava  2  s. c  o m
public String print(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString,
        @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_DOWNLOAD, required = false, defaultValue = "true") Boolean exportDownload,
        @RequestParam(value = Constants.REQUEST_PARAM_EXPORT_INFO, required = true, defaultValue = "") String exportInfoString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    // return null;
    try {

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new Object[] { resourceName, dataFormat, Constants.DS_ACTION_PRINT });
        }

        if (logger.isDebugEnabled()) {

            logger.debug("  --> request-filter: {} ", new Object[] { filterString });
            logger.debug("  --> request-params: {} ", new Object[] { paramString });
            logger.debug("  --> request-result-range: {} ",
                    new Object[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_EXPORT, null);

        IDsService<M, F, P> service = this.findDsService(resourceName);

        IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json");

        F filter = marshaller.readFilterFromString(filterString);
        P params = marshaller.readParamsFromString(paramString);

        ExportInfo exportInfo = marshaller.readDataFromString(exportInfoString, ExportInfo.class);
        exportInfo.prepare(service.getModelClass());

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize)
                .addFilter(filter).addParams(params);

        if (orderBy != null && !orderBy.equals("")) {
            List<ISortToken> sortTokens = marshaller.readSortTokens(orderBy);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        if (filterRulesString != null && !filterRulesString.equals("")) {
            List<IFilterRule> filterRules = marshaller.readFilterRules(filterRulesString);
            builder.addFilterRules(filterRules);
        }

        List<M> data = service.find(builder);

        File _tplDir = null;
        String _tplName = null;

        String _tpl = this.getSettings().getParam(SysParam.CORE_PRINT_HTML_TPL.name());

        if (_tpl == null || "".equals(_tpl)) {
            _tpl = "print-template/print.ftl";
        }

        _tpl = Session.user.get().getWorkspace().getWorkspacePath() + "/" + _tpl;
        File _tplFile = new File(_tpl);

        _tplDir = _tplFile.getParentFile();
        _tplName = _tplFile.getName();

        if (!_tplFile.exists()) {

            // _tplDir = _tplFile.getParentFile();

            if (!_tplDir.exists()) {
                _tplDir.mkdirs();
            }

            Resource resource = new ClassPathResource("seava/j4e/web/ftl/data/print.ftl");
            FileUtils.copyInputStreamToFile(resource.getInputStream(), _tplFile);
        }

        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
        cfg.setDirectoryForTemplateLoading(_tplDir);

        Map<String, Object> root = new HashMap<String, Object>();

        root.put("printer", new ModelPrinter());
        root.put("data", data);
        root.put("filter", filter);
        root.put("params", params);
        root.put("client", Session.user.get().getClient());

        Map<String, Object> reportConfig = new HashMap<String, Object>();
        reportConfig.put("logo", this.getSettings().getParam(SysParam.CORE_LOGO_URL_REPORT.name()));
        reportConfig.put("runBy", Session.user.get().getName());
        reportConfig.put("runAt", new Date());
        reportConfig.put("title", exportInfo.getTitle());
        reportConfig.put("orientation", exportInfo.getLayout());
        reportConfig.put("columns", exportInfo.getColumns());
        reportConfig.put("filter", exportInfo.getFilter());

        root.put("cfg", reportConfig);

        if (dataFormat.equals(Constants.DATA_FORMAT_HTML)) {
            response.setContentType("text/html; charset=UTF-8");
        }

        Template temp = cfg.getTemplate(_tplName);

        if (exportDownload) {
            Writer out = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding());
            temp.process(root, out);
            out.flush();
            return null;
        } else {
            String path = Session.user.get().getWorkspace().getTempPath();
            String fileName = UUID.randomUUID().toString();
            File outFile = new File(path + "/" + fileName + "." + dataFormat);

            Writer out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
            temp.process(root, out);
            out.flush();
            out.close();
            // just send the file name
            return "{success:true, file:\"" + outFile.getName() + "\"}";
        }

    } catch (Exception e) {
        e.printStackTrace();
        this.handleException(e, response);
        return null;
    } finally {
        this.finishRequest();
    }

}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri,
        String servletPath, String proxyPath) throws ServletException, IOException {
    //System.out.println("LOAD "+uri); 
    //System.out.println("LOAD "+proxyPath);

    if ("CONNECT".equalsIgnoreCase(request.getMethod())) {
        handleConnect(request, response);

    } else {/*w  w  w  . j  a  va2 s  .  c o m*/
        URL url = new URL(uri);

        URLConnection connection = url.openConnection();
        connection.setAllowUserInteraction(false);

        // Set method
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
            http.setInstanceFollowRedirects(false);
        }

        // check connection header
        String connectionHdr = request.getHeader("Connection");
        if (connectionHdr != null) {
            connectionHdr = connectionHdr.toLowerCase();
            if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
                connectionHdr = null;
        }

        // copy headers
        boolean xForwardedFor = false;
        boolean hasContent = false;
        Enumeration enm = request.getHeaderNames();
        while (enm.hasMoreElements()) {
            // TODO could be better than this!
            String hdr = (String) enm.nextElement();
            String lhdr = hdr.toLowerCase();

            if (_DontProxyHeaders.contains(lhdr))
                continue;
            if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
                continue;

            if ("content-type".equals(lhdr))
                hasContent = true;

            Enumeration vals = request.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val != null) {
                    connection.addRequestProperty(hdr, val);
                    xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
                }
            }
        }

        // Proxy headers
        connection.setRequestProperty("Via", "1.1 (jetty)");
        if (!xForwardedFor)
            connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr());

        // a little bit of cache control
        String cache_control = request.getHeader("Cache-Control");
        if (cache_control != null
                && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
            connection.setUseCaches(false);

        // customize Connection

        try {
            connection.setDoInput(true);

            // do input thang!
            InputStream in = request.getInputStream();
            if (hasContent) {
                connection.setDoOutput(true);
                IOUtils.copy(in, connection.getOutputStream());
            }

            // Connect
            connection.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream proxy_in = null;

        // handler status codes etc.
        int code = 500;
        if (http != null) {
            proxy_in = http.getErrorStream();

            code = http.getResponseCode();
            response.setStatus(code, http.getResponseMessage());
        }

        if (proxy_in == null) {
            try {
                proxy_in = connection.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
                proxy_in = http.getErrorStream();
            }
        }

        // clear response defaults.
        response.setHeader("Date", null);
        response.setHeader("Server", null);

        // set response headers
        int h = 0;
        String hdr = connection.getHeaderFieldKey(h);
        String val = connection.getHeaderField(h);
        while (hdr != null || val != null) {
            String lhdr = hdr != null ? hdr.toLowerCase() : null;
            if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) {
                if (hdr.equalsIgnoreCase("Location")) {
                    val = Rewriter.translateCleanUrl(val, servletPath, proxyPath);
                }
                response.addHeader(hdr, val);

            }

            h++;
            hdr = connection.getHeaderFieldKey(h);
            val = connection.getHeaderField(h);

        }

        boolean isGzipped = connection.getContentEncoding() != null
                && connection.getContentEncoding().contains("gzip");
        response.addHeader("Via", "1.1 (jetty)");
        // boolean process = connection.getContentType() == null
        // || connection.getContentType().isEmpty()
        // || connection.getContentType().contains("html");
        boolean process = connection.getContentType() != null && connection.getContentType().contains("text");
        if (proxy_in != null) {
            if (!process) {
                IOUtils.copy(proxy_in, response.getOutputStream());
                proxy_in.close();
            } else {
                InputStream in;
                if (isGzipped && proxy_in != null && proxy_in.available() > 0) {
                    in = new GZIPInputStream(proxy_in);
                } else {
                    in = proxy_in;
                }
                ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
                IOUtils.copy(in, byteArrOS);
                in.close();
                if (in != proxy_in)
                    proxy_in.close();
                String charset = response.getCharacterEncoding();
                if (charset == null || charset.isEmpty()) {
                    charset = "ISO-8859-1";
                }
                String originalContent = new String(byteArrOS.toByteArray(), charset);
                byteArrOS.close();
                return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped);
            }
        }

    }
    return null;
}