Example usage for javax.servlet ServletResponse getWriter

List of usage examples for javax.servlet ServletResponse getWriter

Introduction

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

Prototype

public PrintWriter getWriter() throws IOException;

Source Link

Document

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

Usage

From source file:ORG.oclc.os.ipUseThrottleFilter.ipUseThrottleFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String longAddr = null, shortAddr, s, transactionKey = null;
    int count;//from www .  ja  va2  s. c o  m
    boolean ignorable = false;

    synchronized (simultaneousRequestsByShortIPAddr) {
        if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) {
            log.error("This system has exceeded the maxTotalSimultaneousRequests limit of "
                    + maxTotalSimultaneousRequests);
            log.error(simultaneousRequestsByShortIPAddr);
            for (String str : simultaneousRequests)
                log.error(str);
            ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE);
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            writer.println("<html><body><h1>Service Temporarily Unavailable</h1>");
            writer.println(
                    "The system is experiencing a severe load and is temporarily unable to accept new requests");
            if (contactInfo != null)
                writer.println("<p>Contact " + contactInfo + " for more information</p>");
            writer.println("</body></html>");
            writer.close();
            return;
        }
        if (addressInHeader != null) {
            @SuppressWarnings("unchecked")
            Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader);
            while (addrs.hasMoreElements()) {
                longAddr = addrs.nextElement();
                if (longAddr == null) {
                    if (++addressInHeaderErrorCount < 10)
                        log.error("Expected a " + addressInHeader + " header but got null");
                    continue;
                }
                if (longAddr.lastIndexOf('.') >= 0)
                    break;
            }
        }
        if (longAddr == null)
            longAddr = request.getRemoteAddr();
        int i = longAddr.lastIndexOf('.');
        if (i < 0) {
            log.error("bogus IP address: '" + longAddr + "'");
            longAddr = "0.0.0.0";
        }
        shortAddr = longAddr.substring(0, i); // trim off 4th number group
        // that lets us spot requests from clusters
        s = equivalentAddresses.get(shortAddr); // map one short addr to another?
        if (s != null)
            shortAddr = s;
        if (ignorableAddresses.contains(shortAddr)) {
            ignorable = true;
        } else {
            Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr);
            if (icount != null)
                count = icount;
            else
                count = 0;

            int maxSimultaneousRequests = (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4;
            if (maxSimultaneousRequests == 0)
                maxSimultaneousRequests = 1;
            if (count >= maxSimultaneousRequests) {
                log.error("IP addr " + shortAddr + ".* has exceeded " + maxSimultaneousRequests
                        + " simultaneous requests!");
                log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests);
                log.error("totalSimultaneousRequests=" + totalSimultaneousRequests);
                for (String str : simultaneousRequests)
                    log.error(str);
                //                ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); // someday
                ((HttpServletResponse) response).setStatus(429); // too many requests
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                writer.println(
                        "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>");
                writer.println("You have exceeded the maximum simultaneous request value of "
                        + maxSimultaneousRequests);
                writer.println("<p>This message and your IP address have been logged and reported</p>");
                if (contactInfo != null)
                    writer.println("<p>Contact " + contactInfo + " for more information</p>");
                writer.println("</body></html>");
                writer.close();
                return;
            }
            simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1);
            icount = totalRequests.get(shortAddr);
            if (icount != null)
                count = icount;
            else
                count = 0;
            totalRequests.put(shortAddr, count + 1);
            totalSimultaneousRequests++;
            transactionKey = new StringBuilder((new Date(System.currentTimeMillis())).toString()).append('|')
                    .append(shortAddr).append('|').append(((HttpServletRequest) request).getQueryString())
                    .toString();
            simultaneousRequests.add(transactionKey);
        }
    }

    try {
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
        chain.doFilter(request, wrapper);
    } finally {
        if (!ignorable)
            synchronized (simultaneousRequestsByShortIPAddr) {
                totalSimultaneousRequests--;
                simultaneousRequests.remove(transactionKey);
                count = simultaneousRequestsByShortIPAddr.get(shortAddr);
                if (count == 1) // prune them from the table
                    simultaneousRequestsByShortIPAddr.remove(shortAddr);
                else
                    simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1);
            }
    }

    Calendar c = new GregorianCalendar();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    if (hour == 0 && nextReportingHour == 24) { // new day!
        // you could reset your daily limits table here
        nextReportingHour = 0;
    }

    if (hour >= nextReportingHour) { // generate the hourly report
        // you could reset your hourly limits table here
        nextReportingHour = hour + 1;

        if (log.isInfoEnabled()) {
            HashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
            List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet());
            List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values());
            TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues);
            Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]);
            int size = sortedArray.length;

            for (int i = 0; i < size; i++)
                map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]);
            Iterator<String> it = map.keySet().iterator();
            String key;
            StringBuilder sb = new StringBuilder("Top 10 users in the last hour");
            for (int i = 0; i < 10 && it.hasNext(); i++) {
                key = it.next();
                sb.append("\n    ").append(key).append(" : ").append(map.get(key));
            }
            log.info(sb);
        }
        totalRequests.clear();
    }
}

