Example usage for javax.servlet RequestDispatcher FORWARD_REQUEST_URI

List of usage examples for javax.servlet RequestDispatcher FORWARD_REQUEST_URI

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher FORWARD_REQUEST_URI.

Prototype

String FORWARD_REQUEST_URI

To view the source code for javax.servlet RequestDispatcher FORWARD_REQUEST_URI.

Click Source Link

Document

The name of the request attribute under which the original request URI is made available to the target of a #forward(ServletRequest,ServletResponse) forward

Usage

From source file:org.dd4t.core.util.HttpUtils.java

public static String getOriginalUri(final HttpServletRequest request) {
    String orgUri = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);

    if (StringUtils.isNotEmpty(orgUri)) {
        return orgUri;
    } else {//from ww  w . j  a  va  2  s  .  co m
        return request.getRequestURI();
    }
}

From source file:com.miserablemind.butter.apps.butterApp.controller.error.HTTPErrorController.java

/**
 * @param request HTTP request to handle
 * @return never gets to return value. Always throws an exception.
 * @throws com.miserablemind.butter.apps.butterApp.exception.HTTPNotFoundException a 404 Exception that gets handled by {@link com.miserablemind.butter.apps.butterApp.controller.ControllerExceptionHandler}
 *//*from  ww  w  .  j  a  v  a  2 s  .c o  m*/
@RequestMapping(method = RequestMethod.GET, value = "/404")
public String handle404(HttpServletRequest request) throws HTTPNotFoundException {
    String originalUrl = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    throw new HTTPNotFoundException("URL: " + originalUrl);
}

From source file:com.miserablemind.butter.apps.butterApp.controller.error.HTTPErrorController.java

/**
 * @param request HTTP request to handle
 * @return never gets to return value. Always throws an exception.
 * @throws com.miserablemind.butter.apps.butterApp.exception.HTTPBadRequestException a 400 Exception that gets handled by {@link com.miserablemind.butter.apps.butterApp.controller.ControllerExceptionHandler}
 *///from   w  w  w . ja v  a2 s.  c  o m
@RequestMapping(method = RequestMethod.GET, value = "/400")
public String handle400(HttpServletRequest request) throws HTTPBadRequestException {
    String originalUrl = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    throw new HTTPBadRequestException("URL: " + originalUrl);
}

From source file:com.miserablemind.butter.apps.butterApp.controller.error.HTTPErrorController.java

/**
 * @param request HTTP request to handle
 * @return never gets to return value. Always throws an exception.
 * @throws com.miserablemind.butter.apps.butterApp.exception.HTTPInternalServerErrorException a 500 Exception that gets handled by {@link com.miserablemind.butter.apps.butterApp.controller.ControllerExceptionHandler}
 *///from  w  ww . j  a  v a  2  s. co  m
@RequestMapping(method = RequestMethod.GET, value = "/500")
public String handle500(HttpServletRequest request) throws HTTPInternalServerErrorException {
    String originalUrl = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    throw new HTTPInternalServerErrorException("URL: " + originalUrl);
}

From source file:com.hp.autonomy.frontend.find.core.web.ControllerUtilsImpl.java

private String getBaseUrl(final HttpServletRequest request) {
    final String originalUri = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    final String requestUri = originalUri != null ? originalUri : request.getRequestURI();
    final String path = requestUri.replaceFirst(request.getContextPath(), "");
    final int depth = StringUtils.countMatches(path, "/") - 1;

    return depth <= 0 ? "." : StringUtils.repeat("../", depth);
}

From source file:com.fluidops.iwb.server.HybridSearchServlet.java

/**
 * Retrieve the query from request, do the token based security check and
 * evaluate the query.//  w ww. j a  v  a2s  .co m
 * 
 * @param req
 * @param resp
 * @throws IOException, ServletException 
 */
