Example usage for javax.servlet ServletRequest getServletContext

List of usage examples for javax.servlet ServletRequest getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;//from w w w. j  a  v a 2  s .c om
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:admin.controller.Layout.java

public String createImage(ServletRequest servletRequest, String layoutfilename, ServletContext servletContext,
        String modelname) throws SAXException {
    //        throw new UnsupportedOperationException("Not supported yet.");

    String uploadPath = AppConstants.BASE_XML_UPLOAD_PATH;
    try {/*from   w ww.j  a v  a2 s.c om*/
        StringBuffer htmldata = new StringBuffer();
        String backgroundimage, border_radius, margin_left, Blend_mode, margin_top, blend_mode, opacity, width,
                height, background_repeat, background_size;
        String textData, font_family, huerotate, font_weight, Drop_shadow_color, font_style, text_align,
                font_size, font_color, text_shadow, line_height, letter_spacing, webkit_transform, h_shadow,
                v_shadow, Blur, id, defaulttext;
        double grayscale, sepia, saturate, invert, brightness, contrast;

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        Document doc = docBuilder.parse(new File(uploadPath + File.separator + layoutfilename + ".xml"));
        Element docEle = doc.getDocumentElement();
        // normalize text representation
        doc.getDocumentElement().normalize();
        //            logger.log(Level.INFO, "Root element of the doc is " + doc.getDocumentElement().getNodeName());

        NodeList listOfModels = docEle.getElementsByTagName("element");
        NodeList listOfContent = docEle.getElementsByTagName("container");
        int totalModels = listOfModels.getLength();
        Node firstContentNode = listOfContent.item(0);
        Element modelElementContent = (Element) firstContentNode;
        String containerWidth = modelElementContent.getAttribute("Width");
        String containerHeight = modelElementContent.getAttribute("Height");
        logger.log(Level.INFO, "Total no of models : " + totalModels);

        for (int s = 0; s < listOfModels.getLength(); s++) {

            Node firstModelNode = listOfModels.item(s);
            Element modelElement = (Element) firstModelNode;

            logger.log(Level.INFO, modelElement.getAttribute("tag"));
            id = modelElement.getAttribute("type");
            if (modelElement.getAttribute("tag").equalsIgnoreCase("image")) {
                String filter = "";
                if (modelElement.getAttribute("filterEnable").equalsIgnoreCase("false")) {
                    h_shadow = modelElement.getAttribute("H-shadow");
                    v_shadow = modelElement.getAttribute("V-shadow");
                    Blur = modelElement.getAttribute("blur");
                    Drop_shadow_color = modelElement.getAttribute("Drop-shadow-color");
                    filter = "drop-shadow(" + Drop_shadow_color + " " + h_shadow + " " + v_shadow + " " + Blur
                            + ")";
                    logger.log(Level.INFO, filter);
                } else if (modelElement.getAttribute("blur").equalsIgnoreCase("undefined")) {
                    filter = "blur(0px) grayscale(0%) sepia(0%) saturate(100%) hue-rotate(0deg) invert(0%) brightness(100%) contrast(100%)";
                } else if (modelElement.getAttribute("filterEnable").equalsIgnoreCase("true")) {
                    Blur = modelElement.getAttribute("blur");
                    grayscale = (Double.parseDouble(modelElement.getAttribute("grayscale"))) * 100;
                    sepia = (Double.parseDouble(modelElement.getAttribute("sepia"))) * 100;
                    saturate = (Double.parseDouble(modelElement.getAttribute("saturate"))) * 100;
                    huerotate = modelElement.getAttribute("huerotate");
                    invert = (Double.parseDouble(modelElement.getAttribute("invert"))) * 100;
                    brightness = (Double.parseDouble(modelElement.getAttribute("brightness"))) * 100;
                    contrast = (Double.parseDouble(modelElement.getAttribute("contrast"))) * 100;

                    filter = "blur(" + Blur + ") grayscale(" + (int) grayscale + "%) sepia(" + (int) sepia
                            + "%) saturate(" + (int) saturate + "%) hue-rotate(" + huerotate + ") invert("
                            + (int) invert + "%) brightness(" + (int) brightness + "%) contrast("
                            + (int) contrast + "%)";
                    logger.log(Level.INFO, filter);
                }

                backgroundimage = modelElement.getAttribute("background-image");
                margin_left = modelElement.getAttribute("x-co-ordinates");
                margin_top = modelElement.getAttribute("y-co-ordinates");
                Blend_mode = modelElement.getAttribute("Blend");
                blend_mode = modelElement.getAttribute("blend-background-color");
                opacity = modelElement.getAttribute("opacity");
                width = modelElement.getAttribute("width");
                height = modelElement.getAttribute("height");
                background_repeat = "no-repeat";
                background_size = "contain";
                htmldata.append("<div id='" + id + "' style='position: absolute; width:" + width + "; height:"
                        + height + "; background-blend-mode:" + Blend_mode + "; background-color:" + blend_mode
                        + "; background-image:" + backgroundimage + "; margin-left:" + margin_left
                        + "px; margin-top:" + margin_top + "px; background-repeat:" + background_repeat
                        + "; background-position:" + "50% 50%" + "; -webkit-background-size:" + "cover"
                        + ";-webkit-filter:" + filter + ";  opacity:" + opacity + ";'></div>");
                logger.log(Level.INFO, htmldata.toString());
            } else if (modelElement.getAttribute("tag").equalsIgnoreCase("text")) {
                textData = modelElement.getAttribute("type");
                margin_left = modelElement.getAttribute("x-co-ordinates");
                margin_top = modelElement.getAttribute("y-co-ordinates");
                width = modelElement.getAttribute("width");
                height = modelElement.getAttribute("height");
                font_weight = modelElement.getAttribute("font-weight");
                font_style = modelElement.getAttribute("font-style");
                text_align = modelElement.getAttribute("text-align");
                font_family = modelElement.getAttribute("font-family").replace("+", " ");

                font_size = modelElement.getAttribute("font-size");
                font_color = modelElement.getAttribute("font-color");
                h_shadow = modelElement.getAttribute("H-shadow");
                v_shadow = modelElement.getAttribute("V-shadow");
                Blur = modelElement.getAttribute("Blur");
                text_shadow = modelElement.getAttribute("text-shadow");
                line_height = modelElement.getAttribute("line-height");
                letter_spacing = modelElement.getAttribute("letter-spacing");
                opacity = modelElement.getAttribute("opacity");
                webkit_transform = modelElement.getAttribute("webkit-transform");
                defaulttext = modelElement.getAttribute("defaulttext");
                htmldata.append("<textarea id='" + id + "' style='position: absolute; font-weight:"
                        + font_weight + ";font-family:" + font_family + "; width: " + width + "; height:"
                        + height + "; font-style:" + font_style + "; resize:none ; outline:0 ;text-align:"
                        + text_align + "; margin-left:" + margin_left + "px; margin-top:" + margin_top
                        + "px; font-size:" + font_size + "; color:" + font_color + ";text-shadow: " + h_shadow
                        + " " + v_shadow + " " + Blur + " " + text_shadow + "; line-height: " + line_height
                        + ";letter-spacing: " + letter_spacing + "; opacity:" + opacity
                        + ";-webkit-transform: rotate(" + webkit_transform
                        + "deg);background-color: inherit; border:none;overflow:hidden;'>" + defaulttext
                        + "</textarea>");
            } else if (modelElement.getAttribute("tag").equalsIgnoreCase("button")) {
                margin_left = modelElement.getAttribute("x-co-ordinates");
                margin_top = modelElement.getAttribute("y-co-ordinates");
                backgroundimage = modelElement.getAttribute("src").replace("url(", "").replace(")", "");
                String host = ServletUtil.getServerName(servletRequest.getServletContext());
                backgroundimage = backgroundimage.replace("../", host);
                htmldata.append("<img id='" + id + "' style='position: absolute; margin-left: " + margin_left
                        + "; margin-top:" + margin_top + ";' src='" + backgroundimage + "'/>");
            } else if (modelElement.getAttribute("tag").equalsIgnoreCase("logo")) {

                String filter = "";
                if (modelElement.getAttribute("filterEnable").equalsIgnoreCase("false")) {
                    h_shadow = modelElement.getAttribute("H-shadow");
                    v_shadow = modelElement.getAttribute("V-shadow");
                    Blur = modelElement.getAttribute("blur");
                    Drop_shadow_color = modelElement.getAttribute("Drop-shadow-color");
                    filter = "drop-shadow(" + Drop_shadow_color + " " + h_shadow + " " + v_shadow + " " + Blur
                            + ")";
                    logger.log(Level.INFO, filter);
                } else if (modelElement.getAttribute("blur").equalsIgnoreCase("undefined")) {

                    filter = "blur(0px) grayscale(0%) sepia(0%) saturate(100%) hue-rotate(0deg) invert(0%) brightness(100%) contrast(100%)";

                } else if (modelElement.getAttribute("filterEnable").equalsIgnoreCase("true")) {
                    Blur = modelElement.getAttribute("blur");
                    grayscale = (Double.parseDouble(modelElement.getAttribute("grayscale"))) * 100;
                    sepia = (Double.parseDouble(modelElement.getAttribute("sepia"))) * 100;
                    saturate = (Double.parseDouble(modelElement.getAttribute("saturate"))) * 100;
                    huerotate = modelElement.getAttribute("huerotate");
                    invert = (Double.parseDouble(modelElement.getAttribute("invert"))) * 100;
                    brightness = (Double.parseDouble(modelElement.getAttribute("brightness"))) * 100;
                    contrast = (Double.parseDouble(modelElement.getAttribute("contrast"))) * 100;

                    filter = "blur(" + Blur + ") grayscale(" + (int) grayscale + "%) sepia(" + (int) sepia
                            + "%) saturate(" + (int) saturate + "%) hue-rotate(" + huerotate + ") invert("
                            + (int) invert + "%) brightness(" + (int) brightness + "%) contrast("
                            + (int) contrast + "%)";
                    logger.log(Level.INFO, filter);
                }

                backgroundimage = modelElement.getAttribute("background-image");
                margin_left = modelElement.getAttribute("x-co-ordinates");
                margin_top = modelElement.getAttribute("y-co-ordinates");
                Blend_mode = modelElement.getAttribute("Blend");
                blend_mode = modelElement.getAttribute("blend-background-color");
                opacity = modelElement.getAttribute("opacity");
                width = modelElement.getAttribute("width");
                height = modelElement.getAttribute("height");
                background_repeat = "no-repeat";
                background_size = "contain";
                htmldata.append("<div id='" + id + "' style='position: absolute; width:" + width + "; height:"
                        + height + "; background-blend-mode:" + Blend_mode + "; background-color:" + blend_mode
                        + "; background-image:" + backgroundimage + "; margin-left:" + margin_left
                        + "px; margin-top:" + margin_top + "px; background-repeat:" + background_repeat
                        + "; -webkit-background-size:" + background_size + ";-webkit-filter:" + filter
                        + ";  opacity:" + opacity + "; '></div>");
                logger.log(Level.INFO, htmldata.toString());

            } else if (modelElement.getAttribute("tag").equalsIgnoreCase("block")) {
                String filter = "";

                h_shadow = modelElement.getAttribute("H-shadow");
                v_shadow = modelElement.getAttribute("V-shadow");
                Blur = modelElement.getAttribute("blur");
                Drop_shadow_color = modelElement.getAttribute("Drop-shadow-color");
                filter = "drop-shadow(" + Drop_shadow_color + " " + h_shadow + " " + v_shadow + " " + Blur
                        + ")";
                logger.log(Level.INFO, filter);

                margin_left = modelElement.getAttribute("x-co-ordinates");
                margin_top = modelElement.getAttribute("y-co-ordinates");
                border_radius = modelElement.getAttribute("border-radius");
                width = modelElement.getAttribute("width");
                height = modelElement.getAttribute("height");
                opacity = modelElement.getAttribute("opacity");
                String background_color = modelElement.getAttribute("background-color");
                htmldata.append("<div id='" + id + "' style='position: absolute; width:" + width + "; height:"
                        + height + ";opacity:" + opacity + "; margin-left:" + margin_left + "px; margin-top:"
                        + margin_top + "px; background-color:" + background_color + "; -webkit-filter:" + filter
                        + ";border-radius:" + border_radius + "; '></div>");
            } else if (modelElement.getAttribute("tag").equalsIgnoreCase("svg")) {
                String filter = "";

                h_shadow = modelElement.getAttribute("H-shadow");
                v_shadow = modelElement.getAttribute("V-shadow");
                Blur = modelElement.getAttribute("blur");
                Drop_shadow_color = modelElement.getAttribute("Drop-shadow-color");
                filter = "drop-shadow(" + Drop_shadow_color + " " + h_shadow + " " + v_shadow + " " + Blur
                        + ")";
                logger.log(Level.INFO, filter);

                margin_left = modelElement.getAttribute("x-co-ordinates");
                margin_top = modelElement.getAttribute("y-co-ordinates");
                border_radius = modelElement.getAttribute("border-radius");
                width = modelElement.getAttribute("width");
                height = modelElement.getAttribute("height");
                opacity = modelElement.getAttribute("opacity");
                String background_color = modelElement.getAttribute("background-color");
                String filename = modelElement.getAttribute("filename");
                File svgFolder = new File(AppConstants.BASE_TEMP_PATH);
                String svgContent = FileUtils.readFileToString(new File(svgFolder + File.separator + filename),
                        "UTF-8");

                htmldata.append("<div id='" + id + "' style='position: absolute; width:" + width + "; height:"
                        + height + "; margin-left:" + margin_left + "px; margin-top:" + margin_top + "px; '>"
                        + svgContent + "</div>");
            }

            logger.log(Level.INFO, htmldata.toString());
            logger.info(htmldata.toString());
        }
        PhantomImageConverter phantomImageConverter = new PhantomImageConverter(servletContext);

        File imagePngFile = phantomImageConverter.getImage(htmldata.toString(), json_font_list, containerWidth,
                containerHeight, "0", "0");
        Style_image_name = imagePngFile.getName();

        File htmlFolder = new File(AppConstants.LAYOUT_HTML_HOME);
        if (!htmlFolder.exists()) {
            htmlFolder.mkdirs();
        }
        FileUtils.writeStringToFile(new File(htmlFolder.getPath() + File.separator + modelname + ".html"),
                htmldata.toString(), "UTF-8");

    } catch (Exception e) {
        logger.log(Level.SEVERE, "", e);
    }
    return Style_image_name;
}