From source file:org.qifu.sys.GreenStepBaseFormAuthenticationFilter.java

protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    if (!Constants.getSystem().equals(Constants.getMainSystem())
            && !isAjaxRequest((HttpServletRequest) request)) { // ? core-web
        try {//from www  .ja  v a2s . co  m
            if (this.loginUseCurrentCookieForGeneralPackage(request, response)) { // no need to login-page
                String url = SimpleUtils.getHttpRequestUrl((HttpServletRequest) request);
                logger.warn("URL = " + url);
                WebUtils.issueRedirect(request, response, url);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (isAjaxRequest((HttpServletRequest) request)) {
        response.setCharacterEncoding(Constants.BASE_ENCODING);
        response.setContentType("application/json");
        response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
        return;
    }
    /*
    if (this.isIframeMode((HttpServletRequest)request)) { // iframe ??? login.action ?          
       WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
       return;
    } 
    */
    if (this.isTabPage((HttpServletRequest) request)) { //  dojox.layout.ContentPane ??? login.action ??          
        WebUtils.issueRedirect(request, response, "/pages/system/login_again.jsp");
        return;
    }
    WebUtils.issueRedirect(request, response, getLoginUrl());
}

From source file:com.mobileman.filter.SecurityCheckFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest rq1 = (HttpServletRequest) request;
    String requestURI = rq1.getRequestURI().toLowerCase();
    DataHolder holder = new DataHolder(rq1);
    boolean error = false;
    if (requestURI.contains("/patient/")) {
        //check patient loaded         
        if (!holder.isPatient()) {
            error = true;/* w  w w.ja v a2 s .  c om*/
        }
    } else if (requestURI.contains("/arzt/")) {
        //check doctor loaded
        if (!holder.isDoctor()) {
            error = true;
        }
    } else if (requestURI.contains("/admin/") && !requestURI.contains("/admin/anmeldung")) {
        //check admin loaded
        if (!holder.isAdmin()) {
            error = true;
        }
    }

    ///////////////
    if (requestURI.contains("/public")) {
        //redirect to /behandlung
        StringBuffer sb = rq1.getRequestURL();
        String newUrl = StringUtils.replace(sb.toString(), "/public", "/behandlung");
        java.io.PrintWriter out = response.getWriter();
        response.setContentType("text/html");

        out.println("<html>");
        out.println("<head>");
        out.println("<meta http-equiv=\"refresh\" content=\"0;url=");
        out.print(newUrl);
        out.println("\" />");
        out.println("</head>");
        out.println("<body>");
        out.println("</body>");
        out.println("</html>");

        return;
    }

    if (error) {
        //redirect
        request.getRequestDispatcher("/").forward(request, response);
        return;
    }
    filterChain.doFilter(request, response);
}

From source file:org.codeconsole.web.analytics.AnalyticsFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *///from ww  w . j av a 2  s.  c  o m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpStatusExposingServletResponse httpResponse = new HttpStatusExposingServletResponse(
            (HttpServletResponse) response);

    AnalyticsSession analyticsSession = (AnalyticsSession) httpRequest.getSession()
            .getAttribute(sessionAttributeName);
    if (analyticsSession == null) {
        analyticsSession = new AnalyticsSession(maxHistorySize, httpRequest.getHeader("referer"),
                getIp(httpRequest));
        httpRequest.getSession().setAttribute(sessionAttributeName, analyticsSession);
    }

    String compareUrl = getComparisonUrl((HttpServletRequest) request);
    if (compareUrl.endsWith(analyticsUrl)) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>Analytics Report</title></head><body>");
        if (ServletRequestUtils.getBooleanParameter(request, "send", false)) {
            if (analyticsGateway != null) {
                analyticsGateway.sendAnalytics(analyticsSession);
            } else {
                out.println(
                        "<div>Warning: Can't send report.  No Spring application context specified/configured.</div>");
            }
            out.println("<div>Message: Report Sent!</div>");
        }
        if (ServletRequestUtils.getBooleanParameter(request, "clear", false)) {
            analyticsSession.clear();
            httpRequest.getSession().setAttribute(sessionAttributeName, analyticsSession);
            out.println("<div>Message: History Cleared!</div>");
        }
        out.print(
                "<div><a href=\"?\">Refresh</a> &nbsp; <a href=\"?clear=true\">Clear</a> &nbsp; <a href=\"?send=true\">Send</a> &nbsp; <a href=\"?send=true&clear=true\">Send and Clear</a></div>");
        out.print(analyticsSession.toHtmlString());
        out.println("</body></html>");
        out.close();
    } else {
        String sourceRevision = sourceRevisionResolver == null ? null
                : sourceRevisionResolver.getRevision(httpRequest);

        Map<String, String[]> filteredParamMap = request.getParameterMap();
        if (!excludedUrlPatterns.isEmpty()) {
            filteredParamMap = new HashMap<String, String[]>();
            for (Iterator<Map.Entry<String, String[]>> it = request.getParameterMap().entrySet().iterator(); it
                    .hasNext();) {
                Entry<String, String[]> next = it.next();
                for (Pattern exclude : excludedUrlPatterns) {
                    if (exclude.matcher(compareUrl).matches()) {
                        filteredParamMap.put(next.getKey(), new String[] { "**FILTERED**" });
                    } else {
                        filteredParamMap.put(next.getKey(), next.getValue());
                    }
                }
            }
        }

        @SuppressWarnings("unchecked")
        AnalyticsHttpRequest rq = new AnalyticsHttpRequest(httpRequest.getMethod(),
                httpRequest.getRequestURL().toString(), httpRequest.getQueryString(), filteredParamMap,
                sourceRevision);
        try {
            chain.doFilter(request, httpResponse);
        } catch (IOException e) {
            rq.setException(e);
            throw e;
        } catch (ServletException e) {
            rq.setException(e);
            throw e;
        } catch (RuntimeException e) {
            rq.setException(e);
            throw e;
        } finally {
            rq.setCompletionTime(System.currentTimeMillis());
            rq.setStatus(httpResponse.getStatus());

            boolean ignore = false;
            if (rq.getStatus() == 200 || rq.getStatus() == 304) {
                for (Pattern exclude : excludedUrlPatterns) {
                    if (exclude.matcher(compareUrl).matches()) {
                        ignore = true;
                        break;
                    }
                }
            }
            if (!ignore) {
                analyticsSession.appendHistory(rq);
            }

            Serializable userDetails = userDetailsResolver == null ? null
                    : userDetailsResolver.getUserDetails(httpRequest);
            if (userDetails != null && (analyticsSession.getUserDetails() == null
                    || !analyticsSession.getUserDetails().equals(userDetails))) {
                analyticsSession.setUserDetails(userDetails);
            }

            // in case of clustered sessions, always update the session object to propagate the update.
            if (!httpResponse.isCommitted()) {
                httpRequest.getSession().setAttribute(sessionAttributeName, analyticsSession);
            }
            if (rq.getWrappedException() != null && analyticsGateway != null) {
                analyticsGateway.sendAnalytics(analyticsSession);
            }
        }
    }
}

