Example usage for javax.servlet.http HttpServletRequest getLocales

List of usage examples for javax.servlet.http HttpServletRequest getLocales

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getLocales.

Prototype

public Enumeration<Locale> getLocales();

Source Link

Document

Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header.

Usage

From source file:org.infoscoop.web.MenuConfServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String reqUri = req.getRequestURI();
    String srvPath = req.getServletPath();
    String menuType = reqUri.substring(reqUri.lastIndexOf(srvPath) + (srvPath.length() + 1), reqUri.length());

    String ignoreAccessControlHeader = req.getHeader("Ignore-Access-Control");
    boolean ignoreAccessControl = false;
    try {/*  ww w  . j  ava 2 s. com*/
        PortalAdminsService service = (PortalAdminsService) SpringUtil.getBean("PortalAdminsService");
        ignoreAccessControl = Boolean.valueOf(ignoreAccessControlHeader).booleanValue()
                && (service.isPermitted("menu") || service.isPermitted("defaultPanel"));
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

    SiteAggregationMenuService service = (SiteAggregationMenuService) SpringUtil
            .getBean("siteAggregationMenuService");
    try {
        res.setHeader("Content-Type", "text/xml; charset=UTF-8");
        OutputStream w = res.getOutputStream();
        String resStr = service.getMenuTreeXml(menuType, ignoreAccessControl);
        byte[] resBytes = MakeMenuFilter.process(new ByteArrayInputStream(resStr.getBytes("UTF-8")), menuType,
                menuType, (Locale) req.getLocales().nextElement(), false);
        w.write(resBytes);
        w.flush();
        w.close();
    } catch (Exception e) {
        log.error(e);
        res.sendError(500, e.getMessage());
    }
}

From source file:org.infoscoop.web.MultiRssServlet.java