From source file:org.auraframework.http.AuraTestFilter.java

private String captureResponse(ServletRequest req, ServletResponse res, String testName, String uri)
        throws ServletException, IOException {
    CapturingResponseWrapper responseWrapper = new CapturingResponseWrapper((HttpServletResponse) res) {
        @Override/* w  ww .  jav a 2  s . c om*/
        public void sendRedirect(String location) throws IOException {
            // If the response is redirected after this filter, we want to
            // handle the redirect, so we need to set the jstestrun
            // parameter to make sure we can see it on the next request.
            Matcher test = jstestToRunPattern.matcher(location);
            if (test.find()) {
                location = test.replaceAll(testName);
            } else {
                location = location + (location.indexOf('?') < 0 ? "?" : "&") + jstestToRun.name + "="
                        + testName;
            }
            super.sendRedirect(location);
        }
    };
    RequestDispatcher dispatcher = req.getServletContext().getContext(uri).getRequestDispatcher(uri);
    if (dispatcher == null) {
        return null;
    }
    dispatcher.forward(req, responseWrapper);
    if (responseWrapper.getRedirectUrl() != null) {
        return null;
    }
    return responseWrapper.getCapturedResponseString();
}

From source file:org.egov.infra.web.utils.WebUtils.java

public static String currentContextPath(ServletRequest request) {
    return request.getServletContext().getContextPath().replace(SLASH, EMPTY);
}