From source file:org.xmlactions.web.conceal.HttpPager.java

public void processPage(ServletRequest request, ServletResponse response, String page)
        throws ServletException, IOException {
    IExecContext execContext = null;/* www  .  j a  v a  2  s.  c om*/
    if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            execContext = setupExecContext(httpServletRequest, httpServletResponse);

            String pageName = httpServletRequest.getServletPath();

            if (pageName.indexOf("axelconfig") > 0) {
                PrintWriter out = response.getWriter();
                out.print(buildInfo(httpServletRequest, httpServletResponse));
                out.close();
                return;
            }

            if (!pageName.endsWith(".ajax")) {

                String alternatePage = processPrePages(execContext, httpServletRequest, httpServletResponse);
                if ("stop".equals(execContext.getString("pre.page.stop"))) {
                    execContext.put("pre.page.stop", "");
                    response.setContentType("text/html;charset=UTF-8");

                    PrintWriter out = response.getWriter();
                    out.print(alternatePage);
                    out.close();
                }
            }

            log.debug("contextPath:" + httpServletRequest.getContextPath());
            log.debug("URI:" + httpServletRequest.getRequestURI());
            log.debug("root:" + realPath + " page:" + pageName + " wrapperPage:" + wrapperPage);
            log.debug(HttpSessionInfo.sysInfo(httpServletRequest));
            Action action;
            if (pageName.endsWith(".ajax")) {
                page = processAjaxCall(httpServletRequest, httpServletResponse,
                        pageName.substring(1, pageName.length() - ".ajax".length()), execContext);
                page = StrSubstitutor.replace(page, execContext);
            } else if (pageName.endsWith(".bin") || pageName.endsWith(".pdfbin")) {
                String pn = null;
                if (pageName.endsWith(".pdfbin")) {
                    pn = pageName.substring(1, pageName.length() - ".pdfbin".length());
                } else {
                    pn = pageName.substring(1, pageName.length() - ".bin".length());
                }
                page = processAjaxCall(httpServletRequest, httpServletResponse, pn, execContext);

                if (page.startsWith("EX:")) {
                    PrintWriter out = response.getWriter();
                    out.print(page);
                    out.close();
                } else {
                    byte[] image = (byte[]) execContext.get("image");
                    if (pageName.endsWith(".pdfbin")) {
                        String outputPdfFileName = execContext.getString("outputFileName");
                        String ex = serviceJasperPdfRequest(httpServletResponse, image, outputPdfFileName);
                        if (ex != null) {
                            PrintWriter out = response.getWriter();
                            out.print(page);
                            out.close();
                        }
                        return;
                    } else {

                        String responseType = execContext.getString("response_type");
                        if (StringUtils.isEmpty(responseType)) {
                            responseType = "image/png";
                        }
                        response.setContentType(responseType);

                        processPostPages(execContext, httpServletRequest, httpServletResponse);

                        InputStream in = new ByteArrayInputStream(image);
                        OutputStream out = response.getOutputStream();

                        // Copy the contents of the file to the output
                        // stream
                        byte[] buf = new byte[1024];
                        int count = 0;
                        while ((count = in.read(buf)) >= 0) {
                            out.write(buf, 0, count);
                        }
                        in.close();
                        out.close();
                    }
                    return;
                }
            } else {
                if (pageName.startsWith("/:")) {
                    String wrapperPageName = null;
                    int secondColon = pageName.indexOf(':', 2);
                    if (secondColon >= 0) {
                        wrapperPageName = pageName.substring(2, secondColon);
                        execContext.put("inner_page", "/" + pageName.substring(secondColon + 1));
                    } else {
                        if (StringUtils.isEmpty(wrapperPage)) {
                            throw new ServletException("No wrapper page set, why use :");
                        }
                        wrapperPageName = wrapperPage;
                        execContext.put("inner_page", "/" + pageName.substring(2));
                    }
                    // insert the requested page into the wrapper page
                    action = new Action(realPath, wrapperPageName, nameSpace);
                } else {
                    if (StringUtils.isNotEmpty(wrapperPage)) {
                        // we have a base wrapper page defined
                        execContext.put("inner_page", "/" + pageName);
                        action = new Action(realPath, wrapperPage, nameSpace);
                    } else {
                        if (pageName.indexOf("show_axel_config") >= 0) {
                            page = AxelConfig.getAxelConfig(execContext);
                            log.info(page);
                            page = "Config Copied to Log";
                            action = null;
                        } else {
                            // if we don't have a wrapper page we show the requested page
                            action = new Action(realPath, pageName, nameSpace);
                        }
                    }
                }
                if (action != null) {
                    if (StringUtils.isNotEmpty(page)) {
                        page = action.processPage(execContext, page);
                    } else {
                        page = action.processPage(execContext);
                    }
                }
            }

            log.debug("URI:" + httpServletRequest.getRequestURI());
            // log.debug("page:" + page);
            Object object = execContext.get(ActionConst.NO_STR_SUBST);
            // log.debug(ActionConst.NO_STR_SUBST + ":[" + object + "]");
            execContext.put(ActionConst.NO_STR_SUBST, null);

            if (pageName.toLowerCase().endsWith("soap")) {
                response.setContentType(IExecContext.CONTENT_TYPE_XML);

            } else if (pageName.toLowerCase().endsWith("json")) {
                response.setContentType(IExecContext.CONTENT_TYPE_JSON);

            } else {
                response.setContentType(IExecContext.CONTENT_TYPE_HTML);
            }

            processPostPages(execContext, httpServletRequest, httpServletResponse);

            // = = =
            // check if there is a contentType value stored in the execContext.  This could have been set by one of the actions such as an action that wants to return a JSON data.
            // = = =
            String contentType = execContext.getString(IExecContext.CONTENT_TYPE_KEY);
            if (StringUtils.isNotBlank(contentType)) {
                response.setContentType(contentType);
                //               if (contentType.equals(IExecContext.CONTENT_TYPE_JSON) || contentType.equals(IExecContext.CONTENT_TYPE_XML)) {
                //                  if (response instanceof HttpServletResponse) {
                //                     ((HttpServletResponse)response).setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
                //                     ((HttpServletResponse)response).setHeader("Pragma", "no-cache"); // HTTP 1.0
                //                     ((HttpServletResponse)response).setDateHeader("Expires", 0); // Proxies.
                //                  }
                //               }
            }
            execContext.remove("content_type");
            PrintWriter out = response.getWriter();
            out.print(page);
            out.close();

        } catch (Throwable t) {
            // TODO review this, use a better way for reporting the error.
            log.info(t.getMessage(), t);
            throw new ServletException(t);
        } finally {
            if (execContext != null) {
                execContext.saveToPersistence();
                RequestExecContext.remove();
            }
        }
    } else {
        String msg = "Not processing page. Must be HttpServletRequest not [" + request.getClass().getName()
                + "] and HttpServletResponse not [" + response.getClass().getName() + "]";

        log.info(msg);
        throw new ServletException(msg);
    }
}