private void mergeRssAnd2JSON(HttpServletRequest request, HttpServletResponse response, String uid,
        String widgetId, int pageSize, NodeList urlList) throws Exception {

    try {/*from w w w.ja  v a 2s .c om*/
        RssJsonResultBuilder resultBuilder = new SortedRssJsonResultBuilder(pageSize);

        String dateTimeFormat = request.getHeader("X-IS-DATETIMEFORMAT");
        if (dateTimeFormat != null) {
            dateTimeFormat = URLDecoder.decode(dateTimeFormat, "UTF-8");
        }
        String freshTime = request.getHeader("X-IS-FRESHTIME");
        String maxCountString = request.getHeader("X-IS-RSSMAXCOUNT");
        int maxCount = 1000;
        if (maxCountString != null) {
            try {
                int paramMaxCount = Integer.parseInt(maxCountString);
                if (paramMaxCount >= 0) {
                    maxCount = paramMaxCount;
                }
            } catch (NumberFormatException e) {
                log.warn("rssmaxcount \"" + maxCountString + "\" isn't integer value.");
            }
        }

        // Norrowing
        String titleFilter = request.getHeader("X-IS-TITLEFILTER");
        if (titleFilter != null)
            titleFilter = URLDecoder.decode(titleFilter, "UTF-8");
        String creatorFilter = request.getHeader("X-IS-CREATORFILTER");
        if (creatorFilter != null)
            creatorFilter = URLDecoder.decode(creatorFilter, "UTF-8");
        String categoryFilter = request.getHeader("X-IS-CATEGORYFILTER");
        if (categoryFilter != null)
            categoryFilter = URLDecoder.decode(categoryFilter, "UTF-8");

        int DEFAULT_TIMEOUT = 15 * 1000;

        boolean modified = false;
        Map cacheHeaders = new HashMap();
        Map errorMap = new HashMap();
        List siteCacheHeaders = new ArrayList();
        for (int i = 0; i < urlList.getLength(); i++) {
            Element rssEl = (Element) urlList.item(i);
            String url = rssEl.getAttribute("url");

            ProxyRequest proxyRequest = new ProxyRequest(url, "NoOperation");
            proxyRequest.setLocales(request.getLocales());
            proxyRequest.setPortalUid(uid);

            int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
            proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);
            //proxyRequest.setTimeout(timeout);

            proxyRequest.addIgnoreHeader("user-agent");
            proxyRequest.addIgnoreHeader("X-IS-DATETIMEFORMAT");
            proxyRequest.addIgnoreHeader("X-IS-FRESHTIME");
            proxyRequest.addIgnoreHeader("X-IS-REFRESH");
            proxyRequest.addIgnoreHeader("X-IS-RSSMAXCOUNT");
            proxyRequest.addIgnoreHeader("X-IS-PAGESIZE");

            Enumeration headers = request.getHeaderNames();
            while (headers.hasMoreElements()) {
                String headerName = (String) headers.nextElement();
                proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
            }

            NodeList rssChildNodes = rssEl.getElementsByTagName("header");
            for (int j = 0; j < rssChildNodes.getLength(); j++) {
                Element header = (Element) rssChildNodes.item(j);
                if (header.getFirstChild() != null) {
                    String name = header.getAttribute("name");
                    String value = header.getFirstChild().getNodeValue();
                    if (name == null || name.trim().length() == 0 || value == null
                            || value.trim().length() == 0)
                        continue;

                    proxyRequest.putRequestHeader(name, value);
                }
            }

            int statusCode = 0;
            String methodType = rssEl.getAttribute("method");
            try {
                if ("post".equals(methodType)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } catch (SocketTimeoutException ex) {
                log.error("url: [" + url + "] socket timeout.", ex);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_TIMEOUT));
            } catch (ConnectTimeoutException ex) {
                log.error("url: [" + url + "] connection timeout.", ex);
                errorMap.put(url, new Integer(500));
            } catch (SocketException ex) {
                log.error("url: [" + url + "] socket error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (IOException ex) {
                log.error("url: [" + url + "] I/O error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (Exception ex) {
                log.error("url: [" + url + "]" + ex.getMessage(), ex);
                errorMap.put(url, new Integer(500));
            }

            BufferedInputStream bis = null;
            if (errorMap.containsKey(url)) {
                // nothing

            } else if (statusCode == 204) {
                log.warn("url:[" + url + "] is no content #" + statusCode);
                modified = true;
            } else if (statusCode == 304) {
                log.warn("url:[" + url + "] is not modified #" + statusCode);
            } else if (statusCode != 200) {
                log.error("url:[" + url + "] had error status code #" + statusCode);
                errorMap.put(url, new Integer(statusCode));
            } else {
                log.info("url:[" + url + "] is succed #" + statusCode);

                try {
                    modified = true;

                    bis = new BufferedInputStream(proxyRequest.getResponseBody());

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[10240];
                    int c;
                    while ((c = bis.read(buf)) != -1) {
                        baos.write(buf, 0, c);
                        baos.flush();
                    }
                    bis.close();

                    byte[] data = baos.toByteArray();
                    baos.close();

                    //RssCacheDAO.newInstance().insertCache(uid, widgetId+url, -1,data );

                    Map responseHeaders = proxyRequest.getResponseHeaders();
                    String lastModifiedName = "Last-Modified".toLowerCase();
                    if (responseHeaders.containsKey(lastModifiedName)) {
                        siteCacheHeaders.add(lastModifiedName);
                        siteCacheHeaders.add(responseHeaders.get(lastModifiedName));
                    }

                    String etagName = "ETag".toLowerCase();
                    if (responseHeaders.containsKey(etagName)) {
                        siteCacheHeaders.add(etagName);
                        siteCacheHeaders.add(responseHeaders.get(etagName));
                    }

                    if (siteCacheHeaders.size() > 0) {
                        cacheHeaders.put(url, siteCacheHeaders.toArray());
                        siteCacheHeaders.clear();
                    }

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                } catch (IOException ex) {
                    log.error("rss reading " + url + " is failed.", ex);
                    cacheHeaders.remove(url);
                    errorMap.put(url, new Integer(500));

                    bis.close();
                    bis = null;
                }
            }

            if (bis == null)
                continue;

            RssHandler handler;

            boolean isAtom = RssFilter.isAtom(bis);

            XMLFilter.skipEmptyLine(bis);
            if (isAtom) {
                handler = new AtomHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            } else {
                handler = new RssHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            }

            try {
                XMLReader reader = factory.newSAXParser().getXMLReader();
                reader.setEntityResolver(NoOpEntityResolver.getInstance());
                reader.setContentHandler(handler);
                reader.parse(new InputSource(bis));
            } catch (SAXException e) {
                log.info("Parsing rss " + url + " is failed.", e);
                cacheHeaders.remove(url);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_CONTENT_PARSE_ERROR));
            }
        }

        if (!modified && errorMap.isEmpty()) {
            log.warn("multi rss is not modified.");
            response.setStatus(304);

            return;
        } else {
            try {
                long freshTimeLong = new Date().getTime();
                if (freshTime != null)
                    freshTimeLong = Long.parseLong(freshTime.trim());
                setOldData(resultBuilder, uid, widgetId, freshTimeLong, titleFilter, creatorFilter,
                        categoryFilter);

            } catch (NumberFormatException e) {
                log.error("", e);
            }

            //}

            int pageCount = resultBuilder.getPageCount();
            // We create the result cash by all means.
            //if( pageCount > 1 ) {
            for (int pageNum = 0; pageNum < pageCount; pageNum++) {
                RssCacheDAO.newInstance().insertCache(uid, widgetId, pageNum, resultBuilder.getResult(pageNum));
            }
            //}
        }

        response.addHeader("Content-Type", "text/plain; charset=UTF-8");

        String result = resultBuilder.getResult();

        if (!errorMap.isEmpty()) {
            JSONObject errors = new JSONObject(errorMap);
            result = "{errors:" + errors.toString() + "," + result.substring(result.indexOf("{") + 1);
        }
        if (!cacheHeaders.isEmpty()) {
            StringBuffer cacheHeadersBuf = new StringBuffer();
            cacheHeadersBuf.append("cacheHeaders : {");
            for (Iterator keys = cacheHeaders.keySet().iterator(); keys.hasNext();) {
                String url = (String) keys.next();
                Object[] headers = (Object[]) cacheHeaders.get(url);

                cacheHeadersBuf.append("\"").append(url).append("\" : {");
                for (int i = 0; i < headers.length; i += 2) {
                    cacheHeadersBuf.append("\"").append(headers[i]).append("\"");
                    cacheHeadersBuf.append(" : '").append(headers[i + 1]).append("'");
                    if (i + 2 < headers.length)
                        cacheHeadersBuf.append(",");
                }
                cacheHeadersBuf.append("}");
                if (keys.hasNext())
                    cacheHeadersBuf.append(",");
            }
            cacheHeadersBuf.append("}");

            result = "{" + cacheHeadersBuf.toString() + "," + result.substring(result.indexOf("{") + 1);
        }

        response.setContentLength(result.getBytes("UTF-8").length);

        OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        try {
            out.write(result);

            out.flush();
        } catch (SocketException ex) {
            // ignore client abort exception
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (Exception e) {
        log.error("unexpected error occurred.", e);
        response.sendError(500, e.getMessage());
    }

}

