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:dk.netarkivet.harvester.webinterface.EventHarvestUtil.java

/**
 * Adds a bunch of configurations to a given PartialHarvest. For full definitions of the parameters, see
 * Definitions-add-event-seeds.jsp. For each seed in the list, the following steps are taken: 1) The domain is
 * parsed out of the seed. If no such domain is known, it is created with the usual defaults. 2) For each domain, a
 * configuration with the name <harvestDefinition>_<orderTemplate>_<maxBytes>Bytes is created
 * unless it already exists. The configuration uses orderTemplate, and the specified maxBytes. If maxBytes is
 * unspecified, its default value is used. The configuration is added to the harvest specified by the
 * harvestDefinition argument. 3) For each domain, a seedlist with the name
 * <harvestDefinition>_<orderTemplate>_<maxBytes>Bytes is created if it does not already exist and
 * the given url is added to it. This seedlist is the only seedlist associated with the configuration of the same
 * name.//from  ww  w  . j  a v  a  2 s.  co  m
 *
 * @param context the current JSP context
 * @param i18n the translation information to use in this context
 * @param eventHarvestName The name of the partial harvest to which these seeds are to be added
 * @throws ForwardedToErrorPage If maxBytes is not a number, or if any of the seeds is badly formatted such that no
 * domain name can be parsed from it, or if orderTemplate is not given or unknown.
 */
public static void addConfigurations(PageContext context, I18n i18n, String eventHarvestName) {
    ArgumentNotValid.checkNotNull(context, "PageContext context");
    ArgumentNotValid.checkNotNull(i18n, "I18n i18n");
    ArgumentNotValid.checkNotNull(eventHarvestName, "String eventHarvestName");

    HTMLUtils.forwardOnMissingParameter(context, Constants.SEEDS_PARAM);
    ServletRequest request = context.getRequest();

    // If no seeds are specified, just return
    String seeds = request.getParameter(Constants.SEEDS_PARAM);
    if (seeds == null || seeds.trim().length() == 0) {
        return;
    }
    // split the seeds up into individual seeds
    // Note: Matches any sort of newline (unix/mac/dos), but won't get empty
    // lines, which is fine for this purpose

    Set<String> seedSet = new HashSet<String>();
    for (String seed : seeds.split("[\n\r]+")) {
        seedSet.add(seed);
    }

    HTMLUtils.forwardOnEmptyParameter(context, Constants.ORDER_TEMPLATE_PARAM);
    String orderTemplate = request.getParameter(Constants.ORDER_TEMPLATE_PARAM);
    // Check that order template exists
    if (!TemplateDAO.getInstance().exists(orderTemplate)) {
        HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;harvest.template.0.does.not.exist",
                orderTemplate);
        throw new ForwardedToErrorPage("The orderTemplate with name '" + orderTemplate + "' does not exist!");
    }

    // Check that numerical parameters are meaningful and replace null or
    // empty with default values
    long maxBytes = HTMLUtils.parseOptionalLong(context, Constants.MAX_BYTES_PARAM,
            dk.netarkivet.harvester.datamodel.Constants.DEFAULT_MAX_BYTES);
    long maxObjectsL = HTMLUtils.parseOptionalLong(context, Constants.MAX_OBJECTS_PARAM,
            dk.netarkivet.harvester.datamodel.Constants.DEFAULT_MAX_OBJECTS);
    int maxObjects = (int) maxObjectsL;
    // All parameters are valid, so call method
    try {
        PartialHarvest eventHarvest = (PartialHarvest) HarvestDefinitionDAO.getInstance()
                .getHarvestDefinition(eventHarvestName);
        eventHarvest.addSeeds(seedSet, orderTemplate, maxBytes, maxObjects);
    } catch (Exception e) {
        HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;error.adding.seeds.to.0", eventHarvestName,
                e);
        throw new ForwardedToErrorPage("Error while adding seeds", e);
    }
}

From source file:net.ontopia.topicmaps.webed.impl.utils.TagUtils.java

/**
 * Gets the action registry object from application scope.
 *//*from  w  w w  .  j  a v a  2 s .c  o  m*/
public static ActionRegistryIF getActionRegistry(PageContext pageContext) throws JspTagException {

    return getActionRegistry(pageContext.getRequest());
}