From source file:co.kuali.coeus.sys.impl.persistence.SchemaSpyFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final UserSession session = getGlobalVariableService().getUserSession() != null
            ? getGlobalVariableService().getUserSession()
            : (UserSession) ((HttpServletRequest) request).getSession()
                    .getAttribute(KRADConstants.USER_SESSION_KEY);
    if (session == null || !getPermissionService().isAuthorizedByTemplate(session.getPrincipalId(),
            KRADConstants.KRAD_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_VIEW,
            Collections.singletonMap(KimConstants.AttributeConstants.VIEW_ID, KIM_SCHEMA_SPY_VIEW_ID),
            Collections.<String, String>emptyMap())) {
        HttpUtils.disableCache((HttpServletResponse) response);
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from  w ww.  j a  v a  2 s  . c o m
    }

    if (!getConfigurationService().getPropertyValueAsBoolean(SCHEMA_SPY_CONFIG_PARAM)) {
        HttpUtils.disableCache((HttpServletResponse) response);
        response.getWriter().write("SchemaSpy has been disabled.");
        return;
    }

    synchronized (initialized) {
        if (REFRESH_TRUE.equals(request.getParameter(REFRESH_PARAM)) && initialized.get()) {
            Executors.newSingleThreadExecutor().execute(refreshSchemaSpy);
        }

        if (!initialized.get()) {
            HttpUtils.disableCache((HttpServletResponse) response);
            response.getWriter().write("Please wait. SchemaSpy is still processing.");
            return;
        }
    }

    chain.doFilter(request, response);
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

