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:com.aurel.track.dbase.ReadyTesterServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    prepareResponse(resp);// w ww  .  jav a2 s  . c om
    PrintWriter out = resp.getWriter();
    Enumeration<Locale> locales = req.getLocales();
    execute(out, locales);
}

From source file:com.acc.storefront.filters.StorefrontFilter.java

protected void initDefaults(final HttpServletRequest request) {
    final StoreSessionFacade storeSessionFacade = getStoreSessionFacade();

    storeSessionFacade.initializeSession(Collections.list((Enumeration<Locale>) request.getLocales()));
}

From source file:LocaleInformationServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Locale userPreferredLocale = request.getLocale();
    Enumeration userPreferredLocales = request.getLocales();

    out.println("Preferred Locale: " + userPreferredLocale.toString());
    out.println("");
    out.print("Preferred Locales: ");

    while (userPreferredLocales.hasMoreElements()) {
        userPreferredLocale = (Locale) userPreferredLocales.nextElement();
        out.print(userPreferredLocale.toString() + ", ");
    }/* w w w  . ja va 2s  .  com*/
    out.println();
    out.println("");
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

/**
 * The ETAG from the search index is not specific enough, since we may have
 * different versions for different languages. Add the Locales from the
 * request to make it unique.//w ww . ja v  a 2s .  c om
 */
private String produceLanguageSpecificEtag(HttpServletRequest req, String rawEtag) {
    if (rawEtag == null) {
        return null;
    }

    @SuppressWarnings("unchecked")
    List<Locale> locales = EnumerationUtils.toList(req.getLocales());

    StringBuilder buffer = new StringBuilder("\"").append(rawEtag);
    for (Locale locale : locales) {
        buffer.append(locale.toString());
    }
    buffer.append("\"");

    String etag = buffer.toString().replaceAll("\\s", "");
    log.debug("Language-specific ETAG = " + etag);
    return etag;
}

From source file:com.aurel.track.prop.LoginBL.java

/**
 *
 * @param username//from  w  w  w  . j a v a  2  s.c  o  m
 * @param userPwd
 * @param nonce
 * @param request
 * @param anonymousLogin
 * @return Map with two entries: 1. "errors": ArrayList<LabelValueBean>; 2.
 *         "mappingEnum": Integer with 2: bad credentials, 6: license
 *         problems, 7: forward to URL, 8: first time admin user, 18:
 *         request license, 9: standard login
 *
 */