From source file:net.ontopia.topicmaps.webed.impl.utils.TagUtils.java

public static boolean isComponentReadOnly(PageContext pageContext, String compReadOnlyAttr) {
    ServletRequest request = pageContext.getRequest();
    if (compReadOnlyAttr == null)
        return isFormReadOnly(request);
    else if (compReadOnlyAttr.equals("false"))
        return false;
    else if (isFormReadOnly(request))
        return true;
    else/* w w  w  .  java 2 s .co m*/
        return InteractionELSupport.getBooleanValue(compReadOnlyAttr, false, pageContext);
}

From source file:dk.netarkivet.harvester.webinterface.DomainDefinition.java

/**
 * Extracts all required parameters from the request, checks for any inconsistencies, and passes the requisite data
 * to the updateDomain method for processing.
 * <p>//from   w  ww  .j  a v  a2s . c  o m
 * For reference, the parameters for this page look something like
 * http://localhost:8076/HarvestDefinition/Definitions-edit-domain.jsp?
 * update=1&name=netarkivet.dk&default=defaultconfig&configName=&order_xml=&
 * load=&maxObjects=&urlListName=&seedList=+&passwordName=&passwordDomain=& passwordRealm=&userName=&password=&
 * crawlertraps=%2Fcgi-bin%2F*%0D%0A%2Ftrap%2F*%0D%0A
 * <p>
 * update: This method throws an exception if update is not set
 * <p>
 * name: must be the name of a known domain
 * <p>
 * comments: optional user-entered comments about the domain
 * <p>
 * default: the defaultconfig is set to this value. Must be non-null and a known configuration of this domain.
 * <p>
 * crawlertraps: a newline-separated list of urls to be ignored. May be empty or null
 * <p>
 * alias: If set, this domain is an alias of the set domain renewAlias: If set, the alias date should be renewed
 *
 * @param context The context of this request
 * @param i18n I18n information
 * @throws IOFailure on updateerrors in the DAO
 * @throws ForwardedToErrorPage if domain is not found, if the edition is out-of-date, or if parameters are missing
 * or invalid
 */
public static void processRequest(PageContext context, I18n i18n) {
    ArgumentNotValid.checkNotNull(context, "PageContext context");
    ArgumentNotValid.checkNotNull(i18n, "I18n i18n");

    HTMLUtils.forwardOnEmptyParameter(context, Constants.DOMAIN_PARAM, Constants.DEFAULT_PARAM);
    ServletRequest request = context.getRequest();
    String name = request.getParameter(Constants.DOMAIN_PARAM).trim();

    if (!DomainDAO.getInstance().exists(name)) {
        HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;unknown.domain.0", name);
        throw new ForwardedToErrorPage("Unknown domain '" + name + "'");
    }
    Domain domain = DomainDAO.getInstance().read(name);

    // check the edition number before updating
    long edition = HTMLUtils.parseOptionalLong(context, Constants.EDITION_PARAM, -1L);

    if (domain.getEdition() != edition) {
        HTMLUtils.forwardWithRawErrorMessage(context, i18n, "errormsg;domain.definition.changed.0.retry.1",
                "<br/><a href=\"Definitions-edit-domain.jsp?" + Constants.DOMAIN_PARAM + "="
                        + HTMLUtils.escapeHtmlValues(HTMLUtils.encode(name)) + "\">",
                "</a>");
        throw new ForwardedToErrorPage("Domain '" + name + "' has changed");
    }

    // default configuration
    String defaultConf = request.getParameter(Constants.DEFAULT_PARAM);
    if (!domain.hasConfiguration(defaultConf)) {
        HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;unknown.default.configuration.0.for.1",
                defaultConf, name);
        throw new ForwardedToErrorPage("Unknown default configuration '" + defaultConf + "'");
    }

    String crawlertraps = request.getParameter(Constants.CRAWLERTRAPS_PARAM);
    if (crawlertraps == null) {
        crawlertraps = "";
    }
    String comments = request.getParameter(Constants.COMMENTS_PARAM);
    if (comments == null) {
        comments = "";
    }
    String alias = request.getParameter(Constants.ALIAS_PARAM);
    if (alias == null) {
        alias = "";
    }

    String aliasRenew = request.getParameter(Constants.RENEW_ALIAS_PARAM);
    if (aliasRenew == null) {
        aliasRenew = "no";
    }

    boolean renewAlias = aliasRenew.equals("yes");

    ExtendedFieldValueDefinition.processRequest(context, i18n, domain, ExtendedFieldTypes.DOMAIN);

    updateDomain(domain, defaultConf, crawlertraps, comments, alias, renewAlias);
}

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

