Example usage for javax.servlet ServletResponse setCharacterEncoding

List of usage examples for javax.servlet ServletResponse setCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet ServletResponse 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:com.ethercamp.harmony.web.filter.JsonRpcUsageFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if ((request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        final HttpServletResponse httpResponse = (HttpServletResponse) response;

        // don't count alias as it redirects here
        final boolean isJsonRpcUrl = AppConst.JSON_RPC_PATH.equals(httpRequest.getRequestURI());

        if (isJsonRpcUrl && httpRequest.getMethod().equalsIgnoreCase("POST")) {

            try {
                final ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest(
                        httpRequest);/*from   w w  w.  j av a 2s .  c  o  m*/

                final String body = IOUtils.toString(wrappedRequest.getReader());

                wrappedRequest.resetInputStream();

                if (response.getCharacterEncoding() == null) {
                    response.setCharacterEncoding("UTF-8");
                }
                final HttpServletResponseCopier responseCopier = new HttpServletResponseCopier(httpResponse);

                try {
                    chain.doFilter(wrappedRequest, responseCopier);
                    responseCopier.flushBuffer();
                } finally {
                    // read response for stats and log
                    final byte[] copy = responseCopier.getCopy();
                    final String responseText = new String(copy, response.getCharacterEncoding());

                    final JsonNode json = mapper.readTree(body);
                    final JsonNode responseJson = mapper.readTree(responseText);

                    if (json.isArray()) {
                        for (int i = 0; i < json.size(); i++) {
                            notifyInvocation(json.get(i), responseJson.get(i));
                        }
                    } else {
                        notifyInvocation(json, responseJson);
                    }

                    // According to spec, JSON-RPC 2 should return status 200 in case of error
                    if (httpResponse.getStatus() == 500) {
                        httpResponse.setStatus(200);
                    }
                }

            } catch (IOException e) {
                log.error("Error parsing JSON-RPC request", e);
            }
        } else {
            chain.doFilter(request, response);
        }
    } else {
        throw new RuntimeException("JsonRpcUsageFilter supports only HTTP requests.");
    }
}

From source file:de.innovationgate.wgpublisher.filter.WGAFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    WGARequestInformation info = new WGARequestInformation();
    try {//w w w . ja va2 s. co  m
        info.setStartTime(System.currentTimeMillis());
        info.setThread(Thread.currentThread());
        request.setAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME, info);

        _wgaFilterChain.init(request, chain);

        _currentRequests.put(request, info);

        // F000037B2
        if (_core.getCharacterEncoding() != null) {
            request.setCharacterEncoding(_core.getCharacterEncoding());
            // B000041DA
            response.setCharacterEncoding(_core.getCharacterEncoding());
        }

        // add/ delete jvmRoute
        String lbRoute = _core.getClusterService().getLBRoute();
        if (lbRoute != null && !lbRoute.trim().equals("")) {
            WGCookie jvmRouteCookie = new WGCookie(COOKIE_NAME_LBROUTE, lbRoute);
            jvmRouteCookie.setPath("/");
            jvmRouteCookie.setMaxAge(-1);
            jvmRouteCookie.addCookieHeader((HttpServletResponse) response);
        } else {
            Cookie cookie = getCookie((HttpServletRequest) request, COOKIE_NAME_LBROUTE);
            if (cookie != null) {
                WGCookie jvmRouteCookie = WGCookie.from(cookie);
                jvmRouteCookie.setMaxAge(0);
                jvmRouteCookie.addCookieHeader((HttpServletResponse) response);
            }
        }

        RequestWrapper wrappedRequest = createRequestWrapper(response, (HttpServletRequest) request);
        /*
         *  #00005078: don't store original URL. Store converted URL instead.
         *  Will be used in WGA.urlBuilder() and other sources 
         */
        request.setAttribute(REQATTRIB_ORIGINAL_URL, wrappedRequest.getRequestURL().toString());
        request.setAttribute(REQATTRIB_ORIGINAL_URI, wrappedRequest.getRequestURI());
        request.setAttribute(REQATTRIB_ORIGINAL_QUERYSTRING, wrappedRequest.getQueryString());

        FinalCharacterEncodingResponseWrapper wrappedResponse = createResponseWrapper(response, wrappedRequest);

        _holdRequestsLock.readLock().lock();
        try {
            _wgaFilterChain.doFilter(wrappedRequest, wrappedResponse);
        } finally {
            _holdRequestsLock.readLock().unlock();
        }

        info.setStatusCode(wrappedResponse.getStatusCode());
        info.setStatusMessage(wrappedResponse.getStatusMessage());

        AbstractWGAHttpSessionManager sessionManager = _core.getHttpSessionManager();
        if (sessionManager != null) {
            sessionManager.requestFinished(wrappedRequest, wrappedResponse);
        }
    } catch (ServletException e) {
        info.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        info.setStatusMessage(e.getMessage());
        _core.getLog().error("Internal Server Error.", e);
        throw e;
    } finally {
        info.setEndTime(System.currentTimeMillis());
        try {
            WGALoggerWrapper logger = _core.getAccessLogger();
            if (logger != null) {
                logger.logRequest(request);
            }
        } catch (Exception e) {
            _core.getLog().error("Unable to log request.", e);
        }

        WGFactory.getInstance().closeSessions();

        if (!Boolean.TRUE.equals(request.getAttribute(WGPDeployer.REQATTRIB_TML_DEPLOYED))
                && info.getEndTime() > info.getStartTime() + REQUEST_LENGTH_NOTIFICATION_THRESHOLD) {

            String uri = ((HttpServletRequest) request).getRequestURI();
            Problem.Vars vars = Problem.var("reqinfo", info)
                    .var("completeurl", ((HttpServletRequest) request).getRequestURL().toString())
                    .var("host", ((HttpServletRequest) request).getServerName()).var("uri", uri);

            String problemKey = "requestProblem.longRequest#" + uri;

            if (info.getDatabase() != null) {
                _core.getProblemRegistry()
                        .addProblem(Problem.create(new FilterRequestOccasion(),
                                new DatabaseScope(info.getDatabase().getDbReference()), problemKey,
                                ProblemSeverity.LOW, vars));
            } else {
                _core.getProblemRegistry().addProblem(
                        Problem.create(new FilterRequestOccasion(), problemKey, ProblemSeverity.LOW, vars));
            }
        }

        // close opened lucene-resultsets
        LuceneManager luceneManager = _core.getLuceneManager();
        if (luceneManager != null) {
            luceneManager.closeOpenedResultSets();
        }

        _currentRequests.remove(request);
    }
}