protected final ServletContextInitializer sessionServletRegistration() {
    ServletRegistrationBean<ExampleServlet> bean = new ServletRegistrationBean<>(new ExampleServlet() {

        @Override/*from ww w.ja  va  2  s.  co  m*/
        public void service(ServletRequest request, ServletResponse response)
                throws ServletException, IOException {
            HttpSession session = ((HttpServletRequest) request).getSession(true);
            long value = System.currentTimeMillis();
            Object existing = session.getAttribute("boot");
            session.setAttribute("boot", value);
            PrintWriter writer = response.getWriter();
            writer.append(String.valueOf(existing) + ":" + value);
        }

    }, "/session");
    bean.setName("session");
    return bean;
}

From source file:com.evon.injectTemplate.InjectTemplateFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    StringWriter writer = new StringWriter();
    BufferedResponseWrapper wrapper = new BufferedResponseWrapper((HttpServletResponse) response, writer);
    chain.doFilter(request, wrapper);/*  w  w w .j  a  va  2s.c  o  m*/

    String contentType = null;
    String uri = httpRequest.getRequestURI();

    contentType = httpResponse.getContentType();

    if (contentTypes.containsKey(uri)) {
        contentType = contentTypes.get(uri);
    } else if (contentType != null) {
        contentTypes.put(uri, contentType);
    }
    contentType = (contentType == null) ? "none" : contentType;

    String out = writer.getBuffer().toString();

    boolean requestedURIIsTheTemplate = false;

    requestedURIIsTheTemplate = InjectUtils.isTemplate(uri);

    boolean contentTypeIsText = !wrapper.isBinary() && contentType != null && !contentType.equals("none");

    if (requestedURIIsTheTemplate || !contentTypeIsText) {
        if (contentTypeIsText) {
            response.getWriter().print(out);
        }
        return;
    }

    if (!templateLodaded && !templateLodadedStarted) {
        loadTemplates(httpRequest);
    }

    TemplateBean template = getTemplatePathByURI(uri);

    if (template == null) {
        response.getWriter().print(out);
        return;
    }

    String key = null;

    if (template.cache.equals("SESSION")) {
        String cookiesNames = getCookieHashs(httpRequest);
        key = template.path + cookiesNames;
    } else if (template.cache.equals("ON"))

    {
        key = template.path;

    }

    if (!templates.containsKey("/" + template.path)) {
        throw new ServletException("Template [" + template.path + "] not founded");
    }

    boolean needRefresh = template.refreshInSeconds > 0
            && ((System.currentTimeMillis() - template.lastUpdate) / 1000) > template.refreshInSeconds;

    boolean replaceTemplate = template.cache.equals("OFF") || !htmlContents.containsKey(key) || needRefresh;

    /*   pra investigar erro de nulo,    
          boolean notExist = key==null || !htmlContents.containsKey(key);
     * if(!notExist)
          {
             notExist=!notExist;
             //throw new ServletException("content not exist");
          }
       */

    if (replaceTemplate) {
        if (needRefresh) {
            template.lastUpdate = System.currentTimeMillis();
        }

        try {
            loadContentTemplate(template, request.getServerName(), request.getServerPort(),
                    request.getProtocol().contains("HTTPS"), httpRequest);
        } catch (Exception e) {
            throw new ServletException(e.getMessage(), e);
        }
    }

    HTMLInfoBean templateHTML = templates.get("/" + template.path);

    String contentTemplate = htmlContents.get(key).getContent();
    IDocument docOut = HTMLParser.parse(out);

    for (String selector : templateHTML.getSelectors()) {
        IElements elements = docOut.select(selector);
        if (elements.size() == 0) {
            System.out.println("WARNING: Selector [" + selector + "] in template [" + templateHTML.getUri()
                    + "] not founded in [" + httpRequest.getRequestURI() + "]");
            continue;
        }
        if (elements.size() != 1) {
            System.out.println(
                    "WARNING: Selector get many elements. Choosed the first to URI: " + templateHTML.getUri());
        }
        IElement element = elements.get(0);
        String innerHTML = element.html();

        contentTemplate = contentTemplate.replace("<INJECT selector='" + selector + "'/>", innerHTML);
    }

    response.getWriter().print(contentTemplate);
}

