Example usage for javax.servlet.jsp PageContext getRequest

List of usage examples for javax.servlet.jsp PageContext getRequest

Introduction

In this page you can find the example usage for javax.servlet.jsp PageContext getRequest.

Prototype


abstract public ServletRequest getRequest();

Source Link

Document

The current value of the request object (a ServletRequest).

Usage

From source file:com.redhat.rhn.frontend.taglibs.list.ListTagUtil.java

/**
 * Renders the filter UI//from w ww.  j a  v  a2  s . c o  m
 * @param pageContext caller's page context
 * @param filter ListFilter instance
 * @param uniqueName name of the list
 * @param width width of the list
 * @param columnCount list's column count
 * @param searchParent true if list tag allows searching of parent
 * @param searchChild true if the list tag allows searching of child
 * @throws JspException if something bad happens writing to the page
 */
public static void renderFilterUI(PageContext pageContext, ListFilter filter, String uniqueName, String width,
        int columnCount, boolean searchParent, boolean searchChild) throws JspException {
    LocalizationService ls = LocalizationService.getInstance();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String filterByKey = makeFilterByLabel(uniqueName);
    String filterBy = request.getParameter(filterByKey);
    String filterValueKey = makeFilterValueByLabel(uniqueName);
    String filterName = makeFilterNameByLabel(uniqueName);
    String filterValue = ListTagHelper.getFilterValue(pageContext.getRequest(), uniqueName);

    //We set this so we know next time around what the old filter value was
    ListTagUtil.write(pageContext, String.format(HIDDEN_TEXT, makeOldFilterValueByLabel(uniqueName),
            StringEscapeUtils.escapeHtml(filterValue)));

    List fields = filter.getFieldNames();
    if (fields == null || fields.size() == 0) {
        throw new JspException("ListFilter.getFieldNames() returned no field names");
    } else if (fields.size() == 1) {
        ListTagUtil.write(pageContext, "<input type=\"hidden\" name=\"");
        ListTagUtil.write(pageContext, filterByKey);
        ListTagUtil.write(pageContext, "\" value=\"");
        ListTagUtil.write(pageContext, fields.get(0).toString());
        ListTagUtil.write(pageContext, "\" />");
    } else {
        ListTagUtil.write(pageContext, ls.getMessage("message.filterby.multiple"));
        ListTagUtil.write(pageContext, "<select name=\"");
        ListTagUtil.write(pageContext, filterByKey);
        ListTagUtil.write(pageContext, "\">");
        for (Iterator iter = fields.iterator(); iter.hasNext();) {
            String field = (String) iter.next();
            ListTagUtil.write(pageContext, "<option value=\"");
            ListTagUtil.write(pageContext, field);
            ListTagUtil.write(pageContext, "\" ");
            if (field.equals(filterBy)) {
                ListTagUtil.write(pageContext, "selected");
            }
            ListTagUtil.write(pageContext, ">");
            ListTagUtil.write(pageContext, field);
            ListTagUtil.write(pageContext, "</option>");
        }
        ListTagUtil.write(pageContext, "</select>");
    }

    filterValue = StringUtil.nullOrValue(filterValue);
    StringBuilder sb = new StringBuilder();

    // create a new row
    sb.append("<div class=\"input-group input-group-sm\">");

    String placeHolder = StringUtils.defaultString(ls.getMessage("message.filterby", fields.get(0).toString()));
    sb.append(String.format(
            "<input autofocus=\"autofocus\" type=\"text\" "
                    + " name=\"%s\" value=\"%s\" class=\"form-control\" placeholder=\"%s\"/>",
            filterValueKey, (filterValue != null ? StringEscapeUtils.escapeHtml(filterValue) : ""),
            StringEscapeUtils.escapeHtml(placeHolder)));
    sb.append("<span class=\"input-group-btn\">");
    sb.append(String.format(
            "<button value=\"%s\" type=\"submit\" name=\"%s\" "
                    + " class=\"btn btn-default spacewalk-button-filter\"><i class=\"fa fa-eye\"></i>",
            ls.getMessage(RequestContext.FILTER_KEY), filterName));
    sb.append("</button>");
    sb.append("</span>");

    sb.append("</div>");

    ListTagUtil.write(pageContext, sb.toString());

}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Parse an optionally present boolean from a request parameter.
 *
 * @param context The context of the web request.
 * @param param The name of the parameter to parse
 * @param defaultValue A value to return if the parameter is not present (may be null)
 * @return Parsed value or default value if the parameter is missing or empty. Null will only be returned if passed
 * as the default value.//from  w  w  w  .jav  a2 s .  c  o  m
 */