From source file:cc.kune.core.server.searcheable.SearchEngineServletFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException, DefaultException {
    if (filterConfig == null) {
        return;//  w  w w .  j  a va 2  s  . c o m
    }

    if (request instanceof HttpServletRequest) {

        final HttpServletRequest httpReq = (HttpServletRequest) request;
        final StringBuffer url = httpReq.getRequestURL();

        final String queryString = httpReq.getQueryString();

        if ((queryString != null) && (queryString.contains(SiteParameters.ESCAPED_FRAGMENT_PARAMETER))) {
            if (!enabled) {
                final HttpServletResponse httpRes = (HttpServletResponse) response;
                httpRes.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Search Engine service disabled temporally");
                return;
            }
            // rewrite the URL back to the original #! version
            // remember to unescape any %XX characters
            final String urlWithEscapedFragment = request
                    .getParameter(SiteParameters.ESCAPED_FRAGMENT_PARAMETER);
            final String newUrl = url.append("?").append(queryString).toString()
                    .replaceFirst(SiteParameters.ESCAPED_FRAGMENT_PARAMETER, SiteParameters.NO_UA_CHECK)
                    .replaceFirst("/ws", "") + "#" + urlWithEscapedFragment;

            LOG.info("New url with hash: " + newUrl);

            final String page = "In development";
            // return the snapshot
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            response.getOutputStream().write(page.getBytes());
        } else {
            try {
                // not an _escaped_fragment_ URL, so move up the chain of
                // servlet (filters)
                chain.doFilter(request, response);
            } catch (final ServletException e) {
                LOG.error("Servlet exception caught: " + e);
            }
        }
    }
}