From source file:org.apache.myfaces.custom.ajax.api.AjaxDecodePhaseListener.java

private void encodeAjax(UIComponent component, FacesContext context) {
    ServletResponse response = (ServletResponse) context.getExternalContext().getResponse();
    ServletRequest request = (ServletRequest) context.getExternalContext().getRequest();
    UIViewRoot viewRoot = context.getViewRoot();
    Map requestMap = context.getExternalContext().getRequestParameterMap();

    String charset = (String) requestMap.get("charset");

    /* Handle character encoding as of section 2.5.2.2 of JSF 1.1:
     * At the beginning of the render-response phase, the ViewHandler must ensure
     * that the response Locale is set to that of the UIViewRoot, for exampe by
     * calling ServletResponse.setLocale() when running in the servlet environment.
     * Setting the response Locale may affect the response character encoding.
     *//from  w w w  . jav  a  2  s .  c  om
     * Since there is no 'Render Response' phase for AJAX requests, we have to handle
     * this manually.
     */
    response.setLocale(viewRoot.getLocale());

    if (component instanceof DeprecatedAjaxComponent) {
        try {
            String contentType = getContentType("text/xml", charset);
            response.setContentType(contentType);

            StringBuffer buff = new StringBuffer();
            buff.append("<?xml version=\"1.0\"?>\n");
            buff.append("<response>\n");

            PrintWriter out = response.getWriter();
            out.print(buff);

            // imario@apache.org: setup response writer, otherwise the component will fail with an NPE. I dont know why this worked before.
            context.setResponseWriter(
                    new HtmlResponseWriterImpl(out, contentType, request.getCharacterEncoding()));

            if (component instanceof HtmlCommandButtonAjax) {
                buff = new StringBuffer();
                buff.append("<triggerComponent id=\"");
                buff.append(component.getClientId(context));
                buff.append("\" />\n");
                out.print(buff);

                // special treatment for this one, it will try to update the entire form
                // 1. get surrounding form
                //String elname = (String) requestMap.get("elname");
                FormInfo fi = RendererUtils.findNestingForm(component, context);
                UIComponent form = fi.getForm();
                //System.out.println("FOUND FORM: " + form);
                if (form != null) {
                    // special case, add responses from all components in form
                    encodeChildren(form, context, requestMap);
                }
            } else if (component instanceof AjaxComponent) {
                // let component render xml response
                // NOTE: probably don't need an encodeAjax in each component, but leaving it in until that's for sure
                ((AjaxComponent) component).encodeAjax(context);
            } else {
                // just get latest value
                AjaxRendererUtils.encodeAjax(context, component);
            }
            // end response
            out.print("</response>");
            out.flush();
        } catch (IOException e) {
            log.error("Exception while rendering ajax-response", e);
        }
    } else if (component instanceof AjaxComponent) {
        try {
            if (context.getResponseWriter() == null) {
                String contentType = getContentType("text/html", charset);
                response.setContentType(contentType);
                PrintWriter writer = response.getWriter();
                context.setResponseWriter(
                        new HtmlResponseWriterImpl(writer, contentType, response.getCharacterEncoding()));
            }

            ((AjaxComponent) component).encodeAjax(context);
        } catch (IOException e) {
            log.error("Exception while rendering ajax-response", e);
        }
    }

}