From source file:org.infoscoop.web.ProxyServlet.java

public void doProcess(HttpServletRequest request, HttpServletResponse response, int methodType)
        throws ServletException, IOException {
    int statusCode = 0;
    String url = request.getParameter("url");
    ProxyRequest proxyRequest = null;//from   ww  w .  j  ava 2 s .c  om

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {

        String filterType = request.getParameter("filter");

        proxyRequest = new ProxyRequest(url, filterType);

        String filterEncoding = request.getParameter("filterEncoding");
        proxyRequest.setFilterEncoding(filterEncoding);

        proxyRequest.setLocales(request.getLocales());
        proxyRequest.setPortalUid((String) request.getSession().getAttribute("Uid"));

        int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
        proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);

        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
        }

        //The certification for iframe
        String authTypeParam = request.getParameter("authType");
        if (authTypeParam != null && !"".equals(authTypeParam)) {
            proxyRequest.putRequestHeader("authType", authTypeParam);
            proxyRequest.putRequestHeader("authuserid", request.getParameter("authuserid"));
            proxyRequest.putRequestHeader("authpassword", request.getParameter("authpassword"));
        }

        for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
            String name = (String) names.nextElement();

            proxyRequest.setFilterParameter(name, request.getParameter(name));
        }

        try {
            String otherMethod = request.getHeader("MSDPortal-method");
            if (otherMethod == null)
                otherMethod = request.getParameter("method");

            if (methodType == METHOD_GET) {
                if (otherMethod != null && otherMethod.equalsIgnoreCase("delete")) {
                    statusCode = proxyRequest.executeDelete();
                } else if ("postCredential".equals(authTypeParam)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } else {
                if ("get".equalsIgnoreCase(otherMethod)) {
                    statusCode = proxyRequest.executeGet();
                } else {
                    proxyRequest.setReqeustBody(request.getInputStream());
                    if (otherMethod == null || "post".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePost();
                    } else if ("put".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePut();
                    } else if ("report".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executeReport();
                        if (statusCode == 207)
                            statusCode = 200;
                    }
                }
            }

        } catch (SocketTimeoutException ex) {
            // When the status code was 408, Firefox did not move well.
            // ABecause the cords such as 10408 are converted into 500 by Apache-GlassFish cooperation, we set it in a header.Apache-GlassFish.
            response.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        } catch (ConnectTimeoutException ex) {
            // In the case of connection-timeout,  we don't try it again.
            //response.setHeader(HttpStatusCode.HEADER_NAME,
            //      HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        }

        Map<String, List<String>> responseHeaders = proxyRequest.getResponseHeaders();
        if (statusCode == 401) {

            String wwwAuthHeader = proxyRequest.getResponseHeader("WWW-Authenticate");
            if (wwwAuthHeader == null) {
                statusCode = 403;
            } else if (wwwAuthHeader.toLowerCase().startsWith("basic")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "basic");
            } else if (wwwAuthHeader.toLowerCase().startsWith("ntlm")
                    || wwwAuthHeader.toLowerCase().startsWith("negotiate")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "ntlm");
            }
        }
        response.setStatus(statusCode);

        if (log.isInfoEnabled()) {
            log.info("Response-Status: " + statusCode);
        }

        StringBuffer headersSb = new StringBuffer();
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {

            String name = entry.getKey();
            if (name.equalsIgnoreCase("Transfer-Encoding") || name.equalsIgnoreCase("X-Powered-By")) {
                continue;
            }

            for (String value : entry.getValue()) {
                response.setHeader(entry.getKey(), value);
                headersSb.append(name + "=" + value + ",  ");
            }
        }

        if (!response.containsHeader("Connection")) {
            response.setHeader("Connection", "close");
            headersSb.append("Connection=close,  ");
        }

        if (log.isInfoEnabled())
            log.info("ResponseHeader: " + headersSb);

        String cacheHeader = request.getHeader("MSDPortal-Cache");

        InputStream responseBody = proxyRequest.getResponseBody();

        bos = new BufferedOutputStream(response.getOutputStream());

        if (responseBody != null) {

            //bis = new BufferedInputStream(
            //      new ByteArrayInputStream(bytes));
            bis = new BufferedInputStream(responseBody);

            if (log.isDebugEnabled()) {
                /*
                bis.mark(10240000);
                BufferedReader br =  new BufferedReader(new InputStreamReader(bis,"UTF-8"));
                        
                StringBuffer logStr = new StringBuffer();
                String out = null;
                while((out = br.readLine())!= null){
                   logStr.append(out);
                }
                        
                log.debug(logStr);
                bis.reset();
                */
                bis = printDebug(bis);
            }

            String cacheID = null;
            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse")) {

                //Process to save the cash
                String uid = (String) request.getSession().getAttribute("Uid");
                if (uid == null)
                    uid = request.getHeader("MSDPortal-SessionId");

                Map<String, List<String>> headerMap = proxyRequest.getResponseHeaders();

                try {
                    cacheID = CacheService.getHandle().insertCache(uid, url /*proxyRequest.getTargetURL() + "?"
                                                                            + request.getQueryString()*/, bis,
                            headerMap);
                    if (log.isInfoEnabled())
                        log.info("save cache : id = " + cacheID);
                } catch (Exception e) {
                    log.error(e);
                    //response.sendError(500, e.getMessage());
                }
            }

            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse") && cacheID != null) {
                response.setHeader("MSDPortal-Cache-ID", cacheID);
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Content-Length", "1");
                //response.setHeader("Content-Length", "0");
                //response.setHeader("Connection", "close");
                bos.write(0);
                bos.flush();
                //response.setStatus(204);
            } else {
                if (cacheHeader != null && cacheHeader.equals("No-Cache")) {
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                }
                if (!response.containsHeader("Content-Length") || statusCode == 500) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] b = new byte[1024];
                    int c = 0;
                    while ((c = bis.read(b)) != -1) {
                        baos.write(b, 0, c);
                    }

                    byte[] data = baos.toByteArray();
                    response.addHeader("Content-Length", String.valueOf(data.length));

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                }

                byte[] b = new byte[1024];
                int c = 0;
                while ((c = bis.read(b)) != -1) {
                    bos.write(b, 0, c);
                }
                bos.flush();
            }
        } else {
            if (statusCode == HttpStatus.SC_NO_CONTENT) {
                response.setHeader("Content-Length", "0");
            } else {
                response.setHeader("Content-Length", "1");
                bos.write(0);
                bos.flush();
            }
        }

        long elapsedtime = new Date().getTime() - lastDeleteCachesTime;
        if (elapsedtime > 86400000) {
            log.info("Delete old public caches.");
            lastDeleteCachesTime = new Date().getTime();
            CacheService.getHandle().deleteOldPublicCaches();
        }

    } catch (Exception e) {

        log.error("Failed to get the URL. " + buildMessage(statusCode, proxyRequest, url), e);
        response.sendError(500, e.getMessage());
    } finally {
        if (log.isInfoEnabled()) {
            log.info("Succeeded in getting the URL. " + buildMessage(statusCode, proxyRequest, url));
        }

        if (proxyRequest != null)
            proxyRequest.close();
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}