From source file:io.fabric8.apiman.rest.BearerTokenFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from   w  w  w. j a v  a 2  s. c om*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String authHeader = req.getHeader("Authorization");
    AuthToken.set(null);

    if (authHeader != null && authHeader.toUpperCase().startsWith("BEARER")) {
        //validate token with issuer
        try {
            String authToken = authHeader.substring(7);
            UserInfo userInfo = bearerTokenCache.get(authToken);
            AuthToken.set(authToken);
            AuthPrincipal principal = new AuthPrincipal(userInfo.username);
            principal.addRole("apiuser");
            if (userInfo.isClusterAdmin) {
                principal.addRole("apiadmin");
            }
            request = wrapTheRequest(request, principal);
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            String errMsg = e.getMessage();
            if (e.getMessage().contains("Server returned HTTP response code")) {
                errMsg = "Invalid BearerToken";
            } else {
                errMsg = "Cannot validate BearerToken";
                log.error(errMsg, e);
            }
            sendInvalidTokenResponse((HttpServletResponse) response, errMsg);
        }
    } else if (("/".equals(req.getPathInfo())) || ("/swagger.json".equals(req.getPathInfo()))
            || ("/config.js".equals(req.getPathInfo())) || ("/swagger.yaml".equals(req.getPathInfo()))
            || (req.getPathInfo().startsWith("/downloads/"))) {
        //allow anonymous requests to the root or swagger document
        log.debug("Allowing anonymous access to " + req.getPathInfo());
        chain.doFilter(request, response);
    } else {
        //no bearer token present
        String loginForm = "<html>\n" + "<title>Login into APIMAN with authToken</title>\n" + "<head>\n"
                + "</head>\n" + "<body>\n"
                + "<h1>Provide valid authToken and a link into the Apiman console</h1>\n"
                + "<form action=\"/apimanui/link\" method=\"post\">\n"
                + "    AuthToken: <input type=\"text\" name=\"access_token\" size=\"100\" value=\"oc whoami -t\" /></br>\n"
                + "    Redirect URL: <input type=\"text\" name=\"redirect\"  size=\"100\" value=\"/apimanui/api-manager/\" /></br>\n"
                + "    <input type=\"submit\" value=\"Login\" />    \n" + "</form>\n" + "</body>\n" + "</html>";
        response.setCharacterEncoding("UTF-8");
        response.getWriter().append(loginForm);
        //sendInvalidTokenResponse((HttpServletResponse)response, "No BearerToken");
    }
}

From source file:org.b3log.solo.filter.PageCacheFilter.java