protected void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // register search page
    String uri = null;
    if (req.getDispatcherType() == DispatcherType.FORWARD)
        uri = (String) req.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    else
        uri = req.getRequestURI();

    // Done to avoid processing of a request from TimelineWidget.
    if (uri.endsWith("__history__.html")) {
        return;
    }

    FSession.registerPage(uri, FPage.class);

    FSession.removePage(req);

    // get session and page
    FSession session = FSession.getSession(req);
    FPage page;
    try {
        page = (FPage) session.getComponentById(uri, req);
    } catch (Exception e) {
        log.warn("Could not get the page for request: " + uri, e);
        resp.sendRedirect(RedirectService.getRedirectURL(RedirectType.PAGE_NOT_FOUND, req));
        return;
    }

    SearchPageContext pc = getPageContext();

    // register FPage
    pc.page = page;
    pc.session = session;

    // get and decode query
    pc.query = getQueryFromRequest(req);
    if (pc.query == null) {
        // use empty query if no query is given
        pc.query = "";
    }

    pc.query = pc.query.trim();
    PageContext.setThreadPageContext(pc);

    List<String> queryTargets = SearchProviderFactory.getDefaultQueryTargets();

    String[] vals;
    if ((vals = req.getParameterValues("queryTarget")) != null && (vals.length > 0)) {
        queryTargets = Lists.newArrayList(vals);
    }

    SparqlQueryType qt = null;

    // Currently, the special query language protocol can be passed in two ways:
    // - as a prefix to the query: e.g., "sql:".
    // - as a request parameter "queryLanguage".
    // If no query language is given explicitly, then the default routine is performed:
    // First, we check that the query is a valid SPARQL query and then, if it is not the case, it is interpreted as a 
    // keyword query.
    pc.queryLanguage = determineQueryLanguage(pc.query, req);

    // If the query language was provided as a prefix, we no longer need the prefix
    if (!pc.queryLanguage.equals("DEFAULT")
            && pc.query.toUpperCase().startsWith(pc.queryLanguage.toUpperCase() + ":")) {
        pc.query = pc.query.substring(pc.queryLanguage.length() + 1).trim();
    }

    if (pc.queryLanguage.equals("SPARQL") || pc.queryLanguage.equals("DEFAULT")) {
        try {
            qt = ReadDataManagerImpl.getSparqlQueryType(pc.query, true);
            // We managed to parse it as SPARQL, so it's SPARQL anyway.
            pc.queryLanguage = "SPARQL";
            // since ASK queries are used in bigowlim for several control functionalities
            // we do not want to support them right now. Same for UPDATE
            if (qt == SparqlQueryType.ASK || qt == SparqlQueryType.UPDATE) {
                error(resp, 403, "Not allowed to execute ASK or UPDATE queries.");
                return;
            }
        } catch (MalformedQueryException e) {
            // if the SPARQL prefix was provided explicitly: throw an error 
            if (pc.queryLanguage.equals("SPARQL")) {
                error(resp, 400, "Malformed query:\n\n" + pc.query + "\n\n" + e.getMessage());
                return;
            }
            // ignore: not a valid SPARQL query, treat it as keyword query
        }
    }

    //////////////////SECURITY CHECK/////////////////////////
    // remarks:
    // queries are checked, keywords and invalid queries are always allowed
    String securityToken = req.getParameter("st");
    if (!EndpointImpl.api().getUserManager().hasQueryPrivileges(pc.query, qt, securityToken)) {
        error(resp, 403, "Not enough rights to execute query.");
        return;
    }

    // value to be used in queries instead of ??
    String _resolveValue = req.getParameter("value");
    Value resolveValue = _resolveValue != null ? ValueFactoryImpl.getInstance().createURI(_resolveValue) : null;

    boolean infer = false; // default value for inferencing is false

    if (req.getParameter("infer") != null)
        infer = Boolean.parseBoolean(req.getParameter("infer"));

    pc.infer = infer;

    List<ErrorRecord> errorRecords = Lists.newArrayListWithCapacity(queryTargets.size());

    // empty query --> empty result
    if (pc.query.isEmpty()) {
        pc.queryLanguage = "KEYWORD";
        pc.queryType = "KEYWORD";

        try {
            pc.queryResult = new MutableTupleQueryResultImpl(new TupleQueryResultImpl(
                    Collections.<String>emptyList(), Collections.<BindingSet>emptyList().iterator()));
        } catch (QueryEvaluationException e) {
            log.warn("Could not produce a mutable tuple query result");
            log.debug("Details: ", e);
        }
    }
    // allowed SPARQL queries
    else if (pc.queryLanguage.equals("SPARQL")) {
        pc.queryType = qt.toString();

        QueryResult<?> queryRes = null;

        List<SparqlSearchProvider> sparqlProviders = SearchProviderFactory.getInstance()
                .getSparqlSearchProviders(queryTargets);

        for (SparqlSearchProvider sparqlProvider : sparqlProviders) {

            try {
                QueryResult<?> currentQueryRes = sparqlProvider.search(pc.query, qt, resolveValue, infer);
                queryRes = ReadDataManagerImpl.mergeQueryResults(queryRes, currentQueryRes);
            } catch (MalformedQueryException e) {
                // If a SPARQL query is malformed, no need to send it to all search providers
                error(resp, 400, e.getMessage());
                return;
            } catch (Exception e) {
                errorRecords.add(createErrorRecord(e, sparqlProvider, pc));
            }

        }

        if (queryRes == null) {
            if (qt == SparqlQueryType.CONSTRUCT) {
                queryRes = new GraphQueryResultImpl(
                        EndpointImpl.api().getNamespaceService().getRegisteredNamespacePrefixes(),
                        Collections.<Statement>emptyList());
            } else {
                queryRes = new MutableTupleQueryResultImpl(Lists.newArrayList("Results"),
                        Collections.<BindingSet>emptyList());
            }
        }
        pc.queryResult = queryRes;

    }
    // query with a pre-defined custom protocol
    else if (!pc.queryLanguage.equals("DEFAULT")) {
        pc.queryType = "KEYWORD";

        QueryResult<?> queryRes = null;

        List<SearchProvider> providers = SearchProviderFactory.getInstance()
                .getSearchProvidersSupportingQueryLanguage(queryTargets, pc.queryLanguage);

        QueryResult<?> currentQueryResult;

        for (SearchProvider provider : providers) {
            // If the query protocol was provided, we assume that the target knows how to deal with it.
            try {
                currentQueryResult = provider.search(pc.queryLanguage, pc.query);
                queryRes = ReadDataManagerImpl.mergeQueryResults(queryRes, currentQueryResult);
            } catch (Exception e) {
                errorRecords.add(createErrorRecord(e, provider, pc));
            }
        }

        pc.queryResult = (queryRes != null) ? queryRes : createEmptyKeywordQueryResult();

    }
    // keyword query
    else {

        try {
            handleKeywordQuery(pc, queryTargets);

        } catch (ParseException e) {
            error(resp, 400, "Malformed keyword query:\n\n" + pc.query + "\n\n" + e.getMessage());
        } catch (SearchException e) {
            errorRecords.add(createErrorRecord(e, pc));
        }
    }

    resp.setStatus(HttpServletResponse.SC_OK);

    // calculate facets
    // legacy code faceted search, currently not active
    //         String facetsAsString = "";
    //         if (Config.getConfig().getFacetedSearch().equals("standard")) 
    //         {
    //            FacetCalculator facetter = new FacetCalculator( pc );
    //            FContainer facetContainer = facetter.getFacetContainer();
    //            page.register(facetContainer);
    //            facetsAsString = facetContainer.htmlAnchor().toString();
    //            facetContainer.drawAdvHeader(true);
    //            facetContainer.drawHeader(false);
    //         }

    // page title
    pc.title = (pc.queryLanguage.equals("SPARQL") && !pc.queryType.equals("KEYWORD") || pc.query.isEmpty())
            ? "Search result"
            : "Search result: " + StringEscapeUtils.escapeHtml(pc.query);

    // TODO: activeLabel

    // select widgets to display search results
    selectWidgets(pc, infer);

    // layout result page
    populateContainer(pc, errorRecords);

    // print response
    EndpointImpl.api().getPrinter().print(pc, resp);
}