From source file:org.fenixedu.bennu.core.filters.CloseTransactionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    try {/*from  ww  w. j  a v  a  2s  .c o m*/
        doChain(request, response, chain);
    } catch (Error t) {
        t.printStackTrace();
        InputStream resource = request.getServletContext().getResourceAsStream("/error.html");
        if (resource != null) {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("text/html");
            IOUtils.copy(resource, outputStream);
            outputStream.flush();
        } else {
            throw t;
        }
    }
}

From source file:org.geonetwork.http.SessionTimeoutCookieFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpSession session = httpReq.getSession(false);

    //If we are not being accessed by a bot/crawler
    if (session != null) {
        long currTime = System.currentTimeMillis();

        Cookie cookie = new Cookie("serverTime", "" + currTime);
        cookie.setPath("/");
        cookie.setSecure(req.getServletContext().getSessionCookieConfig().isSecure());
        httpResp.addCookie(cookie);/*from w  ww.j  a  v a 2 s.  c o  m*/

        UserSession userSession = null;
        if (session != null) {
            Object tmp = session.getAttribute(JeevesServlet.USER_SESSION_ATTRIBUTE_KEY);
            if (tmp instanceof UserSession) {
                userSession = (UserSession) tmp;
            }
        }
        // If user is authenticated, then set expiration time
        if (userSession != null && StringUtils.isNotEmpty(userSession.getName())) {
            long expiryTime = currTime + session.getMaxInactiveInterval() * 1000;
            cookie = new Cookie("sessionExpiry", "" + expiryTime);
        } else {
            cookie = new Cookie("sessionExpiry", "" + currTime);
        }
        cookie.setPath("/");
        cookie.setSecure(req.getServletContext().getSessionCookieConfig().isSecure());
        httpResp.addCookie(cookie);
    }

    filterChain.doFilter(req, resp);
}