/**
 * Try to write response from cache.//from w  w w. ja  v a  2  s  .  c  om
 *
 * @param request the specified request
 * @param response the specified response
 * @param chain filter chain
 * @throws IOException io exception
 * @throws ServletException servlet exception
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
        final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
        LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
        request.getRequestDispatcher(path).forward(request, response);

        return;
    }

    if (!Latkes.isPageCacheEnabled()) {
        LOGGER.log(Level.FINEST, "Page cache is disabled");
        chain.doFilter(request, response);

        return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
        // Mobile request, bypasses page caching
        chain.doFilter(request, response);

        return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
        pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
        request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject = PageCaches.get(pageCacheKey, httpServletRequest,
            (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
        LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
        chain.doFilter(request, response);

        return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
        // If cached an article that has view password, dispatches the password form
        if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
                && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
            JSONObject article = new JSONObject();

            final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

            article.put(Keys.OBJECT_ID, articleId);
            article.put(Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

            if (articles.needViewPwd(httpServletRequest, article)) {
                article = articleRepository.get(articleId); // Loads the article entity

                final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                try {
                    httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd"
                            + articles.buildArticleViewPwdFormParameters(article));
                    return;
                } catch (final Exception e) {
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }

    try {
        LOGGER.log(Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        final PrintWriter writer = response.getWriter();
        String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
        final String topBarHTML = TopBars.getTopBarHTML((HttpServletRequest) request,
                (HttpServletResponse) response);
        cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

        final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
        LOGGER.log(Level.FINEST, "Cached value[key={0}, type={1}, title={2}]",
                new Object[] { pageCacheKey, cachedType, cachedTitle });

        statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

        final long endimeMillis = System.currentTimeMillis();
        final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
        final String msg = String.format("<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
                endimeMillis - startTimeMillis, dateString);
        LOGGER.finer(msg);
        cachedPageContent += Strings.LINE_SEPARATOR + msg;
        writer.write(cachedPageContent);
        writer.flush();
        writer.close();
    } catch (final JSONException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    } catch (final ServiceException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        chain.doFilter(request, response);
    }
}

From source file:org.apache.unomi.web.ContextServlet.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    final Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }//from   w w  w  .  j a  v a 2  s.  c o  m
    // first we must retrieve the context for the current visitor, and build a Javascript object to attach to the
    // script output.
    String profileId;

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String httpMethod = httpServletRequest.getMethod();
    //        logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest));

    // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors
    HttpUtils.setupCORSHeaders(httpServletRequest, response);

    if ("options".equals(httpMethod.toLowerCase())) {
        response.flushBuffer();
        return;
    }

    Profile profile = null;

    String cookieProfileId = null;
    Cookie[] cookies = httpServletRequest.getCookies();
    for (Cookie cookie : cookies) {
        if (profileIdCookieName.equals(cookie.getName())) {
            cookieProfileId = cookie.getValue();
        }
    }

    Session session = null;

    String personaId = request.getParameter("personaId");
    if (personaId != null) {
        PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId);
        if (personaWithSessions == null) {
            logger.error("Couldn't find persona with id=" + personaId);
            profile = null;
        } else {
            profile = personaWithSessions.getPersona();
            session = personaWithSessions.getLastSession();
        }
    }

    String sessionId = request.getParameter("sessionId");

    if (cookieProfileId == null && sessionId == null && personaId == null) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    boolean profileCreated = false;

    ContextRequest contextRequest = null;
    String scope = null;
    String stringPayload = HttpUtils.getPayload(httpServletRequest);
    if (stringPayload != null) {
        ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
        JsonFactory factory = mapper.getFactory();
        try {
            contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class);
        } catch (Exception e) {
            logger.error("Cannot read payload " + stringPayload, e);
            return;
        }
        scope = contextRequest.getSource().getScope();
    }

    int changes = EventService.NO_CHANGE;

    if (profile == null) {
        if (sessionId != null) {
            session = profileService.loadSession(sessionId, timestamp);
            if (session != null) {
                profileId = session.getProfileId();
                profile = profileService.load(profileId);
                profile = checkMergedProfile(response, profile, session);
            }
        }
        if (profile == null) {
            // profile not stored in session
            if (cookieProfileId == null) {
                // no profileId cookie was found, we generate a new one and create the profile in the profile service
                profile = createNewProfile(null, response, timestamp);
                profileCreated = true;
            } else {
                profile = profileService.load(cookieProfileId);
                if (profile == null) {
                    // this can happen if we have an old cookie but have reset the server,
                    // or if we merged the profiles and somehow this cookie didn't get updated.
                    profile = createNewProfile(null, response, timestamp);
                    profileCreated = true;
                    HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
                } else {
                    profile = checkMergedProfile(response, profile, session);
                }
            }
        } else if ((cookieProfileId == null || !cookieProfileId.equals(profile.getItemId()))
                && !profile.isAnonymousProfile()) {
            // profile if stored in session but not in cookie
            HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain);
        }
        // associate profile with session
        if (sessionId != null && session == null) {
            session = new Session(sessionId, profile, timestamp, scope);
            changes |= EventService.SESSION_UPDATED;
            Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp);

            event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            changes |= eventService.send(event);
        }
    }

    if (profileCreated) {
        changes |= EventService.PROFILE_UPDATED;

        Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp);
        profileUpdated.setPersistent(false);
        profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
        profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);

        logger.debug("Received event {} for profile={} {} target={} timestamp={}",
                profileUpdated.getEventType(), profile.getItemId(),
                session != null ? " session=" + session.getItemId() : "", profileUpdated.getTarget(),
                timestamp);
        changes |= eventService.send(profileUpdated);
    }

    ContextResponse data = new ContextResponse();
    data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : profile.getItemId());

    if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) {
        profile = privacyService.getAnonymousProfile();
        session.setProfile(profile);
        changes = EventService.SESSION_UPDATED;
    }

    if (contextRequest != null) {
        changes |= handleRequest(contextRequest, profile, session, data, request, response, timestamp);
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED && profile != null) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) {
        profileService.saveSession(session);
    }

    String extension = httpServletRequest.getRequestURI()
            .substring(httpServletRequest.getRequestURI().lastIndexOf(".") + 1);
    boolean noScript = "json".equals(extension);
    String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(data);
    Writer responseWriter;
    if (noScript) {
        response.setCharacterEncoding("UTF-8");
        responseWriter = response.getWriter();
        response.setContentType("application/json");
        IOUtils.write(contextAsJSONString, responseWriter);
    } else {
        responseWriter = response.getWriter();
        responseWriter.append("window.digitalData = window.digitalData || {};\n").append("var cxs = ")
                .append(contextAsJSONString).append(";\n");

        // now we copy the base script source code
        InputStream baseScriptStream = getServletContext().getResourceAsStream(
                profile instanceof Persona ? IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION);
        IOUtils.copy(baseScriptStream, responseWriter);
    }

    responseWriter.flush();
}