public static boolean parseOptionalBoolean(PageContext context, String param, boolean defaultValue) {
    ArgumentNotValid.checkNotNullOrEmpty(param, "String param");
    String paramValue = context.getRequest().getParameter(param);
    if (paramValue != null && paramValue.trim().length() > 0) {
        paramValue = paramValue.trim();
        return Boolean.parseBoolean(paramValue);
    } else {
        return defaultValue;
    }
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Prints the header information for the webpages in the GUI. This includes the navigation menu, and links for
 * changing the language. The title of the page is generated internationalised from sitesections. If you want to
 * specify it, use the overloaded method.
 *
 * @param context The context of the web page request.
 * @throws IOException if an error occurs during writing of output.
 *//*from  www.  j  ava  2s .  c  o  m*/
public static void generateHeader(PageContext context, String... jsToInclude) throws IOException {
    ArgumentNotValid.checkNotNull(context, "context");
    String url = ((HttpServletRequest) context.getRequest()).getRequestURL().toString();
    Locale locale = context.getResponse().getLocale();
    String title = getTitle(url, locale);
    generateHeader(title, context, jsToInclude);
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Prints the header information for the webpages in the GUI. This includes the navigation menu, and links for
 * changing the language. The title of the page is generated internationalised from sitesections. If you want to
 * specify it, use the overloaded method.
 *
 * @param context The context of the web page request.
 * @param refreshInSeconds auto-refresh time in seconds
 * @throws IOException if an error occurs during writing of output.
 *//*  w w w.  ja v a  2  s.  co m*/
public static void generateHeader(PageContext context, long refreshInSeconds) throws IOException {
    ArgumentNotValid.checkNotNull(context, "context");
    String url = ((HttpServletRequest) context.getRequest()).getRequestURL().toString();
    Locale locale = context.getResponse().getLocale();
    String title = getTitle(url, locale);
    generateHeader(title, refreshInSeconds, context);
}

From source file:org.sakaiproject.iclicker.tool.ToolController.java

public static void addMessage(PageContext context, String key, String messageKey, Object... args) {
    if (context == null || key == null) {
        throw new IllegalArgumentException(
                "context (" + context + ") and key (" + key + ") must both not be null");
    }/*  ww w . jav  a 2s  .com*/
    if (messageKey != null && !"".equals(messageKey)) {
        // get the message from messageSource if possible
        MessageSource ms = (MessageSource) context.findAttribute("messageSource");
        Locale locale = context.getRequest().getLocale();
        String message;
        try {
            message = ms.getMessage(messageKey, args, locale);
        } catch (NoSuchMessageException e) {
            message = "{{INVALID KEY:" + messageKey + "}}";
        }
        addMessage(context, key, message);
    }
}

From source file:dk.netarkivet.archive.webinterface.BatchGUI.java

/**
 * Method for executing a batchjob.// ww w .  jav  a  2  s.  c o  m
 *
 * @param context The page context containing the needed information for executing the batchjob.
 */
@SuppressWarnings("rawtypes")
public static void execute(PageContext context) {
    try {
        ServletRequest request = context.getRequest();

        // get parameters
        String filetype = request.getParameter(Constants.FILETYPE_PARAMETER);
        String jobId = request.getParameter(Constants.JOB_ID_PARAMETER);
        String jobName = request.getParameter(Constants.BATCHJOB_PARAMETER);
        String repName = request.getParameter(Constants.REPLICA_PARAMETER);

        FileBatchJob batchjob;

        // Retrieve the list of arguments.
        List<String> args = new ArrayList<String>();
        String arg;
        Integer i = 1;
        // retrieve the constructor to find out how many arguments
        Class c = getBatchClass(jobName);
        Constructor con = findStringConstructor(c);

        // retrieve the arguments and put them into the list.
        while (i <= con.getParameterTypes().length) {
            arg = request.getParameter("arg" + i.toString());
            if (arg != null) {
                args.add(arg);
            } else {
                log.warn("Should contain argument number " + i + ", but "
                        + "found a null instead, indicating missing " + "argument. Use empty string instead.");
                args.add("");
            }
            i++;
        }

        File jarfile = getJarFile(jobName);
        if (jarfile == null) {
            // get the constructor and instantiate it.
            Constructor construct = findStringConstructor(getBatchClass(jobName));
            batchjob = (FileBatchJob) construct.newInstance(args.toArray());
        } else {
            batchjob = new LoadableJarBatchJob(jobName, args, jarfile);
        }

        // get the regular expression.
        String regex = jobId + "-";
        if (filetype.equals(BatchFileType.Metadata.toString())) {
            regex += Constants.REGEX_METADATA;
        } else if (filetype.equals(BatchFileType.Content.toString())) {
            // TODO fix this 'content' regex. (NAS-1394)
            regex += Constants.REGEX_CONTENT;
        } else {
            regex += Constants.REGEX_ALL;
        }

        // validate the regular expression (throws exception if wrong).
        Pattern.compile(regex);

        Replica rep = Replica.getReplicaFromName(repName);

        new BatchExecuter(batchjob, regex, rep).start();

        JspWriter out = context.getOut();
        out.write("Executing batchjob with the following parameters. " + "<br/>\n");
        out.write("BatchJob name: " + jobName + "<br/>\n");
        out.write("Replica: " + rep.getName() + "<br/>\n");
        out.write("Regular expression: " + regex + "<br/>\n");
    } catch (Exception e) {
        throw new IOFailure("Could not instantiate the batchjob.", e);
    }
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Parse an optionally present date-value from a request parameter.
 *
 * @param context The context of the web request.
 * @param param The name of the parameter to parse
 * @param format The format of the date, in the format defined by SimpleDateFormat
 * @param defaultValue A value to return if the parameter is not present (may be null)
 * @return Parsed value or default value if the parameter is missing or empty. Null will only be returned if passed
 * as the default value./*from  w  w w  .j  a va2s .  com*/
 * @throws ForwardedToErrorPage if the parameter is present but not parseable as a date
 */
public static Date parseOptionalDate(PageContext context, String param, String format, Date defaultValue) {
    ArgumentNotValid.checkNotNullOrEmpty(param, "String param");
    ArgumentNotValid.checkNotNullOrEmpty(format, "String format");
    String paramValue = context.getRequest().getParameter(param);
    if (paramValue != null && paramValue.trim().length() > 0) {
        paramValue = paramValue.trim();
        try {
            return new SimpleDateFormat(format).parse(paramValue);
        } catch (ParseException e) {
            forwardWithErrorMessage(context, I18N, "errormsg;parameter.0.not.a.date.with.format.1.2", param,
                    format, paramValue);
            throw new ForwardedToErrorPage("Invalid value " + paramValue + " for date parameter '" + param
                    + "' with format '" + format + "'", e);
        }
    } else {
        return defaultValue;
    }
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Prints the header information for the webpages in the GUI. This includes the navigation menu, and links for
 * changing the language.//from   www.jav  a  2 s  . c  o m
 *
 * @param title An internationalised title of the page.
 * @param context The context of the web page request.
 * @param refreshInSeconds auto-refresh time in seconds
 * @throws IOException if an error occurs during writing to output.
 */
public static void generateHeader(String title, long refreshInSeconds, PageContext context) throws IOException {
    ArgumentNotValid.checkNotNull(title, "title");
    ArgumentNotValid.checkNotNull(context, "context");

    JspWriter out = context.getOut();
    String url = ((HttpServletRequest) context.getRequest()).getRequestURL().toString();
    Locale locale = context.getResponse().getLocale();
    title = escapeHtmlValues(title);
    log.debug("Loaded URL '" + url + "' with title '" + title + "'");
    out.print(WEBPAGE_HEADER_TEMPLATE_TOP);
    if (refreshInSeconds > 0) {
        out.print(WEBPAGE_HEADER_AUTOREFRESH.replace(TITLE_PLACEHOLDER, Long.toString(refreshInSeconds)));
    }
    out.print(WEBPAGE_HEADER_TEMPLATE_BOTTOM.replace(TITLE_PLACEHOLDER, title).replace(JS_PLACEHOLDER, ""));
    // Start the two column / one row table which fills the page
    out.print("<table id =\"main_table\"><tr>\n");
    // fill in data in the left column
    generateNavigationTree(out, url, locale);
    // The right column contains the active form content for this page
    out.print("<td valign = \"top\" >\n");
    // Language links
    generateLanguageLinks(out);
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Prints the header information for the webpages in the GUI. This includes the navigation menu, and links for
 * changing the language.//  w w  w  .  j  ava  2  s .  com
 *
 * @param title An internationalised title of the page.
 * @param context The context of the web page request.
 * @param jsToInclude path(s) to external .js files to include in header.
 * @throws IOException if an error occurs during writing to output.
 */
public static void generateHeader(String title, PageContext context, String... jsToInclude) throws IOException {
    ArgumentNotValid.checkNotNull(title, "title");
    ArgumentNotValid.checkNotNull(context, "context");

    JspWriter out = context.getOut();
    String url = ((HttpServletRequest) context.getRequest()).getRequestURL().toString();
    Locale locale = context.getResponse().getLocale();
    title = escapeHtmlValues(title);
    log.debug("Loaded URL '" + url + "' with title '" + title + "'");
    out.print(WEBPAGE_HEADER_TEMPLATE_TOP);

    String includeJs = "";
    if (jsToInclude != null && jsToInclude.length > 0) {
        for (String js : jsToInclude) {
            includeJs += "<script type=\"text/javascript\" src=\"" + js + "\"></script>\n";
        }
    }

    out.print(WEBPAGE_HEADER_TEMPLATE_BOTTOM.replace(TITLE_PLACEHOLDER, title).replace(JS_PLACEHOLDER,
            includeJs));
    // Start the two column / one row table which fills the page
    out.print("<table id =\"main_table\"><tr>\n");
    // fill in data in the left column
    generateNavigationTree(out, url, locale);
    // The right column contains the active form content for this page
    out.print("<td valign = \"top\" >\n");
    // Language links
    generateLanguageLinks(out);
}

From source file:com.orange.wro.taglib.tag.OptionalScriptTag.java

@Override
public void doTag() throws JspException, IOException {

    WroConfig conf = WroConfig.getInstance();
    PageContext context = (PageContext) getJspContext();
    StringBuilder builder = new StringBuilder();

    Object lessObj = context.getRequest().getAttribute(WroTagLibConstants.LESS_INJECTED);
    boolean isLessNeeded = lessObj == null ? false : (Boolean) lessObj;

    if (isLessNeeded) {
        logger.debug("Writing LESS JS to output for client side compilation.");
        writeScript(context, builder, conf.getOptions().getLessJsPath());
    }/*ww w . j  a v a 2  s  .co m*/

    context.getOut().append(builder);
}