/**
 * Increments a "persistent" counter. These counters are used by column tags
 * to track and increment values across column render passes.
 * @param ctx active PageContext/* w ww.  j a v a2 s .  com*/
 * @param name name of counter
 * @return next value
 */
public static Long incrementPersistentCounter(PageContext ctx, String name) {
    Long counter = (Long) ctx.getRequest().getAttribute(name);
    if (counter == null) {
        counter = new Long(1);
    } else {
        counter = new Long(counter.longValue() + 1);
    }
    ctx.getRequest().setAttribute(name, counter);
    return counter;
}

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

/**
 * Extract the name of the replica (parameter Constants.BITARCHIVE_NAME_PARAM) and the type of update requested
 * (parameter Constants.UPDATE_TYPE_PARAM). The latter is set to to Constants.FIND_MISSING_FILES_OPTION if the
 * request is to update missing files, or to Constants.CHECKSUM_OPTION if the request is to update the checksum
 * information.//  ww  w . java  2  s . c  o m
 *
 * @param context the current JSP context
 * @return an I18N string telling which type of update has just been initiated.
 * @throws ForwardedToErrorPage if an unknown bitarchive or update type is posted, or one of the two required
 * parameters are missing.
 * @throws ArgumentNotValid If the context is null.
 */
public static String processUpdateRequest(PageContext context) throws ArgumentNotValid, ForwardedToErrorPage {
    ArgumentNotValid.checkNotNull(context, "PageContext context");
    ServletRequest request = context.getRequest();

    String bitarchiveName = request.getParameter(Constants.BITARCHIVE_NAME_PARAM);
    if (bitarchiveName == null) {
        HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;missing.parameter.0",
                Constants.BITARCHIVE_NAME_PARAM);

        throw new ForwardedToErrorPage("Parameter '" + Constants.BITARCHIVE_NAME_PARAM + "' not set");
    }

    String updateTypeRequested = request.getParameter(Constants.UPDATE_TYPE_PARAM);
    if (updateTypeRequested == null) {
        HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;missing.parameter.0",
                Constants.UPDATE_TYPE_PARAM);

        throw new ForwardedToErrorPage("Parameter '" + Constants.UPDATE_TYPE_PARAM + "' not set");
    }

    if (!Replica.isKnownReplicaName(bitarchiveName)) {
        HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;unknown.bitarchive.0", bitarchiveName);
        throw new ForwardedToErrorPage("Unknown replica: " + bitarchiveName);
    }

    Replica bitarchive = Replica.getReplicaFromName(bitarchiveName);

    Locale l = context.getResponse().getLocale();
    String statusmessage = HTMLUtils.escapeHtmlValues(
            I18N.getString(l, "initiating;update.of.0.for.replica.1", updateTypeRequested, bitarchiveName));
    if (updateTypeRequested.equalsIgnoreCase(Constants.FIND_MISSING_FILES_OPTION)) {
        // Start new thread for findmissing files action.
        new BitpreservationUpdateThread(bitarchive, BitpreservationUpdateType.FINDMISSING).start();
        return statusmessage;

    } else if (updateTypeRequested.equalsIgnoreCase(Constants.CHECKSUM_OPTION)) {
        // Start new thread for finding corrupt files action.
        new BitpreservationUpdateThread(bitarchive, BitpreservationUpdateType.CHECKSUM).start();
        return statusmessage;
    } else {
        HTMLUtils.forwardWithErrorMessage(context, I18N, "errormsg;unknown.filestatus.update.type.0",
                updateTypeRequested);
        throw new ForwardedToErrorPage("Unknown filestatus update type: " + bitarchiveName);
    }
}

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

/**
 * Includes arbitrary _local_ url as content
 * @param ctx caller's page context//from   w  w  w. j  av a 2s . c o  m
 * @param url local url
 * @throws JspException if something goes wrong
 *
 * Note: Local means Urls in the same application
 */