From source file:no.kantega.commons.util.URLHelper.java

/**
 * Returns the actual URL requested by the client
 * @param request//from w w  w .j  av a2  s. c om
 * @return String URL requested by client
 */
public static String getRequestedUrl(HttpServletRequest request) {
    StringBuilder urlBuilder = new StringBuilder(getServerURL(request));

    // URI
    urlBuilder.append(request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI));

    // Query params
    if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
        urlBuilder.append("?").append(request.getQueryString());
    }

    return urlBuilder.toString();
}

From source file:org.cyk.ui.web.api.WebNavigationManager.java

public String getRequestUrl(HttpServletRequest request) {
    String url, path = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    if (path == null) {
        url = request.getRequestURL().toString();
        if (StringUtils.isNotEmpty(request.getQueryString()))
            url += Constant.CHARACTER_QUESTION_MARK + request.getQueryString();
    } else {/*  w w  w .ja  v  a 2  s. c o m*/
        url = request.getScheme() + Constant.CHARACTER_COLON + Constant.CHARACTER_SLASH
                + Constant.CHARACTER_SLASH + request.getServerName() + Constant.CHARACTER_COLON
                + request.getServerPort() + path;
    }

    //if(StringUtils.isNotEmpty(PrettyContext.getCurrentInstance().getRequestQueryString().toQueryString()))
    //   url += NavigationHelper.QUERY_START+PrettyContext.getCurrentInstance().getRequestQueryString().toQueryString();
    return url;
}

From source file:org.ireland.jnetty.webapp.RequestDispatcherImpl.java

private void doForward(HttpServletRequest request, HttpServletResponse response, HttpInvocation invocation)
        throws ServletException, IOException {

    // Reset any output that has been buffered, but keep headers/cookies
    response.resetBuffer(); // Servlet-3_1-PFD 9.4

    //Wrap the request
    ForwardRequest wrequest = new ForwardRequest(request, response, invocation);

    // If we have already been forwarded previously, then keep using the established
    // original value. Otherwise, this is the first forward and we need to establish the values.
    // Note: the established value on the original request for pathInfo and
    // for queryString is allowed to be null, but cannot be null for the other values.
    if (request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI) == null) {
        // ??,/*from   w w w . j  ava 2 s  .  c om*/
        wrequest.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, request.getRequestURI());

        wrequest.setAttribute(RequestDispatcher.FORWARD_CONTEXT_PATH, request.getContextPath());
        wrequest.setAttribute(RequestDispatcher.FORWARD_SERVLET_PATH, request.getServletPath());
        wrequest.setAttribute(RequestDispatcher.FORWARD_PATH_INFO, request.getPathInfo());
        wrequest.setAttribute(RequestDispatcher.FORWARD_QUERY_STRING, request.getQueryString());
    }

    boolean isValid = false;

    try {

        invocation.getFilterChainInvocation().service(wrequest, response);

        isValid = true;
    } finally {
        if (request.getAsyncContext() != null) {
            // An async request was started during the forward, don't close the
            // response as it may be written to during the async handling
            return;
        }

        // server/106r, ioc/0310
        if (isValid) {
            finishResponse(response);
        }
    }
}