From source file:org.jahia.bin.Logout.java

protected String resolveLanguage(HttpServletRequest request, final JCRSiteNode site) throws JahiaException {
    final List<Locale> newLocaleList = new ArrayList<Locale>();
    List<Locale> siteLanguages = Collections.emptyList();
    try {/* w  w  w.j  a  v  a2s.c  o m*/
        if (site != null) {
            siteLanguages = site.getLanguagesAsLocales();
        }
    } catch (Exception t) {
        logger.debug("Exception while getting language settings as locales", t);
    }

    // retrieve the browser locales
    for (@SuppressWarnings("unchecked")
    Iterator<Locale> browserLocales = new EnumerationIterator(request.getLocales()); browserLocales
            .hasNext();) {
        final Locale curLocale = browserLocales.next();
        if (siteLanguages.contains(curLocale)) {
            addLocale(site, newLocaleList, curLocale);
        } else if (!StringUtils.isEmpty(curLocale.getCountry())) {
            final Locale langOnlyLocale = new Locale(curLocale.getLanguage());
            if (siteLanguages.contains(langOnlyLocale)) {
                addLocale(site, newLocaleList, langOnlyLocale);
            }
        }
    }

    String language = DEFAULT_LOCALE;
    if (!newLocaleList.isEmpty()) {
        language = newLocaleList.get(0).toString();
    } else if (site != null) {
        language = site.getDefaultLanguage();
    } else if (!StringUtils.isEmpty(SettingsBean.getInstance().getDefaultLanguageCode())) {
        language = SettingsBean.getInstance().getDefaultLanguageCode();
    }
    return language;
}