From source file:com.netspective.sparx.navigate.NavigationPage.java

/**
 * Handles the generation of the page body using the assigned page skin
 *
 * @param writer writer object to write the output to
 * @param nc     current navigation context
 *//*from   ww w. j a  v  a2s  .  c o  m*/
public void handlePageBody(Writer writer, NavigationContext nc) throws ServletException, IOException {
    // see if dynamic commands should be allowed
    HttpServletRequest request = nc.getHttpRequest();
    String panelEditorCommandSpec = request
            .getParameter(PanelEditorCommand.PANEL_EDITOR_COMMAND_REQUEST_PARAM_NAME);
    if (panelEditorCommandSpec != null && getFlags().flagIsSet(Flags.ALLOW_PANEL_EDITING)) {
        PanelEditorCommand command = new PanelEditorCommand();
        command.setParameters(panelEditorCommandSpec);
        Object panelEditorSource = null;
        // verify that this command is configured to be in this pae
        if (!getFlags().flagIsSet(Flags.VALIDATE_PANEL_EDITOR_IN_PAGE)
                || verifyPanelEditorInPage(nc, command)) {
            try {
                command.handleCommand(writer, nc, false);
            } catch (CommandException e) {
                getLog().error("Command error in body", e);
                throw new ServletException(e);
            }
            return;
        } else {
            getLog().error("Request to execute a panel editor '" + command.getPanelEditorName()
                    + "' that does not exist in page.");
        }
    }

    if (getFlags().flagIsSet(Flags.ALLOW_PAGE_CMD_PARAM)) {
        String commandSpec = request.getParameter(AbstractHttpServletCommand.PAGE_COMMAND_REQUEST_PARAM_NAME);
        if (commandSpec != null) {
            HttpServletCommand command = (HttpServletCommand) Commands.getInstance().getCommand(commandSpec);
            try {
                command.handleCommand(writer, nc, false);
            } catch (CommandException e) {
                getLog().error("Command error in body", e);
                throw new ServletException(e);
            }
            return;
        }
    }

    switch (getBodyType().getValueIndex()) {
    case NavigationPageBodyType.NONE:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName() + " class but has no body.");
        break;

    case NavigationPageBodyType.OVERRIDE:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName()
                + " class and is set as override class but does not override handlePageBody().");
        break;

    case NavigationPageBodyType.CUSTOM_HANDLER:
        for (int i = 0; i < customHandlers.size(); i++)
            ((NavigationPageBodyHandler) customHandlers.get(i)).handleNavigationPageBody(this, writer, nc);
        break;

    case NavigationPageBodyType.COMMAND:
        ValueSource commandExpr = getCommandExpr();
        if (commandExpr != null) {
            String commandText = commandExpr.getTextValue(nc);
            if (commandText != null) {
                try {
                    HttpServletCommand httpCommand = (HttpServletCommand) Commands.getInstance()
                            .getCommand(commandText);
                    httpCommand.handleCommand(writer, nc, false);
                    break;
                } catch (Exception e) {
                    getLog().error("Command error in " + this.getClass().getName(), e);
                    throw new ServletException(e);
                }
            }
        }

        // if we get to here, we don't have an expression or the expression returned null so see if we have static
        // command supplied
        try {
            ((HttpServletCommand) getCommand()).handleCommand(writer, nc, false);
        } catch (CommandException e) {
            getLog().error("Command error in body", e);
            throw new ServletException(e);
        }
        break;

    case NavigationPageBodyType.PANEL:
        getBodyPanel().render(writer, nc, nc.getActiveTheme(), HtmlPanel.RENDERFLAGS_DEFAULT);
        break;

    case NavigationPageBodyType.TEMPLATE:
        getBodyTemplate().process(writer, nc, createDefaultBodyTemplateVars(nc));
        break;

    case NavigationPageBodyType.FORWARD:
        // this should never happen -- forwards should never get to this point but we'll add a sanity check
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName()
                + " class and the body type is set to FORWARD but forwarding should happen before any response is committed.");
        break;

    case NavigationPageBodyType.INCLUDE: {
        String includeUrl = getInclude().getTextValue(nc);
        RequestDispatcher rd = request.getRequestDispatcher(includeUrl);
        ServletResponse response = nc.getResponse();
        if (writer != response.getWriter())
            response = new AlternateOutputDestServletResponse(writer, response);
        request.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc);
        rd.include(request, response);
        request.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT);
    }
        break;

    default:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName() + " but doesn't know how to handle body type "
                + getBodyType().getValueIndex() + ".");
    }
}