Search in sources :

Example 86 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project ofbiz-framework by apache.

the class SeoContextFilter method doFilter.

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String uri = httpRequest.getRequestURI();
    boolean forwarded = forwardUri(httpResponse, uri);
    if (forwarded) {
        return;
    }
    URL controllerConfigURL = ConfigXMLReader.getControllerConfigURL(config.getServletContext());
    ControllerConfig controllerConfig = null;
    Map<String, ConfigXMLReader.RequestMap> requestMaps = null;
    try {
        controllerConfig = ConfigXMLReader.getControllerConfig(controllerConfigURL);
        requestMaps = controllerConfig.getRequestMapMap();
    } catch (WebAppConfigurationException e) {
        Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
        throw new ServletException(e);
    }
    Set<String> uris = requestMaps.keySet();
    // test to see if we have come through the control servlet already, if not do the processing
    String requestPath = null;
    String contextUri = null;
    if (httpRequest.getAttribute(ControlFilter.FORWARDED_FROM_SERVLET) == null) {
        requestPath = httpRequest.getServletPath();
        if (requestPath == null)
            requestPath = "";
        if (requestPath.lastIndexOf('/') > 0) {
            if (requestPath.indexOf('/') == 0) {
                requestPath = '/' + requestPath.substring(1, requestPath.indexOf('/', 1));
            } else {
                requestPath = requestPath.substring(1, requestPath.indexOf('/'));
            }
        }
        String requestInfo = httpRequest.getServletPath();
        if (requestInfo == null)
            requestInfo = "";
        if (requestInfo.lastIndexOf('/') >= 0) {
            requestInfo = requestInfo.substring(0, requestInfo.lastIndexOf('/')) + "/*";
        }
        StringBuilder contextUriBuffer = new StringBuilder();
        if (httpRequest.getContextPath() != null) {
            contextUriBuffer.append(httpRequest.getContextPath());
        }
        if (httpRequest.getServletPath() != null) {
            contextUriBuffer.append(httpRequest.getServletPath());
        }
        if (httpRequest.getPathInfo() != null) {
            contextUriBuffer.append(httpRequest.getPathInfo());
        }
        contextUri = contextUriBuffer.toString();
        List<String> pathItemList = StringUtil.split(httpRequest.getPathInfo(), "/");
        String viewName = "";
        if (pathItemList != null) {
            viewName = pathItemList.get(0);
        }
        String requestUri = UtilHttp.getRequestUriFromTarget(httpRequest.getRequestURI());
        // check to make sure the requested url is allowed
        if (!allowedPathList.contains(requestPath) && !allowedPathList.contains(requestInfo) && !allowedPathList.contains(httpRequest.getServletPath()) && !allowedPathList.contains(requestUri) && !allowedPathList.contains("/" + viewName) && (UtilValidate.isEmpty(requestPath) && UtilValidate.isEmpty(httpRequest.getServletPath()) && !uris.contains(viewName))) {
            String filterMessage = "[Filtered request]: " + contextUri;
            if (redirectPath == null) {
                if (UtilValidate.isEmpty(viewName)) {
                    // redirect without any url change in browser
                    RequestDispatcher rd = request.getRequestDispatcher(SeoControlServlet.getDefaultPage());
                    rd.forward(request, response);
                } else {
                    int error = 404;
                    if (UtilValidate.isNotEmpty(errorCode)) {
                        try {
                            error = Integer.parseInt(errorCode);
                        } catch (NumberFormatException nfe) {
                            Debug.logWarning(nfe, "Error code specified would not parse to Integer : " + errorCode, module);
                        }
                    }
                    filterMessage = filterMessage + " (" + error + ")";
                    httpResponse.sendError(error, contextUri);
                    request.setAttribute("filterRequestUriError", contextUri);
                }
            } else {
                filterMessage = filterMessage + " (" + redirectPath + ")";
                if (!redirectPath.toLowerCase(Locale.getDefault()).startsWith("http")) {
                    redirectPath = httpRequest.getContextPath() + redirectPath;
                }
                // httpResponse.sendRedirect(redirectPath);
                if ("".equals(uri) || "/".equals(uri)) {
                    // redirect without any url change in browser
                    RequestDispatcher rd = request.getRequestDispatcher(redirectPath);
                    rd.forward(request, response);
                } else {
                    // redirect with url change in browser
                    httpResponse.setStatus(SeoConfigUtil.getDefaultResponseCode());
                    httpResponse.setHeader("Location", redirectPath);
                }
            }
            Debug.logWarning(filterMessage, module);
            return;
        } else if ((allowedPathList.contains(requestPath) || allowedPathList.contains(requestInfo) || allowedPathList.contains(httpRequest.getServletPath()) || allowedPathList.contains(requestUri) || allowedPathList.contains("/" + viewName)) && !webServlets.contains(httpRequest.getServletPath())) {
            request.setAttribute(SeoControlServlet.REQUEST_IN_ALLOW_LIST, Boolean.TRUE);
        }
    }
    // we're done checking; continue on
    chain.doFilter(httpRequest, httpResponse);
}
Also used : ControllerConfig(org.apache.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) URL(java.net.URL) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException)