From source file:org.jahia.utils.LanguageCodeConverters.java

public static Locale resolveLocaleForGuest(HttpServletRequest request) {
    List<Locale> availableBundleLocales = getAvailableBundleLocales();
    Enumeration<Locale> browserLocales = request.getLocales();
    Locale resolvedLocale = availableBundleLocales != null && !availableBundleLocales.isEmpty()
            ? availableBundleLocales.get(0)
            : Locale.ENGLISH;/*www .  jav a  2  s  .com*/
    while (browserLocales != null && browserLocales.hasMoreElements()) {
        Locale candidate = browserLocales.nextElement();
        if (candidate != null) {
            if (availableBundleLocales.contains(candidate)) {
                resolvedLocale = candidate;
                break;
            } else if (StringUtils.isNotEmpty(candidate.getCountry())
                    && availableBundleLocales.contains(new Locale(candidate.getLanguage()))) {
                resolvedLocale = new Locale(candidate.getLanguage());
                break;
            }
        }
    }

    return resolvedLocale;
}

From source file:org.josso.gl2.agent.SSOAgentValve.java

/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 * @throws IOException/*from   w w w  .ja va2 s  .  co  m*/
 */
private void saveRequest(HttpRequest request, Session session) {

    // Create and populate a SavedRequest object for this request
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++)
            saved.addCookie(cookies[i]);
    }
    Enumeration names = hreq.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = hreq.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration locales = hreq.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        saved.addLocale(locale);
    }
    Map parameters = hreq.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();
    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        String paramValues[] = (String[]) parameters.get(paramName);
        saved.addParameter(paramName, paramValues);
    }
    saved.setMethod(hreq.getMethod());
    saved.setQueryString(hreq.getQueryString());
    saved.setRequestURI(hreq.getRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(org.apache.catalina.authenticator.Constants.FORM_REQUEST_NOTE, saved);

}