public static void includeContent(PageContext ctx, String url) throws JspException {
    HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
    HttpServletResponse response = (HttpServletResponse) ctx.getResponse();
    RequestDispatcher rd = request.getSession(true).getServletContext().getRequestDispatcher(url);
    if (rd == null) {
        ListTagUtil.write(ctx, "<!-- " + url + " not found -->");
    } else {
        try {
            BufferedResponseWrapper wrapper = new BufferedResponseWrapper(response);
            rd.include(request, wrapper);
            wrapper.flush();
            ListTagUtil.write(ctx, wrapper.getBufferedOutput());
        } catch (Exception e) {
            throw new JspException(e);
        }
    }
}

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

/**
 * Processes a checksum request.//w w w . ja v a2s  .c o  m
 * <p>
 * The name of a bitarchive must always be given in parameter Constants.BITARCHIVE_NAME_PARAM.
 * <p>
 * If parameter Constants.FILENAME_PARAM is given, file info for that file will be returned, and all actions will
 * work on that file.
 * <p>
 * If parameter Constants.FIX_ADMIN_CHECKSUM_PARAM is given, the admin data checksum will be fixed for the file.
 * <p>
 * If parameter Constants.CREDENTIALS and Constants.CHECKSUM_PARAM is given, removes and reuploads a file with that
 * checksum in the given bitarchive, using the credentials for authorisation.
 *
 * @param res the result object. This is updated with result information, and expected to be printed to the
 * resulting page.
 * @param context the current JSP pagecontext.
 * @return The file preservation state for a file, if a filename is given in the request. Null otherwise.
 * @throws ArgumentNotValid If the context or res is null.
 */
public static PreservationState processChecksumRequest(StringBuilder res, PageContext context)
        throws ArgumentNotValid {
    ArgumentNotValid.checkNotNull(res, "StringBuilder res");
    ArgumentNotValid.checkNotNull(context, "PageContext context");
    ServletRequest request = context.getRequest();
    Locale l = context.getResponse().getLocale();
    HTMLUtils.forwardOnIllegalParameter(context, Constants.BITARCHIVE_NAME_PARAM, Replica.getKnownNames());
    String bitarchiveName = request.getParameter(Constants.BITARCHIVE_NAME_PARAM);
    Replica bitarchive = Replica.getReplicaFromName(bitarchiveName);
    String filename = request.getParameter(Constants.FILENAME_PARAM);
    String fixadminchecksum = request.getParameter(Constants.FIX_ADMIN_CHECKSUM_PARAM);
    String credentials = request.getParameter(Constants.CREDENTIALS_PARAM);
    String checksum = request.getParameter(Constants.CHECKSUM_PARAM);

    // Parameter validation. Get filename. Complain about missing filename
    // if we are trying to do actions.
    if (filename == null) { // param "file" not set - no action to take
        if (fixadminchecksum != null || credentials != null || checksum != null) {
            // Only if an action was intended do we complain about
            // a missing file.
            res.append(I18N.getString(l, "errormsg;lack.name.for.file.to.be.corrected.in.0", bitarchiveName));
        }
        return null;
    }

    // At this point we know that the parameter filename is given.
    // Now we check for actions.
    ActiveBitPreservation preserve = ActiveBitPreservationFactory.getInstance();
    if (fixadminchecksum != null) {
        // Action to fix admin.data checksum.
        preserve.changeStateForAdminData(filename);
        res.append(I18N.getString(l, "file.0.now.has.correct.checksum.in.admin.data", filename));
        res.append("<br/>");
    } else if (checksum != null || credentials != null) {
        // Action to replace a broken file with a correct file.
        // Both parameters must be given.
        if (checksum == null) { // param CHECKSUM_PARAM not set
            res.append(I18N.getString(l, "errormsg;lack.checksum.for.corrupted.file.0", filename));
            res.append("<br/>");
        } else if (credentials == null) { // param CREDENTIALS_PARAM not set
            res.append(I18N.getString(l, "errormsg;lacking.privileges.to.correct.in.replica"));
            res.append("<br/>");
        } else {
            // Parameters are correct. Fix the file and report result.
            try {
                preserve.replaceChangedFile(bitarchive, filename, credentials, checksum);
                res.append(I18N.getString(l, "file.0.has.been.replaced.in.1", filename, bitarchive));
                res.append("<br/>");
            } catch (Exception e) {
                res.append(I18N.getString(l, "errormsg;attempt.at.restoring.0.in.replica" + ".at.1.failed",
                        filename, bitarchive));
                res.append("<br/>");
                res.append(e.getMessage());
                res.append("<br/>");
                log.warn("Attempt at restoring '" + filename + "' in bitarchive on replica '" + bitarchive
                        + "' failed", e);
            }
        }
    }

    return preserve.getPreservationState(filename);
}

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