Example 87 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project ofbiz-framework by apache.

the class SeoContentUrlFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Delegator delegator = (Delegator) httpRequest.getSession().getServletContext().getAttribute("delegator");
    String urlContentId = null;
    String pathInfo = UtilHttp.getFullRequestUrl(httpRequest);
    if (UtilValidate.isNotEmpty(pathInfo)) {
        String alternativeUrl = pathInfo.substring(pathInfo.lastIndexOf('/'));
        if (alternativeUrl.endsWith("-content")) {
            try {
                List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView").where("drObjectInfo", alternativeUrl).queryList();
                if (contentDataResourceViews.size() > 0) {
                    contentDataResourceViews = EntityUtil.orderBy(contentDataResourceViews, UtilMisc.toList("createdDate DESC"));
                    GenericValue contentDataResourceView = EntityUtil.getFirst(contentDataResourceViews);
                    List<GenericValue> contents = EntityQuery.use(delegator).from("ContentAssoc").where("contentAssocTypeId", "ALTERNATIVE_URL", "contentIdTo", contentDataResourceView.getString("contentId")).filterByDate().queryList();
                    if (contents.size() > 0) {
                        GenericValue content = EntityUtil.getFirst(contents);
                        urlContentId = content.getString("contentId");
                    }
                }
            } catch (Exception e) {
                Debug.logWarning(e.getMessage(), module);
            }
        }
        if (UtilValidate.isNotEmpty(urlContentId)) {
            StringBuilder urlBuilder = new StringBuilder();
            if (UtilValidate.isNotEmpty(SeoControlServlet.getControlServlet())) {
                urlBuilder.append("/" + SeoControlServlet.getControlServlet());
            }
            urlBuilder.append("/" + config.getInitParameter("viewRequest") + "?contentId=" + urlContentId);
            // Set view query parameters
            UrlServletHelper.setViewQueryParameters(request, urlBuilder);
            Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module);
            RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString());
            dispatch.forward(request, response);
            return;
        }
        // Check path alias
        UrlServletHelper.checkPathAlias(request, httpResponse, delegator, pathInfo);
    }
    // we're done checking; continue on
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher)

Example 88 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project evosuite by EvoSuite.

the class HttpServletTest method testInitServlet.