From source file:ORG.oclc.os.SRW.SRWServletInfo.java

public void writeXmlHeader(final PrintWriter printWriter, final MessageContext msgContext,
        final HttpServletRequest req, final String defaultXsl) {
    printWriter.println("<?xml version=\"1.0\" ?> ");
    String xsl = req.getParameter("xsl"); // version 1.0
    if (xsl == null)
        xsl = req.getParameter("stylesheet"); // version 1.1
    if (xsl == null)
        xsl = defaultXsl;/*ww  w .j  a  va 2s  .c  om*/
    if (xsl != null) {
        String languages = req.getHeader("Accept-Language");
        String realXsl = (String) realXsls.get(languages + '/' + xsl);
        if (realXsl == null)
            xsl = findRealXsl(languages, req.getLocales(), xsl);
        else
            xsl = realXsl;
        printWriter.println("<?xml-stylesheet type=\"text/xsl\" " + "href=\"" + xsl + "\"?>");
    }
}

From source file:ORG.oclc.os.SRW.SRWServletInfo.java

public void writeXmlHeader(final javax.servlet.ServletOutputStream sos, final MessageContext msgContext,
        final HttpServletRequest req, final String defaultXsl) {
    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" ?> \n");
    String xsl = req.getParameter("xsl"); // version 1.0
    if (xsl == null)
        xsl = req.getParameter("stylesheet"); // version 1.1
    if (xsl == null)
        xsl = defaultXsl;//from  ww  w  .j a  va  2 s .  c o m
    if (xsl != null) {
        String languages = req.getHeader("Accept-Language");
        String realXsl = (String) realXsls.get(languages + '/' + xsl);
        if (realXsl == null)
            xsl = findRealXsl(languages, req.getLocales(), xsl);
        else
            xsl = realXsl;
        sb.append("<?xml-stylesheet type=\"text/xsl\" href=\"").append(xsl).append("\"?>\n");
    }
    try {
        sos.write(sb.toString().getBytes("utf-8"));
    } catch (Exception e) {
    }
}

From source file:org.openqa.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//from   w  w  w. j  a  v a 2s .c o m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

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

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.ppwcode.vernacular.l10n_III.web.HttpRequestLocaleFilter.java

private void doRequestLocaleFilter(HttpServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpSession session = request.getSession();

    if (session.getAttribute(ATTRIBUTE_PREFERRED_LOCALE) == null) {
        Enumeration<?> acceptedLocales = request.getLocales();
        List<Locale> supportedLocales = LocaleManager.getSupportedLocales();

        @SuppressWarnings("unchecked") // request.getLocales does not use generics
        Enumeration<Locale> typedAcceptedLocales = (Enumeration<Locale>) acceptedLocales;
        Locale bestLocale = LocaleHelpers.findPreferredLocale(typedAcceptedLocales, supportedLocales);

        if (LOG.isDebugEnabled()) {
            String info = "accepted:  ";
            Enumeration<?> test = request.getLocales();
            while (test.hasMoreElements()) {
                info += test.nextElement() + " ";
            }/*from  w  ww  .ja  va 2s.  com*/
            LOG.debug(info);
            LOG.debug("supported: " + supportedLocales);
            LOG.debug("preferred: " + bestLocale);
        }

        session.setAttribute(ATTRIBUTE_PREFERRED_LOCALE, bestLocale);
    }
    chain.doFilter(request, response);
}