/**
 * Processes a missingFiles request.//from  w  ww .j a  v a  2s .  co  m
 * <p>
 * Parameters of the form Constants.ADD_COMMAND=&lt;bitarchive&gt;##&lt;filename&gt; causes the file to be added to
 * that bitarchive, if it is missing.
 * <p>
 * Parameters of the form Constants.GET_INFO_COMMAND=&lt;filename&gt; causes checksums to be computed for the file
 * in all bitarchives and the information to be shown in the next update (notice that this information disappears
 * when the page is next reloaded).
 *
 * @param context the current JSP context.
 * @param res the result object. This is updated with result information, and expected to be printed to the
 * resulting page.
 * @return A map of info gathered for files as requested.
 * @throws ArgumentNotValid If the context or res is null.
 * @throws ForwardedToErrorPage if the commands have the wrong number of arguments.
 */
public static Map<String, PreservationState> processMissingRequest(PageContext context, StringBuilder res)
        throws ArgumentNotValid, ForwardedToErrorPage {
    ArgumentNotValid.checkNotNull(context, "PageContext context");
    ArgumentNotValid.checkNotNull(res, "StringBuilder res");
    Map<String, String[]> params = context.getRequest().getParameterMap();
    HTMLUtils.forwardOnMissingParameter(context, Constants.BITARCHIVE_NAME_PARAM);
    String bitarchiveName = params.get(Constants.BITARCHIVE_NAME_PARAM)[0];
    if (!Replica.isKnownReplicaName(bitarchiveName)) {
        List<String> names = new ArrayList<String>();
        HTMLUtils.forwardOnIllegalParameter(context, Constants.BITARCHIVE_NAME_PARAM,
                StringUtils.conjoin(", ", names.toArray(Replica.getKnownNames())));
    }
    ActiveBitPreservation preserve = ActiveBitPreservationFactory.getInstance();
    Locale l = context.getResponse().getLocale();
    if (params.containsKey(Constants.ADD_COMMAND)) {
        String[] adds = params.get(Constants.ADD_COMMAND);
        for (String s : adds) {
            String[] parts = s.split(Constants.STRING_FILENAME_SEPARATOR);
            checkArgs(context, parts, Constants.ADD_COMMAND, "bitarchive name", "filename");
            final Replica ba = Replica.getReplicaFromName(parts[0]);
            final String filename = parts[1];
            try {
                preserve.uploadMissingFiles(ba, filename);
                res.append(HTMLUtils.escapeHtmlValues(
                        I18N.getString(l, "file.0.has.been.restored.in.replica.on.1", filename, ba.getName())));
                res.append("<br/>");
            } catch (Exception e) {
                res.append(I18N.getString(l, "errormsg;attempt.at.restoring.0.in.replica" + ".at.1.failed",
                        filename, ba));
                res.append("<br/>");
                res.append(e.getMessage());
                res.append("<br/>");
                log.warn("Could not restore file '" + filename + "' in bitarchive '" + ba + "'", e);
            }
        }
    }
    // A map ([filename] -> [preservationstate]) to contain
    // preservationstates for all files retrieved from the
    // parameter Constants.GET_INFO_COMMAND.
    // This map is an empty map, if this parameter is undefined.
    Map<String, PreservationState> infoMap;
    // Do this at the end so that the info reflects the current state.
    if (params.containsKey(Constants.GET_INFO_COMMAND)) {
        String[] getInfos = params.get(Constants.GET_INFO_COMMAND);
        infoMap = preserve.getPreservationStateMap(getInfos);
    } else {
        infoMap = new HashMap<String, PreservationState>();
    }

    return infoMap;
}

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  w w w.  j  av  a 2s .  c  o  m
public static void generateHeader(PageContext context) 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);
}