@Test
public void testInitServlet() throws Exception {
    final String delegate = "/result.jsp";
    Assert.assertFalse(TestDataJavaEE.getInstance().getViewOfDispatchers().contains(delegate));
    HttpServlet servlet = new HttpServlet() {

        @Override
        public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(delegate);
            dispatcher.forward(req, resp);
        }
    };
    EvoHttpServletRequest req = new EvoHttpServletRequest();
    EvoHttpServletResponse resp = new EvoHttpServletResponse();
    try {
        servlet.service(req, resp);
        Assert.fail();
    } catch (IllegalStateException e) {
    // expected
    }
    EvoServletConfig conf = new EvoServletConfig();
    servlet.init(conf);
    try {
        servlet.service(req, resp);
        Assert.fail();
    } catch (NullPointerException e) {
    // expected
    }
    conf.createDispatcher(delegate);
    servlet.init(conf);
    servlet.service(req, resp);
    String body = resp.getBody();
    Assert.assertNotEquals(EvoHttpServletResponse.WARN_NO_COMMITTED, body);
    Assert.assertTrue(body.length() > 0);
    // the name of the delegate should appear in the response
    Assert.assertTrue(body.contains(delegate));
    Assert.assertTrue(TestDataJavaEE.getInstance().getViewOfDispatchers().contains(delegate));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServlet(javax.servlet.http.HttpServlet) EvoServletConfig(org.evosuite.runtime.javaee.javax.servlet.EvoServletConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestDispatcher(javax.servlet.RequestDispatcher) Test(org.junit.Test)

Example 89 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project acs-aem-commons by Adobe-Consulting-Services.

the class VanityURLServiceImpl method dispatch.

public boolean dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException, RepositoryException {
    if (request.getAttribute(VANITY_DISPATCH_CHECK_ATTR) != null) {
        log.trace("Processing a previously vanity dispatched request. Skipping...");
        return false;
    }
    request.setAttribute(VANITY_DISPATCH_CHECK_ATTR, true);
    final String requestURI = request.getRequestURI();
    final RequestPathInfo mappedPathInfo = new PathInfo(request.getResourceResolver(), requestURI);
    final String candidateVanity = mappedPathInfo.getResourcePath();
    final String pathScope = StringUtils.removeEnd(requestURI, candidateVanity);
    log.debug("Candidate vanity URL to check and dispatch: [ {} ]", candidateVanity);
    // 2) the candidate is in at least 1 sling:vanityPath under /content
    if (!StringUtils.equals(candidateVanity, requestURI) && isVanityPath(pathScope, candidateVanity, request)) {
        log.debug("Forwarding request to vanity resource [ {} ]", candidateVanity);
        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(candidateVanity);
        requestDispatcher.forward(new ExtensionlessRequestWrapper(request), response);
        return true;
    }
    return false;
}
Also used : RequestPathInfo(org.apache.sling.api.request.RequestPathInfo) PathInfo(com.day.cq.commons.PathInfo) RequestPathInfo(org.apache.sling.api.request.RequestPathInfo) RequestDispatcher(javax.servlet.RequestDispatcher)

Example 90 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project narayana by jbosstm.

the class TestServlet method doPost.

/**
 * Execute the test
 * @param request The HTTP servlet request.
 * @param response The HTTP servlet response.
 */
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    final String serviceURI = request.getParameter(TestConstants.PARAM_SERVICE_URI);
    final String test = request.getParameter(TestConstants.PARAM_TEST);
    final String testTimeoutValue = request.getParameter(TestConstants.PARAM_TEST_TIMEOUT);
    // final String asyncTestValue = request.getParameter(TestConstants.PARAM_ASYNC_TEST) ;
    String resultPageAddress = request.getParameter(TestConstants.PARAM_RESULT_PAGE);
    if (resultPageAddress == null || resultPageAddress.length() == 0) {
        resultPageAddress = TestConstants.DEFAULT_RESULT_PAGE_ADDRESS;
    }
    final int serviceURILength = (serviceURI == null ? 0 : serviceURI.length());
    final int testLength = (test == null ? 0 : test.length());
    long testTimeout = 0;
    boolean testTimeoutValid = false;
    if ((testTimeoutValue != null) && (testTimeoutValue.length() > 0)) {
        try {
            testTimeout = Long.parseLong(testTimeoutValue);
            testTimeoutValid = true;
        }// ignore
         catch (final NumberFormatException nfe) {
        }
    }
    // final boolean asyncTest = (asyncTestValue != null) ;
    final boolean asyncTest = true;
    if ((serviceURILength == 0) || (testLength == 0) || !testTimeoutValid) {
        final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/invalidParameters.html");
        dispatcher.forward(request, response);
        return;
    }
    final HttpSession session = request.getSession();
    final String id = session.getId();
    final int logCount = getLogCount(session);
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    final String date = format.format(new Date());
    final String logName = date + "-" + id + "-" + logCount;
    session.setAttribute(TestConstants.ATTRIBUTE_TEST_RESULT, null);
    session.setAttribute(TestConstants.ATTRIBUTE_TEST_VALIDATION, null);
    session.setAttribute(TestConstants.ATTRIBUTE_LOG_NAME, null);
    final String threadLog;
    try {
        final TestResult result = TestRunner.execute(serviceURI, testTimeout, asyncTest, test);
        if (result != null) {
            session.setAttribute(TestConstants.ATTRIBUTE_TEST_RESULT, result);
            threadLog = MessageLogging.getThreadLog();
            try {
                TestLogController.writeLog(logName, threadLog);
                session.setAttribute(TestConstants.ATTRIBUTE_LOG_NAME, logName);
            } catch (final IOException ioe) {
                log("Unexpected IOException writing message log", ioe);
            }
        } else {
            threadLog = null;
        }
    } finally {
        MessageLogging.clearThreadLog();
    }
    if ((threadLog != null) && (threadLog.length() > 0)) {
        try {
            final String testValidation = transform(threadLog);
            session.setAttribute(TestConstants.ATTRIBUTE_TEST_VALIDATION, testValidation);
        } catch (final Throwable th) {
            log("Unexpected throwable transforming message log", th);
        }
    }
    final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(resultPageAddress);
    dispatcher.forward(request, response);
}
Also used : HttpSession(javax.servlet.http.HttpSession) TestResult(junit.framework.TestResult) IOException(java.io.IOException) SimpleDateFormat(java.text.SimpleDateFormat) RequestDispatcher(javax.servlet.RequestDispatcher) Date(java.util.Date)

Aggregations

RequestDispatcher (javax.servlet.RequestDispatcher)354 ServletException (javax.servlet.ServletException)98 HttpSession (javax.servlet.http.HttpSession)97 IOException (java.io.IOException)74 HttpServletRequest (javax.servlet.http.HttpServletRequest)56 HttpServletResponse (javax.servlet.http.HttpServletResponse)44 SQLException (java.sql.SQLException)31 User (com.zyf.bean.User)28 ServletContext (javax.servlet.ServletContext)26 Properties (java.util.Properties)14 Test (org.junit.Test)14 RelatorioDAO (br.senac.tads3.pi03b.gruposete.dao.RelatorioDAO)13 RelatorioMudancas (br.senac.tads3.pi03b.gruposete.models.RelatorioMudancas)12 PrintWriter (java.io.PrintWriter)12 RequestDispatcherOptions (org.apache.sling.api.request.RequestDispatcherOptions)11 Resource (org.apache.sling.api.resource.Resource)11 ArrayList (java.util.ArrayList)9 Map (java.util.Map)9 GenericValue (org.apache.ofbiz.entity.GenericValue)9 WebUser (org.compiere.util.WebUser)9