From source file:org.restcomm.connect.http.cors.CorsFilter.java

private void initLazily(ServletRequest request) {
    if (lazyServletContext == null) {
        ServletContext context = request.getServletContext();
        String rootPath = context.getRealPath("/");
        rootPath = StringUtils.stripEnd(rootPath, "/"); // remove trailing "/" character
        String restcommXmlPath = rootPath + "/WEB-INF/conf/restcomm.xml";

        // ok, found restcomm.xml. Now let's get rcmlserver/base-url configuration setting
        File restcommXmlFile = new File(restcommXmlPath);
        // Create apache configuration
        XMLConfiguration apacheConf = new XMLConfiguration();
        apacheConf.setDelimiterParsingDisabled(true);
        apacheConf.setAttributeSplittingDisabled(true);
        try {/*  w ww  . j a v a 2  s  .c om*/
            apacheConf.load(restcommXmlPath);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        // Create high-level configuration
        ConfigurationSource source = new ApacheConfigurationSource(apacheConf);
        RcmlserverConfigurationSet rcmlserverConfig = new RcmlserverConfigurationSetImpl(source);
        // initialize allowedOrigin
        String baseUrl = rcmlserverConfig.getBaseUrl();
        if (baseUrl != null && (!baseUrl.trim().equals(""))) {
            // baseUrl is set. We need to return CORS allow headers
            allowedOrigin = baseUrl;
        }

        lazyServletContext = context;

        logger.info("Initialized (lazily) CORS servlet response filter. allowedOrigin: " + allowedOrigin);
    }
}

From source file:password.pwm.http.filter.RequestInitializationFilter.java

public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) servletRequest;
    final HttpServletResponse resp = (HttpServletResponse) servletResponse;
    final PwmApplicationMode mode = PwmApplicationMode.determineMode(req);
    final PwmURL pwmURL = new PwmURL(req);

    PwmApplication testPwmApplicationLoad = null;
    try {//from w ww  .  j a v  a 2  s  .  c  o m
        testPwmApplicationLoad = ContextManager.getPwmApplication(req);
    } catch (PwmException e) {
    }

    if (testPwmApplicationLoad == null && pwmURL.isResourceURL()) {
        filterChain.doFilter(req, resp);
    } else if (pwmURL.isStandaloneWebService() || pwmURL.isJerseyWebService()) {
        filterChain.doFilter(req, resp);
    } else {
        if (mode == PwmApplicationMode.ERROR) {
            try {
                final ContextManager contextManager = ContextManager.getContextManager(req.getServletContext());
                if (contextManager != null) {
                    final ErrorInformation startupError = contextManager.getStartupErrorInformation();
                    servletRequest.setAttribute(PwmRequestAttribute.PwmErrorInfo.toString(), startupError);
                }
            } catch (Exception e) {
                if (pwmURL.isResourceURL()) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }

                LOGGER.error("error while trying to detect application status: " + e.getMessage());
            }

            LOGGER.error("unable to satisfy incoming request, application is not available");
            resp.setStatus(500);
            final String url = JspUrl.APP_UNAVAILABLE.getPath();
            servletRequest.getServletContext().getRequestDispatcher(url).forward(servletRequest,
                    servletResponse);
        } else {
            initializeServletRequest(req, resp, filterChain);
        }
    }
}