public static Map<String, Object> setEnvironment(String username, String userPwd, String nonce,
        HttpServletRequest request, Map<String, Object> sessionMap, boolean anonymousLogin,
        boolean usingContainerBasedAuthentication, boolean springAuthenticated) {
    HttpSession httpSession = request.getSession();
    ArrayList<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    HashMap<String, Object> result = new HashMap<String, Object>();
    Integer mappingEnum = 0;

    // Make things robust
    if (username == null) {
        username = "x";
    }
    if (userPwd == null) {
        userPwd = "x";
    }
    // Move locale to one that we actually have, in case there
    // was a request for a locale that we do not have
    Locale locale = LocaleHandler.getExistingLocale(request.getLocales());
    LocaleHandler.exportLocaleToSession(sessionMap, locale);
    Support support = new Support();
    support.setURIs(request);
    if (username != null) {
        ACCESSLOGGER.info("LOGON: User '" + username.trim() + "' trying to log on" + " at "
                + new Date().toString() + " from " + request.getRemoteAddr());
    }
    ServletContext servletContext = org.apache.struts2.ServletActionContext.getServletContext();
    try {
        if (!Torque.isInit()) {
            Torque.init(HandleHome.getTorqueProperties(servletContext, true));
            LOGGER.debug("Database is " + Torque.getDefaultDB());
            LOGGER.info("Torque was re-initialized.");
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        LOGGER.error("Could not initialize Torque (1)");
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        errors.add(new LabelValueBean("errGeneralError",
                getText("logon.err.noDataBase", locale) + ":" + e.getMessage()));
        mappingEnum = 1;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }
    TPersonBean personBean = null;
    if (anonymousLogin) {
        personBean = PersonBL.getAnonymousIfActive();
    } else {
        try {
            String pwd = "";
            if (nonce == null || nonce.length() == 0) {
                pwd = userPwd; // clear text
            } else {
                pwd = decrypt(nonce.charAt(0), userPwd); // key is first
                // character of
                // nonce
            }
            personBean = PersonBL.loadByLoginNameWithRights(username);

            if (personBean != null) {
                personBean.setPlainPwd(pwd);

                if (personBean.isDisabled()) {
                    errors.add(
                            new LabelValueBean("errCredentials", getText("logon.err.user.disabled", locale)));
                    ACCESSLOGGER
                            .warn("LOGON: User " + personBean.getLoginName() + " is disabled, login refused!");
                } else if (usingContainerBasedAuthentication == false && springAuthenticated == false
                        && !personBean.authenticate(pwd)) {
                    ACCESSLOGGER.warn("LOGON: Wrong password given for user " + personBean.getFullName()
                            + " at " + new Date().toString() + " from " + request.getRemoteAddr());
                    errors.add(new LabelValueBean("errCredentials",
                            getText("logon.err.password.mismatch", locale)));
                }
            } else {
                ACCESSLOGGER.warn("LOGON: No such user: " + username + " at " + new Date().toString() + " from "
                        + request.getRemoteAddr());
                errors.add(
                        new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale)));
                LOGGER.debug("User '" + username + "' is not in database...");
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("Could not initialize Torque (2)");
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale)));
        }
    }

    if (errors.size() > 0 || personBean == null) {
        mappingEnum = 2;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    // At this point, we have successfully identified the user.
    // Try to set the users preferred locale
    if (personBean.getPrefLocale() != null && !"".equals(personBean.getPrefLocale())) {
        // get as stored in user profile
        locale = LocaleHandler.getExistingLocale(LocaleHandler.getLocaleFromString(personBean.getPrefLocale()));
    }
    if (locale == null) {
        // rely on browser settings
        locale = LocaleHandler.getExistingLocale(request.getLocales());
    }
    personBean.setLocale(locale);

    // set the bean with the last saved login date and save the actual date
    // as
    // last login date in the database
    personBean.setLastButOneLogin(personBean.getLastLogin());
    personBean.setLastLogin(new Date());
    PersonBL.saveSimple(personBean);
    LocaleHandler.exportLocaleToSession(sessionMap, locale);

    // -----------------------------------------------------

    // check if opState
    // (reject users, but not admin, in maintenance state)
    ApplicationBean appBean = ApplicationBean.getInstance();

    if (appBean == null) {
        LOGGER.error("appBean == null: this should never happen");
        mappingEnum = 3;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    httpSession.setAttribute(Constants.APPLICATION_BEAN, appBean);

    TSiteBean siteBean = DAOFactory.getFactory().getSiteDAO().load1();

    if (ApplicationBean.OPSTATE_MAINTENNANCE.equals(siteBean.getOpState()) && !personBean.getIsSysAdmin()) {
        // print error, refuse login
        errors.add(new LabelValueBean("errGeneralError", getText("logon.err.maintenance", locale)));
        mappingEnum = 4;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    Runtime rt = Runtime.getRuntime();
    long mbyte = 1024 * 1024;
    long freeMemoryMB = rt.freeMemory() / mbyte;
    if (freeMemoryMB < 50 && !personBean.getIsSysAdmin()) {
        rt.gc();
        freeMemoryMB = rt.freeMemory() / mbyte;
        if (freeMemoryMB < 50) {
            errors.add(new LabelValueBean("errGeneralError", getText("logon.err.freeMemory", locale)));
            mappingEnum = 19;
            result.put("errors", errors);
            result.put("mappingEnum", mappingEnum);
            return result;
        }
    }

    // Save our logged-in user in the session
    // and set a cookie so she can conveniently point
    // directly to issues without having to log on for
    // the next CookieTimeout seconds

    httpSession.setAttribute(Constants.USER_KEY, personBean);

    int maxItemsProUser = GeneralSettings.getMaxItems();
    FilterUpperTO filterUpperTO = new FilterUpperTO();
    TreeFilterExecuterFacade.prepareFilterUpperTO(filterUpperTO, personBean, locale, null, null);
    int noOfProjectRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterProjectRoleItems(filterUpperTO,
            personBean, locale, maxItemsProUser);
    int noOfRACIRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterRACIRoleItems(filterUpperTO,
            personBean, locale, maxItemsProUser);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Maximum number of items per user " + maxItemsProUser);
        LOGGER.debug(
                "Number of project role items accessible by " + username + ": " + noOfProjectRoleItemsProUser);
        LOGGER.debug("Number of RACI role items accessible by " + username + ": " + noOfRACIRoleItemsProUser);
    }
    boolean projectRoleItemsAboveLimit = noOfProjectRoleItemsProUser >= maxItemsProUser;
    boolean raciRoleItemsAboveLimit = noOfRACIRoleItemsProUser >= maxItemsProUser;
    personBean.setProjectRoleItemsAboveLimit(Boolean.valueOf(projectRoleItemsAboveLimit));
    personBean.setRaciRoleItemsAboveLimit(Boolean.valueOf(raciRoleItemsAboveLimit));
    PersonBL.setLicensedFeatures(personBean);

    List<TListTypeBean> issueTypes = IssueTypeBL.loadAllByPerson(personBean.getObjectID(), locale);
    httpSession.setAttribute("issueTypesJSON", JSONUtility.encodeIssueTypes(issueTypes));
    Integer sessionTimeoutMinutes = personBean.getSessionTimeoutMinutes();
    if (sessionTimeoutMinutes != null && sessionTimeoutMinutes.intValue() != 0) {
        httpSession.setMaxInactiveInterval(sessionTimeoutMinutes * 60);
    }
    // load the my filters in the menu
    List<FilterInMenuTO> myFilters = FilterBL.loadMyMenuFiltersWithTooltip(personBean, locale);

    httpSession.setAttribute(FilterBL.MY_MENU_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(myFilters));

    List<FilterInMenuTO> lastQueries = FilterInMenuBL.getLastExecutedQueries(personBean, locale);

    httpSession.setAttribute(FilterBL.LAST_EXECUTED_FILTERS_JSON,
            FilterInMenuJSON.encodeFiltersInMenu(lastQueries));
    httpSession.setAttribute(ShortcutBL.SHORTCUTS_JSON, ShortcutBL.encodeShortcutsJSON());

    // modules
    List modules = getModuleDescriptors(personBean);
    httpSession.setAttribute("usedModules", modules);
    httpSession.setAttribute("usedModulesJSON", MasterHomeJSON.encodeModules(modules, personBean));
    httpSession.setAttribute("loggedInPersonUserLevel", personBean.getUserLevel());
    httpSession.setAttribute("clientUserLevelID", TPersonBean.USERLEVEL.CLIENT);

    // maxFileSize
    int maxFileSize = AttachBL.getMaxFileSize(siteBean);
    httpSession.setAttribute("MAXFILESIZE", maxFileSize);

    // ------------------------------------------------------
    // Create a new SessionBean for this session and bind it to the session

    SessionBean sBean = new SessionBean();
    httpSession.setAttribute(Constants.SESSION_BEAN, sBean);

    ItemLockBL.removeLockedIssuesByUser(personBean.getObjectID());

    ACCESSLOGGER.info("LOGON: User '" + personBean.getLoginName().trim() + "' (" + personBean.getFullName()
            + ")" + " logged in at " + new Date().toString() + " from " + request.getRemoteAddr());

    LicenseManager lm = appBean.getLicenseManager();
    if (lm != null) {
        int rf = lm.getErrorCode();
        boolean haveLicenseErrors = false;
        switch (rf) {
        case 1:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.needCommercial", locale)));
            break;
        case 2:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.expired", locale)));
            break;
        case 3:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.full.exceeded", locale)));
            break;
        case 4:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.invalid",
                    new String[] { ApplicationBean.getIpNumbersString() }, locale)));
            break;
        case 7:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError",
                    getText("logon.err.license.limited.exceeded", locale)));
            break;
        case 8:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.gantt.exceeded", locale)));
            break;
        default:
            break;
        }

        if (haveLicenseErrors == true) {
            mappingEnum = 6;
            result.put("errors", errors);
            result.put("mappingEnum", mappingEnum);
            return result;
        }
    }

    result.put("errors", errors);

    httpSession.setAttribute("DESIGNPATH", personBean.getDesignPath());

    Boolean isMobileDevice = LogoffBL.isThisAMobileDevice(request);
    httpSession.setAttribute("mobile", isMobileDevice);

    LOGGER.debug("Mobile is " + httpSession.getAttribute("mobile"));

    // check for post-login forward
    String forwardUrl = (String) httpSession.getAttribute(Constants.POSTLOGINFORWARD);
    if (forwardUrl != null) {
        LOGGER.debug("Forward URL found :" + forwardUrl);
        mappingEnum = 7;
        result.put("mappingEnum", mappingEnum);
        return result;

    }

    Map ret = new GroovyScriptExecuter().handleEvent(IEventSubscriber.EVENT_POST_USER_LOGGED_IN, new HashMap());
    if (ret.get(BINDING_PARAMS.CONTINUE).equals(Boolean.FALSE)) {
        mappingEnum = 10;
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    String extendedKey = ApplicationBean.getInstance().getExtendedKey();

    if (extendedKey == null || extendedKey.length() < 10) { // no empty keys
        // allowed
        mappingEnum = 18;
        result.put("mappingEnum", mappingEnum);
        return result;

    }

    String firstTime = (String) servletContext.getAttribute("FirstTime");

    result.put("user", personBean);

    if (personBean.getIsSysAdmin() && firstTime != null && firstTime.equals("FT")) {

        servletContext.removeAttribute("FirstTime");
        mappingEnum = 8;
        result.put("mappingEnum", mappingEnum);
        return result;

    } else {
        // Forward control to the specified success URI
        mappingEnum = 9;
        result.put("mappingEnum", mappingEnum);
        return result;
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

@RequestMapping(value = { "/api/records/{metadataUuid}/formatters/{formatterId}",
        "/api/" + API.VERSION_0_1
                + "/records/{metadataUuid}/formatters/{formatterId}" }, method = RequestMethod.GET, produces = {
                        MediaType.TEXT_HTML_VALUE, MediaType.APPLICATION_XHTML_XML_VALUE, "application/pdf",
                        MediaType.ALL_VALUE
        // TODO: PDF
})
@ApiOperation(value = "Get a formatted metadata record", nickname = "getRecordFormattedBy")
@ResponseBody/*  w w w . ja v a  2 s  .co  m*/
public void getRecordFormattedBy(
        @ApiParam(value = "Formatter type to use.") @RequestHeader(value = HttpHeaders.ACCEPT, defaultValue = MediaType.TEXT_HTML_VALUE) String acceptHeader,
        @PathVariable(value = "formatterId") final String formatterId,
        @ApiParam(value = API_PARAM_RECORD_UUID, required = true) @PathVariable String metadataUuid,
        @RequestParam(value = "width", defaultValue = "_100") final FormatterWidth width,
        @RequestParam(value = "mdpath", required = false) final String mdPath,
        @RequestParam(value = "output", required = false) FormatType formatType,
        @ApiIgnore final NativeWebRequest request, final HttpServletRequest servletRequest) throws Exception {

    ApplicationContext applicationContext = ApplicationContextHolder.get();
    Locale locale = languageUtils.parseAcceptLanguage(servletRequest.getLocales());

    // TODO :
    // if text/html > xsl_view
    // if application/pdf > xsl_view and PDF output
    // if application/x-gn-<formatterId>+(xml|html|pdf|text)
    // Force PDF ouutput when URL parameter is set.
    // This is useful when making GET link to PDF which
    // can not use headers.
    if (MediaType.ALL_VALUE.equals(acceptHeader)) {
        acceptHeader = MediaType.TEXT_HTML_VALUE;
    }
    if (formatType == null) {
        formatType = FormatType.find(acceptHeader);
    }
    if (formatType == null) {
        formatType = FormatType.xml;
    }

    final String language = LanguageUtils.locale2gnCode(locale.getISO3Language());
    final ServiceContext context = createServiceContext(language, formatType,
            request.getNativeRequest(HttpServletRequest.class));
    AbstractMetadata metadata = ApiUtils.canViewRecord(metadataUuid, servletRequest);

    Boolean hideWithheld = true;
    //        final boolean hideWithheld = Boolean.TRUE.equals(hide_withheld) ||
    //            !context.getBean(AccessManager.class).canEdit(context, resolvedId);
    Key key = new Key(metadata.getId(), language, formatType, formatterId, hideWithheld, width);
    final boolean skipPopularityBool = false;

    ISODate changeDate = metadata.getDataInfo().getChangeDate();

    Validator validator;
    if (changeDate != null) {
        final long changeDateAsTime = changeDate.toDate().getTime();
        long roundedChangeDate = changeDateAsTime / 1000 * 1000;
        if (request.checkNotModified(language, roundedChangeDate)
                && context.getBean(CacheConfig.class).allowCaching(key)) {
            if (!skipPopularityBool) {
                context.getBean(DataManager.class).increasePopularity(context,
                        String.valueOf(metadata.getId()));
            }
            return;
        }
        validator = new ChangeDateValidator(changeDateAsTime);
    } else {
        validator = new NoCacheValidator();
    }
    final FormatMetadata formatMetadata = new FormatMetadata(context, key, request);

    byte[] bytes;
    if (hasNonStandardParameters(request)) {
        // the http headers can cause a formatter to output custom output due to the parameters.
        // because it is not known how the parameters may affect the output then we have two choices
        // 1. make a unique cache for each configuration of parameters
        // 2. don't cache anything that has extra parameters beyond the standard parameters used to
        //    create the key
        // #1 has a major flaw because an attacker could simply make new requests always changing the parameters
        // and completely swamp the cache.  So we go with #2.  The formatters are pretty fast so it is a fine solution
        bytes = formatMetadata.call().data;
    } else {
        bytes = context.getBean(FormatterCache.class).get(key, validator, formatMetadata, false);
    }
    if (bytes != null) {
        if (!skipPopularityBool) {
            context.getBean(DataManager.class).increasePopularity(context, String.valueOf(metadata.getId()));
        }
        writeOutResponse(context, metadataUuid, locale.getISO3Language(),
                request.getNativeResponse(HttpServletResponse.class), formatType, bytes);
    }
}

From source file:org.itracker.web.util.LoginUtilities.java

/**
 * Get a locale from request//  ww  w.  j  a  va  2s  .c om
 * <p/>
 * <p>
 * TODO the order of retrieving locale from request should be:
 * <ol>
 * <li>request-attribute Constants.LOCALE_KEY</li>
 * <li>request-param 'loc'</li>
 * <li>session attribute <code>Constants.LOCALE_KEY</code></li>
 * <li>cookie 'loc'</li>
 * <li>request.getLocale()/request.getLocales()</li>
 * <li>ITrackerResources.DEFAULT_LOCALE</li>
 * </ol>
 * </p>
 */
@SuppressWarnings("unchecked")
public static Locale getCurrentLocale(HttpServletRequest request) {
    Locale requestLocale = null;
    HttpSession session = request.getSession(true);
    try {

        requestLocale = (Locale) request.getAttribute(Constants.LOCALE_KEY);

        if (logger.isDebugEnabled()) {
            logger.debug("getCurrentLocale: request-attribute was {}", requestLocale);
        }

        if (null == requestLocale) {
            // get locale from request param
            String loc = request.getParameter("loc");
            if (null != loc && loc.trim().length() > 1) {
                requestLocale = ITrackerResources.getLocale(loc);
            }

            logger.debug("getCurrentLocale: request-parameter was {}", loc);

        }

        if (null == requestLocale) {
            // get it from the session
            requestLocale = (Locale) session.getAttribute(Constants.LOCALE_KEY);
            //            if (logger.isDebugEnabled()) {
            //               logger.debug("getCurrentLocale: session-attribute was "
            //                     + requestLocale);
            //            }
        }

        if (null == requestLocale) {
            ResourceBundle bundle = ITrackerResources.getBundle(request.getLocale());
            if (logger.isDebugEnabled()) {
                logger.debug("getCurrentLocale: trying request header locale " + request.getLocale());
            }
            if (bundle.getLocale().getLanguage().equals(request.getLocale().getLanguage())) {
                requestLocale = request.getLocale();
                if (logger.isDebugEnabled()) {
                    logger.debug("getCurrentLocale: request-locale was " + requestLocale);
                }
            }
        }

        // is there no way to detect supported locales of current
        // installation?

        if (null == requestLocale) {
            Enumeration<Locale> locales = (Enumeration<Locale>) request.getLocales();
            ResourceBundle bundle;
            Locale locale;
            while (locales.hasMoreElements()) {
                locale = locales.nextElement();
                bundle = ITrackerResources.getBundle(locale);

                logger.debug("getCurrentLocale: request-locales processing {}, bundle: {}", locale, bundle);

                if (bundle.getLocale().getLanguage().equals(locale.getLanguage())) {
                    requestLocale = locale;

                    logger.debug("getCurrentLocale: request-locales locale was {}", requestLocale);

                }
            }
        }

    } finally {
        if (null == requestLocale) {
            // fall back to default locale
            requestLocale = ITrackerResources.getLocale();

            logger.debug("getCurrentLocale: fallback default locale was {}", requestLocale);

        }
        session.setAttribute(Constants.LOCALE_KEY, requestLocale);
        request.setAttribute(Constants.LOCALE_KEY, requestLocale);
        request.setAttribute("currLocale", requestLocale);

        logger.debug("getCurrentLocale: request and session was setup with {}", requestLocale);

    }

    return requestLocale;
}

From source file:net.lightbody.bmp.proxy.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 {/*  ww  w  .ja  va2  s . co 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:de.innovationgate.wgpublisher.WGACore.java

public String getSystemLabel(String systemBundleName, String labelKey, HttpServletRequest servletRequest) {

    String label = null;/* ww w.j  av  a 2  s. c om*/
    PropertyResourceBundle bundle = null;

    List<Locale> locales = new ArrayList<Locale>();
    if (servletRequest != null) {
        locales.addAll(WGUtils.extractEntryList(servletRequest.getLocales()));
    }
    locales.add(Locale.getDefault());
    locales.add(Locale.ENGLISH);

    for (Locale locale : locales) {
        try {
            bundle = (PropertyResourceBundle) ResourceBundle.getBundle(
                    WGACore.SYSTEMLABEL_BASE_PATH + systemBundleName, locale, this.getClass().getClassLoader());
            label = bundle.getString(labelKey);
            if (label != null) {
                return label;
            }
        } catch (java.util.MissingResourceException e) {
        }
    }

    return null;
}

From source file:org.acegisecurity.ui.savedrequest.SavedRequest.java

public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
    Assert.notNull(request, "Request required");
    Assert.notNull(portResolver, "PortResolver required");

    // Cookies/*from  www  .jav a 2 s  . com*/
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            this.addCookie(cookies[i]);
        }
    }

    // Headers
    Enumeration names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = request.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            this.addHeader(name, value);
        }
    }

    // Locales
    Enumeration locales = request.getLocales();

    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        this.addLocale(locale);
    }

    // Parameters
    Map parameters = request.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();

    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        Object o = parameters.get(paramName);
        if (o instanceof String[]) {
            String[] paramValues = (String[]) o;
            this.addParameter(paramName, paramValues);
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("ServletRequest.getParameterMap() returned non-String array");
            }
        }
    }

    // Primitives
    this.method = request.getMethod();
    this.pathInfo = request.getPathInfo();
    this.queryString = request.getQueryString();
    this.requestURI = request.getRequestURI();
    this.serverPort = portResolver.getServerPort(request);
    this.requestURL = request.getRequestURL().toString();
    this.scheme = request.getScheme();
    this.serverName = request.getServerName();
    this.contextPath = request.getContextPath();
    this.servletPath = request.getServletPath();
}