Example usage for javax.servlet ServletContext getContextPath

List of usage examples for javax.servlet ServletContext getContextPath

Introduction

In this page you can find the example usage for javax.servlet ServletContext getContextPath.

Prototype

public String getContextPath();

Source Link

Document

Returns the context path of the web application.

Usage

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testGetFormPreviewRendererNotFound() throws Exception {
    final Translator translator = EasyMock.createMock(Translator.class);
    final ServletContext context = EasyMock.createMock(ServletContext.class);
    final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    RESTFormService restService = emulateRESTFormService(translator, null, null,
            new RendererException("not finding a renderer"));
    restService.setFormService(new MockFormDefinitionService());

    FormPreviewDTO dto = new FormPreviewDTO();
    FormRepresentation form = createMockForm("myForm", "key1", "key2");
    String jsonBody = FormEncodingFactory.getEncoder().encode(form);
    dto.setRepresentation(jsonBody);//  w ww.ja v  a  2s . co  m

    URL url = new URL("http://www.redhat.com");
    EasyMock.expect(translator.translateForm(EasyMock.eq(form))).andReturn(url).once();
    EasyMock.expect(context.getContextPath()).andReturn("/").anyTimes();

    EasyMock.replay(translator, context, request);
    Response resp = restService.getFormPreview(dto, "lang", context, request);
    EasyMock.verify(translator, context, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.INTERNAL_SERVER_ERROR);
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,
        ServletContext sc) {
    Log logger = LogFactory.getLog(DhccContextLoader.class);
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
        // The application context id is still set to its original default value
        // -> assign a more useful id based on available information
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);//from w  ww  .  ja  v  a2  s.  c  o m
        } else {
            // Generate default id...
            if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
                // Servlet <= 2.4: resort to name specified in web.xml, if any.
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                        + ObjectUtils.getDisplayString(sc.getServletContextName()));
            } else {
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                        + ObjectUtils.getDisplayString(sc.getContextPath()));
            }
        }
    }

    wac.setServletContext(sc);
    String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);
    if (isMicrokernelStart(sc)) {
        initParameter = "classpath:codeTemplate/applicationSetupContext.xml";
        logger.error("because cant't  connect to db or setup flg is 0 so init application as  Microkernel ");
    } else {
        logger.info("initParameter==" + initParameter);
    }
    if (initParameter != null) {
        wac.setConfigLocation(initParameter);
    }
    customizeContext(sc, wac);
    wac.refresh();
}

From source file:org.kuali.mobility.tags.angular.PageTag.java

public void doTag() throws JspException {
    String appcacheEnabled;/*from   ww w  . jav  a  2s  .  com*/

    PageContext pageContext = (PageContext) getJspContext();
    HttpServletRequest hsr = (HttpServletRequest) pageContext.getRequest();
    ServletContext servletContext = pageContext.getServletContext();
    WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    setKmeProperties((Properties) ac.getBean("kmeProperties"));

    CoreService coreService = (CoreService) ac.getBean("coreService");
    Properties kmeProperties = (Properties) ac.getBean("kmeProperties");
    Locale locale = RequestContextUtils.getLocale((HttpServletRequest) pageContext.getRequest());
    MessageSource ms = (MessageSource) ac.getBean("messageSource");

    User user = (User) pageContext.getSession().getAttribute(AuthenticationConstants.KME_USER_KEY);
    String contextPath = servletContext.getContextPath();

    appcacheEnabled = kmeProperties.getProperty("appcache.enabled", "true");

    JspWriter out = pageContext.getOut();
    StringBuilder builder = new StringBuilder();
    try {
        builder.append("<!DOCTYPE html>");
        builder.append("<html");
        if (!appcacheEnabled.equals("false")) {
            LOG.debug("Appcache Enabled");
            builder.append(" manifest=\"CONTEXT_PATH/kme.appcache\"");
        }
        if (null != getNgAppName()) {
            builder.append(" ng-app=\"");
            builder.append(getNgAppName());
            builder.append("\"");
        }
        builder.append(">");

        builder.append("<head>");
        builder.append("<title>");
        builder.append(getTitle());
        builder.append("</title>");
        builder.append("<link href=\"");
        builder.append(kmeProperties.getProperty("favico.url", "http://www.kuali.org/favicon.ico"));
        builder.append("\" rel=\"icon\" />");
        builder.append("<link href=\"");
        builder.append(kmeProperties.getProperty("favico.url", "http://www.kuali.org/favicon.ico"));
        builder.append("\" rel=\"shortcut icon\" />");

        builder.append("<link rel=\"apple-touch-icon\" href=\"CONTEXT_PATH/touch-icon-iphone.png\"/>");
        builder.append(
                "<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"CONTEXT_PATH/touch-icon-ipad.png\"/>");
        builder.append(
                "<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"CONTEXT_PATH/touch-icon-iphone-retina.png\"/>");
        builder.append(
                "<link rel=\"apple-touch-icon\" sizes=\"144x144\" href=\"CONTEXT_PATH/touch-icon-ipad-retina.png\"/>");

        builder.append(
                "<script src=\"//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js\"></script>\n");
        builder.append(
                "<script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js\"></script>\n");
        builder.append(
                "<script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-route.js\"></script>\n");
        builder.append(
                "<script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-sanitize.js\"></script>\n");

        builder.append("<script src=\"CONTEXT_PATH/js/jquery.cookie.js\"></script>");
        builder.append("<script src=\"CONTEXT_PATH/js/ui3/ui-bootstrap-tpls-0.10.0.min.js\"></script>\n");
        builder.append("<script src=\"CONTEXT_PATH/js/bootstrap.js\"></script>\n");
        builder.append("<script src=\"CONTEXT_PATH/js/bootbox.js\"></script>\n");

        builder.append("<!-- Latest compiled and minified CSS -->\n");
        builder.append(
                "<link rel=\"stylesheet\" href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\"/>\n");
        builder.append("<link href=\"CONTEXT_PATH/css/ui3/kme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n");
        builder.append(
                "<link href=\"CONTEXT_PATH/css/ui3/institution.css\" rel=\"stylesheet\" type=\"text/css\"/>\n");
        // Attach all CSS files
        for (String cssFile : getCssFilenames()) {
            builder.append("<link href=\"CONTEXT_PATH/css/ui3/");
            builder.append(cssFile);
            builder.append(".css\" rel=\"stylesheet\" type=\"text/css\"/>\n");
        }
        builder.append("<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/BrowserDetect.js\"></script>\n");
        builder.append("<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/ServerDetails.js\"></script>\n");

        if (isPlatform(Device.TYPE_IOS)) {
            if (isPhoneGap("1.4.1")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/phonegap-1.4.1.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/ChildBrowser.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/barcodescanner.js\"></script>\n");
                //                builder.append("<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/Connection.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/PushHandler.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/Badge.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/applicationPreferences.js\"></script>\n");
            } else if (isPhoneGap("1.7.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/cordova-1.7.0.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/ChildBrowser.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/barcodescanner.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/ActionSheet.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/Badge.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/LocalNotifications.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/Notifications.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/PrintPlugin.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/1.7.0/applicationPreferences.js\"></script>\n");
            } else if (isPhoneGap("2.2.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/cordova-2.2.0.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/ActionSheet.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/applicationPreferences.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/AudioStreamer.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/Badge.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/barcodescanner.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.2.0/ChildBrowser.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/PushHandler.js\"></script>\n");
            } else if (isPhoneGap("2.3.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.3.0/cordova-2.3.0.js\"></script>\n");
            } else if (isPhoneGap("2.4.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.4.0/cordova-2.4.0.js\"></script>\n");
            } else if (isPhoneGap("2.5.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.5.0/cordova-2.5.0.js\"></script>\n");
            } else if (isPhoneGap("2.6.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.6.0/cordova-2.6.0.js\"></script>\n");
            } else if (isPhoneGap("2.7.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.7.0/cordova-2.7.0.js\"></script>\n");
            } else if (isPhoneGap("2.8.1")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/iOS/2.8.1/cordova.js\"></script>\n");
            }
        } else if (isPlatform(Device.TYPE_ANDROID)) {
            builder.append(
                    "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/PushConfig.js\"></script>\n");
            if (isPhoneGap("2.2.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/cordova-2.2.0.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/childbrowser.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/barcodescanner.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/statusbarnotification.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/datePickerPlugin.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/applicationPreferences.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/AudioStreamer.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/GCMPlugin.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/2.2.0/CORDOVA_GCM_script.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/PushHandler.js\"></script>\n");
            } else {
                builder.append("<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/phonegap-"
                        + getPhonegap() + ".js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/childbrowser.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/barcodescanner.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/statusbarnotification.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/C2DMPlugin.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/PG_C2DM_script.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/android/PushHandler.js\"></script>\n");
            }
        } else if (isPlatform(Device.TYPE_BLACKBERRY)) {
            builder.append(
                    "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/PushConfig.js\"></script>\n");
            if (isPhoneGap("2.2.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/blackberry/2.2.0/cordova-2.2.0.js\"></script>\n");
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/blackberry/2.2.0/kme-application.js\"></script>\n");
            }
        } else if (isPlatform(Device.TYPE_WINDOWS)) {
            if (isPhoneGap("2.2.0")) {
                builder.append(
                        "<script type=\"text/javascript\" src=\"CONTEXT_PATH/js/windowsMobile/2.2.0/cordova-2.2.0.js\"></script>\n");
            }
        }

        /* Google Analytics */
        String profileId = coreService.findGoogleAnalyticsProfileId().trim();
        if (!disableGoogleAnalytics && profileId.length() > 0) {
            String profileDomain = coreService.getGoogleAnalyticsProfileDomain().trim();
            if (coreService.isGoogleUniversalAnalytics() && !profileDomain.isEmpty()) {
                out.println("<script type=\"text/javascript\">");
                out.println("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){");
                out.println("(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),");
                out.println("m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)");
                out.println("})(window,document,'script','//www.google-analytics.com/analytics.js','ga');");

                out.println("ga('create', '" + profileId + "', '" + profileDomain + "'); ");
                out.println("ga('send', 'pageview');");
                out.println("</script>");
            } else {
                out.println("<script type=\"text/javascript\">");
                out.println("var _gaq = _gaq || [];");
                out.println("_gaq.push(['_setAccount', '" + profileId + "']);");
                out.println("_gaq.push(['_trackPageview']);");
                out.println("(function() {");
                out.println(
                        "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;");
                out.println(
                        "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';");
                out.println(
                        "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);");
                out.println("})();");
                out.println("</script>");
            }
        }

        if (isUsesGoogleMaps()) {
            builder.append(
                    "<script type=\"text/javascript\" src=\"https://maps.google.com/maps/api/js?libraries=geometry&v=3.exp&sensor=true");
            if (null != getMapLocale() && !getMapLocale().isEmpty()) {
                builder.append("&language=");
                builder.append(getMapLocale());
            }
            if (null != getMapCallbackFunction() && !getMapCallbackFunction().isEmpty()) {
                builder.append("&callback=");
                builder.append(getMapCallbackFunction());
            }
            builder.append("\"></script>\n");
            //                builder.append("<script type=\"text/javascript\" src=\"//maps.google.com/maps/api/js?libraries=geometry&v=3&sensor=true\"></script>\n");
            builder.append(
                    "<script type=\"text/javascript\" src=\"//google-maps-utility-library-v3.googlecode.com/svn/trunk/styledmarker/src/StyledMarker.js\"></script>\n");
            builder.append(
                    "<script type=\"text/javascript\" src=\"//google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js\"></script>\n");
        }

        if ("mapquest".equalsIgnoreCase(getKmeProperties().getProperty("maps.api"))) {
            builder.append(
                    "<script type=\"text/javascript\" src=\"http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?key=Fmjtd%7Cluubnu6r2q%2C8n%3Do5-9uyllr\"></script>\n");
        }

        for (String javascript : getJsFilenames()) {
            builder.append("<script type=\"text/javascript\" src=\"CONTEXT_PATH/");
            builder.append(getToolName());
            builder.append("/js/");
            builder.append(javascript);
            builder.append(".js\"></script>\n");
        }

        builder.append(
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\">\n");
        builder.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");

        builder.append("</head>");
        builder.append("<body");
        if (null != getToolName()) {
            builder.append(" id=\"");
            builder.append(getToolName());
            builder.append("\"");
        }
        if (null != getNgControllerName()) {
            builder.append(" ng-controller=\"");
            builder.append(getNgControllerName());
            builder.append("\"");
        }
        if (null != getNgInitFunction()) {
            builder.append(" data-ng-init=\"");
            builder.append(getNgInitFunction());
            builder.append("()\"");
        }
        builder.append(">\n");

        builder.append(
                "    <nav class=\"kme-top-nav navbar navbar-default navbar-fixed-top\" role=\"navigation\">\n");
        //back
        if (!isHideBackButton()) {
            boolean showButton = true;
            if (("true".equalsIgnoreCase(getKmeProperties().getProperty("shim.backbutton.ios"))
                    && isPlatform(Device.TYPE_IOS))
                    || ("true".equalsIgnoreCase(getKmeProperties().getProperty("shim.backbutton.android"))
                            && isPlatform(Device.TYPE_ANDROID))) {
                showButton = false;
            }
            if (showButton) {
                if ("left".equalsIgnoreCase(getKmeProperties().getProperty("nav.back.position"))) {
                    builder.append("        <div class=\"nav navbar-nav  pull-left kme-nav-back\">\n");
                } else if ("right".equalsIgnoreCase(getKmeProperties().getProperty("nav.back.position"))) {
                    builder.append("        <div class=\"nav navbar-nav  pull-right kme-nav-back\">\n");
                } else {
                    builder.append("        <div class=\"nav navbar-nav  pull-left kme-nav-back\">\n");
                }

                builder.append("            <a ng-click=\"");
                if (null == getBackFunction() || getBackFunction().isEmpty()) {
                    builder.append("kmeNavLeft");
                } else {
                    builder.append(getBackFunction());
                }
                builder.append(
                        "()\" class=\"ur-small-element\"><span class=\"glyphicon glyphicon-chevron-left white\"></span></a>\n");
                builder.append("        </div>\n");
            }
        }
        //end back

        //menu
        if (!isHideMenuButton()) {
            boolean showButton = true;
            if (("true".equalsIgnoreCase(getKmeProperties().getProperty("shim.homebutton.ios"))
                    && isPlatform(Device.TYPE_IOS))
                    || ("true".equalsIgnoreCase(getKmeProperties().getProperty("shim.homebutton.android"))
                            && isPlatform(Device.TYPE_ANDROID))) {
                showButton = false;
            }
            if (showButton) {
                if ("left".equalsIgnoreCase(getKmeProperties().getProperty("nav.menu.position"))) {
                    builder.append("        <div class=\"nav navbar-nav pull-left dropdown kme-nav-menu\">\n");
                } else if ("right".equalsIgnoreCase(getKmeProperties().getProperty("nav.menu.position"))) {
                    builder.append("        <div class=\"nav navbar-nav pull-right dropdown kme-nav-menu\">\n");
                } else {
                    builder.append("        <div class=\"nav navbar-nav pull-right dropdown kme-nav-menu\">\n");
                }
                builder.append(
                        "            <a class=\"dropdown-toggle ur-small-element\" href=\"#\" ><span class=\"glyphicon glyphicon-align-justify white\"></span></a>\n");
                builder.append("            <ul class=\"dropdown-menu\">\n");
                //home
                builder.append("                <li><a href=\"CONTEXT_PATH/home\">Home</a></li>\n");
                //end home
                builder.append(
                        "                <li ng-repeat=\"menu in menuItems.menus\" ng-class=\"{divider:menu.divider}\"><a href=\"CONTEXT_PATH{{menu.url}}\" _target=\"self\">{{menu.label}}</a></li>\n");
                if ("true".equalsIgnoreCase(kmeProperties.getProperty("home.preferences.enabled", "true"))) {
                    builder.append("                <li class=\"divider\"></li>\n");
                    builder.append(
                            "                <li><a href=\"CONTEXT_PATH/preferences\">Preferences</a></li>\n");
                }
                builder.append("            </ul>\n");
                builder.append("        </div>\n");
            }
        }
        //end menu

        builder.append("        <div class=\"navbar-header navbar-text \">");
        builder.append(getTitle());
        builder.append("</div>\n");

        builder.append("    </nav>\n");

        String output = builder.toString();
        output = output.replaceAll("CONTEXT_PATH", contextPath);
        out.println(output);
        getJspBody().invoke(out);
        out.println("</body>");
        out.println("</html>");
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private void serveRequest(RequestMethod method, HttpServletRequest req, HttpServletResponse rsp)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }/*from   w ww . j a v a  2  s  .  c  o  m*/

    if ((loopRetryTimeout > 0L) && (!loopDetected)) {
        long now = System.currentTimeMillis(), diff = now - initTimestamp;
        if ((diff > 0L) && (diff < loopRetryTimeout)) {
            try {
                MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(new ObjectName(
                        "net.community.chest.gitcloud.facade.backend.git:name=BackendRepositoryResolver"));
                if (mbeanInfo != null) {
                    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " detected loop: " + mbeanInfo.getClassName() + "["
                            + mbeanInfo.getDescription() + "]");
                    loopDetected = true;
                }
            } catch (JMException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " failed " + e.getClass().getSimpleName()
                            + " to detect loop: " + e.getMessage());
                }
            }
        }
    }

    ResolvedRepositoryData repoData = resolveTargetRepository(method, req);
    if (repoData == null) {
        throw ExtendedLogUtils.thrownLogging(logger, Level.WARNING,
                "serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]",
                new NoSuchElementException("Failed to resolve repository"));
    }

    String username = authenticate(req);
    // TODO check if the user is allowed to access the repository via the resolve operation (push/pull) if at all (e.g., private repo)
    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] user="
            + username);

    /*
     * NOTE: this feature requires enabling cross-context forwarding.
     * In Tomcat, the 'crossContext' attribute in 'Context' element of
     * 'TOMCAT_HOME\conf\context.xml' must be set to true, to enable cross-context 
     */
    if (loopDetected) {
        // TODO see if can find a more efficient way than splitting and re-constructing
        URI uri = repoData.getRepoLocation();
        ServletContext curContext = req.getServletContext();
        String urlPath = uri.getPath(), urlQuery = uri.getQuery();
        String[] comps = StringUtils.split(urlPath, '/');
        String appName = comps[0];
        ServletContext loopContext = Validate.notNull(curContext.getContext("/" + appName),
                "No cross-context for %s", appName);
        // build the relative path in the re-directed context
        StringBuilder sb = new StringBuilder(
                urlPath.length() + 1 + (StringUtils.isEmpty(urlQuery) ? 0 : urlQuery.length()));
        for (int index = 1; index < comps.length; index++) {
            sb.append('/').append(comps[index]);
        }
        if (!StringUtils.isEmpty(urlQuery)) {
            sb.append('?').append(urlQuery);
        }

        String redirectPath = sb.toString();
        RequestDispatcher dispatcher = Validate.notNull(loopContext.getRequestDispatcher(redirectPath),
                "No dispatcher for %s", redirectPath);
        dispatcher.forward(req, rsp);
        if (logger.isDebugEnabled()) {
            logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                    + "]" + " forwarded to " + loopContext.getContextPath() + "/" + redirectPath);
        }
    } else {
        executeRemoteRequest(method, repoData.getRepoLocation(), req, rsp);
    }
}

From source file:org.bibalex.wamcp.storage.WAMCPIndexedStorage.java

 public void writeIndexFieldsToFile(ActionEvent ev) throws WAMCPException, WFSVNException,
      SVNException, XSAException {/*from  w  ww .j av a2 s . com*/
      
   Properties ixedFieldsNameType = new Properties();
      
   for (String key : this.getAllFieldNames()) {
      String value = this.getSolrTypeForField(key);
         
      if (!key.startsWith("All")) { // catch all fields don't have an XPath
         
         Set<Entry<XSAInstance, String>> entriesToSearch;
         if (key.indexOf('_') == -1) {
            entriesToSearch = this.advSearchFieldsNames.entrySet();
         } else {
            entriesToSearch = this.ixedFieldsNames.entrySet();
         }
            
         for (Entry<XSAInstance, String> mapping : entriesToSearch) {
            if (key.equals(mapping.getValue())) {
                  
               String fieldXPathStr = mapping.getKey().getXPathToAllOccsInAllBaseShifts();
               value += "," + fieldXPathStr;
                  
               // A field can take values from more than one XPath break;
            }
         }
      }
         
      ixedFieldsNameType.setProperty(key, value);
   }
      
   try {
      File ixedFieldesNameTypeTempFile = new File(this.getUserDir().getCanonicalPath()
            + File.separator + "ixedFieldesNameType.properties");
      FileOutputStream ixedFieldesNameTypeTempStream = new FileOutputStream(
            ixedFieldesNameTypeTempFile);
         
      ixedFieldsNameType.store(ixedFieldesNameTypeTempStream, "");
         
      ixedFieldesNameTypeTempStream.flush();
      ixedFieldesNameTypeTempStream.close();
         
      String targetPathAbs = ixedFieldesNameTypeTempFile.getCanonicalPath();
      ServletContext sltCtx = (ServletContext) FacesContext.getCurrentInstance()
            .getExternalContext().getContext();
      String filePathAbs = sltCtx.getRealPath("");
         
      String filePathRel = targetPathAbs.substring(filePathAbs.length());
      filePathRel = filePathRel.replace('\\', '/');
      String fileURL = sltCtx.getContextPath() + filePathRel;
         
      this.setQuickMessage("Index fields file created: <a href='" + fileURL
            + "'>"
            + " Click to download! </a>");
   } catch (IOException e) {
      throw new WAMCPException(e);
   }
      
}

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testGetFormPreviewOK() throws Exception {
    final Renderer renderer = EasyMock.createMock(Renderer.class);
    final Translator translator = EasyMock.createMock(Translator.class);
    final ServletContext context = EasyMock.createMock(ServletContext.class);
    final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    RESTFormService restService = emulateRESTFormService(translator, null, renderer, null);
    restService.setFormService(new MockFormDefinitionService());

    FormRepresentation form = createMockForm("myForm", "key1", "key2");
    FormPreviewDTO dto = createFormPreviewDTO(form);

    URL url = new URL("http://www.redhat.com");
    EasyMock.expect(translator.translateForm(EasyMock.eq(form))).andReturn(url).once();
    String htmlResult = "<html><body><div>Hello</div></body></html>";
    @SuppressWarnings("unchecked")
    Map<String, Object> anyObject = EasyMock.anyObject(Map.class);
    EasyMock.expect(renderer.render(EasyMock.anyObject(URL.class), anyObject)).andReturn(htmlResult);
    EasyMock.expect(context.getContextPath()).andReturn("/").anyTimes();
    EasyMock.expect(request.getLocale()).andReturn(Locale.getDefault()).once();

    EasyMock.replay(renderer, translator, context, request);
    Response resp = restService.getFormPreview(dto, "lang", context, request);
    EasyMock.verify(renderer, translator, context, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.OK);
    assertNotNull("resp.entity shouldn't be null", resp.getEntity());
    Object entity = resp.getEntity();
    assertNotNull("resp.metadata shouldn't be null", resp.getMetadata());
    Object contentType = resp.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
    assertNotNull("contentType shouldn't be null", contentType);
    assertEquals("contentType should be application/xml but is" + contentType, contentType,
            MediaType.TEXT_PLAIN);/*from   ww  w .  ja v  a2s  .  c  o  m*/
    String html = entity.toString();
    assertTrue("html should contain data", html.length() > 0);
}

From source file:org.jbpm.formbuilder.server.RESTFormServiceTest.java

public void testGetFormPreviewRendererProblem() throws Exception {
    final Renderer renderer = EasyMock.createMock(Renderer.class);
    final Translator translator = EasyMock.createMock(Translator.class);
    final ServletContext context = EasyMock.createMock(ServletContext.class);
    final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    RESTFormService restService = emulateRESTFormService(translator, null, renderer, null);
    restService.setFormService(new MockFormDefinitionService());

    FormRepresentation form = createMockForm("myForm", "key1", "key2");
    FormPreviewDTO dto = createFormPreviewDTO(form);

    EasyMock.expect(translator.translateForm(EasyMock.eq(form))).andReturn(new URL("http://www.redhat.com"))
            .once();/*from www  .j  a  va2 s.  co m*/
    RendererException exception = new RendererException("Something going wrong");
    @SuppressWarnings("unchecked")
    Map<String, Object> anyObject = EasyMock.anyObject(Map.class);
    EasyMock.expect(renderer.render(EasyMock.anyObject(URL.class), anyObject)).andThrow(exception).once();
    EasyMock.expect(context.getContextPath()).andReturn("/").anyTimes();
    EasyMock.expect(request.getLocale()).andReturn(Locale.getDefault()).once();

    EasyMock.replay(renderer, translator, context, request);
    Response resp = restService.getFormPreview(dto, "lang", context, request);
    EasyMock.verify(renderer, translator, context, request);

    assertNotNull("resp shouldn't be null", resp);
    assertStatus(resp.getStatus(), Status.INTERNAL_SERVER_ERROR);
}

From source file:com.dominion.salud.mpr.configuration.MPRInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.scan("com.dominion.salud.mpr.configuration");
    ctx.setServletContext(servletContext);
    System.setProperty("mpr.conf.home", findConfigurationAndLogger(ctx));
    ctx.refresh();//from   www. ja  v  a 2  s  . c  o m

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(ctx));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.addMapping("/controller/*");
    dispatcher.addMapping("/services/*");
    servletContext.addListener(new ContextLoaderListener(ctx));

    // Configuracion GENERAL DEL MODULO
    MPRConstantes._MPR_HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator)
            ? servletContext.getRealPath("/")
            : servletContext.getRealPath("/") + File.separator;
    MPRConstantes._MPR_CONF_HOME = ctx.getEnvironment().getProperty("mpr.conf.home");
    MPRConstantes._MPR_VERSION = ResourceBundle.getBundle("version").getString("version");
    MPRConstantes._MPR_RESOURCES = MPRConstantes._MPR_HOME + "resources" + File.separator;
    MPRConstantes._MPR_TEMP = MPRConstantes._MPR_HOME + "WEB-INF" + File.separator + "temp" + File.separator;
    MPRConstantes._MPR_CONTEXT_NAME = servletContext.getServletContextName();
    MPRConstantes._MPR_CONTEXT_PATH = servletContext.getContextPath();
    MPRConstantes._MPR_CONTEXT_SERVER = servletContext.getServerInfo();

    // Configuracion de LOGS DEL MODULO
    if (StringUtils.isBlank(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())) {
        ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE"))
                .setFile(MPRConstantes._MPR_HOME + "WEB-INF" + File.separator + "classes" + File.separator
                        + "logs" + File.separator + "mpr-desktop.log");
    }
    MPRConstantes._MPR_LOGS = new File(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())
                    .getParent();

    // Parametrizacion GENERAL DEL SISTEMA
    MPRConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.enable.technical.information"))
                    ? Boolean.parseBoolean(ctx.getEnvironment().getProperty("mpr.enable.technical.information"))
                    : false;

    // Parametrizacion de CONEXION A EMPI
    MPRConstantes._EMPI_ENABLE = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.enable"))
            ? Boolean.parseBoolean(ctx.getEnvironment().getProperty("mpr.empi.enable"))
            : false;
    MPRConstantes._EMPI_USUARIO = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.usuario"))
            ? ctx.getEnvironment().getProperty("mpr.empi.usuario")
            : "";
    MPRConstantes._EMPI_SISTEMA = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.sistema"))
            ? ctx.getEnvironment().getProperty("mpr.empi.sistema")
            : "";
    MPRConstantes._EMPI_URL = StringUtils.isNotBlank(ctx.getEnvironment().getProperty("mpr.empi.url"))
            ? ctx.getEnvironment().getProperty("mpr.empi.url")
            : "";

    // Parametrizacion de TAREAS PROGRAMADAS
    MPRConstantes._TASK_BUZON_IN_PROCESS_MESSAGES = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.process.messages"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.in.process.messages")
                    : MPRConstantes._TASK_BUZON_IN_PROCESS_MESSAGES;
    MPRConstantes._TASK_BUZON_OUT_PROCESS_MESSAGES = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.process.messages"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.out.process.messages")
                    : MPRConstantes._TASK_BUZON_OUT_PROCESS_MESSAGES;
    MPRConstantes._TASK_BUZON_IN_HIS_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean")
                    : MPRConstantes._TASK_BUZON_IN_HIS_CLEAN;
    MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean")
                    : MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN;
    MPRConstantes._TASK_BUZON_IN_HIS_CLEAN_OLD = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean.old"))
                    ? Integer.parseInt(ctx.getEnvironment().getProperty("mpr.task.buzon.in.his.clean.old"))
                    : MPRConstantes._TASK_BUZON_IN_HIS_CLEAN_OLD;
    MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN_OLD = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean.old"))
                    ? Integer.parseInt(ctx.getEnvironment().getProperty("mpr.task.buzon.out.his.clean.old"))
                    : MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN_OLD;
    MPRConstantes._TASK_BUZON_IN_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.in.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.in.clean")
                    : MPRConstantes._TASK_BUZON_IN_CLEAN;
    MPRConstantes._TASK_BUZON_OUT_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.out.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.out.clean")
                    : MPRConstantes._TASK_BUZON_OUT_CLEAN;
    MPRConstantes._TASK_BUZON_ERRORES_CLEAN = StringUtils
            .isNotBlank(ctx.getEnvironment().getProperty("mpr.task.buzon.errores.clean"))
                    ? ctx.getEnvironment().getProperty("mpr.task.buzon.errores.clean")
                    : MPRConstantes._TASK_BUZON_ERRORES_CLEAN;

    logger.info("Iniciando el modulo de [" + MPRConstantes._MPR_CONTEXT_NAME + "]");
    logger.debug("     Configuracion GENERAL DEL MODULO");
    logger.debug("          mpr.home: " + MPRConstantes._MPR_HOME);
    logger.debug("          mpr.conf.home: " + MPRConstantes._MPR_CONF_HOME);
    logger.debug("          mpr.version: " + MPRConstantes._MPR_VERSION);
    logger.debug("          mpr.resources: " + MPRConstantes._MPR_RESOURCES);
    logger.debug("          mpr.temp: " + MPRConstantes._MPR_TEMP);
    logger.debug("          mpr.logs: " + MPRConstantes._MPR_LOGS);
    logger.debug("          mpr.logs.file: "
            + ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile());
    logger.debug("          mpr.context.name: " + MPRConstantes._MPR_CONTEXT_NAME);
    logger.debug("          mpr.context.path: " + MPRConstantes._MPR_CONTEXT_PATH);
    logger.debug("          mpr.context.server: " + MPRConstantes._MPR_CONTEXT_SERVER);
    logger.debug("          java.version: " + ctx.getEnvironment().getProperty("java.version"));
    logger.debug("");
    logger.debug("     Parametrizacion GENERAL DEL SISTEMA");
    logger.debug("          mpr.enable.technical.information: " + MPRConstantes._ENABLE_TECHNICAL_INFORMATION);
    logger.debug("     Parametrizacion de CONEXION A EMPI");
    logger.debug("          mpr.empi.enable: " + MPRConstantes._EMPI_ENABLE);
    logger.debug("          mpr.empi.usuario: " + MPRConstantes._EMPI_USUARIO);
    logger.debug("          mpr.empi.sistema: " + MPRConstantes._EMPI_SISTEMA);
    logger.debug("          mpr.empi.url: " + MPRConstantes._EMPI_URL);
    logger.debug("     Parametrizacion de TAREAS PROGRAMADAS");
    logger.debug(
            "          mpr.task.buzon.in.process.messages: " + MPRConstantes._TASK_BUZON_IN_PROCESS_MESSAGES);
    logger.debug(
            "          mpr.task.buzon.out.process.messages: " + MPRConstantes._TASK_BUZON_OUT_PROCESS_MESSAGES);
    logger.debug("          mpr.task.buzon.in.his.clean: " + MPRConstantes._TASK_BUZON_IN_HIS_CLEAN);
    logger.debug("          mpr.task.buzon.out.his.clean: " + MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN);
    logger.debug("          mpr.task.buzon.in.his.clean.old: " + MPRConstantes._TASK_BUZON_IN_HIS_CLEAN_OLD);
    logger.debug("          mpr.task.buzon.out.his.clean.old: " + MPRConstantes._TASK_BUZON_OUT_HIS_CLEAN_OLD);
    logger.debug("          mpr.task.buzon.in.clean: " + MPRConstantes._TASK_BUZON_IN_CLEAN);
    logger.debug("          mpr.task.buzon.out.clean: " + MPRConstantes._TASK_BUZON_OUT_CLEAN);
    logger.debug("          mpr.task.buzon.errores.clean: " + MPRConstantes._TASK_BUZON_ERRORES_CLEAN);
    logger.debug("     Variables de ENTORNO de utilidad");
    logger.debug("          catalina.home: " + ctx.getEnvironment().getProperty("catalina.home"));
    logger.debug("          jboss.home.dir: " + ctx.getEnvironment().getProperty("jboss.home.dir"));
    logger.info("Modulo [" + MPRConstantes._MPR_CONTEXT_NAME + "] iniciado correctamente");
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationProcessor.java

public List<APIResourceConfiguration> extractAPIInfo(final ServletContext servletContext,
        Set<String> entityClasses) throws ClassNotFoundException {
    List<APIResourceConfiguration> apiResourceConfigs = new ArrayList<APIResourceConfiguration>();
    if (entityClasses != null && !entityClasses.isEmpty()) {
        for (final String className : entityClasses) {
            APIResourceConfiguration apiResourceConfiguration = AccessController
                    .doPrivileged(new PrivilegedAction<APIResourceConfiguration>() {
                        public APIResourceConfiguration run() {
                            Class<?> clazz = null;
                            APIResourceConfiguration apiResourceConfig = null;
                            try {
                                clazz = classLoader.loadClass(className);
                                Annotation swaggerDefinition = clazz.getAnnotation(apiClazz);
                                Annotation Scopes = clazz.getAnnotation(scopesClass);
                                List<APIResource> resourceList;
                                if (swaggerDefinition != null) {
                                    if (log.isDebugEnabled()) {
                                        log.debug("Application Context root = "
                                                + servletContext.getContextPath());
                                    }/*from   w  ww  .  j  a  v  a  2s  .c o  m*/
                                    try {
                                        apiResourceConfig = processAPIAnnotation(swaggerDefinition);
                                        if (Scopes != null) {
                                            apiScopes = processAPIScopes(Scopes);
                                        }
                                        if (apiResourceConfig != null) {
                                            String rootContext = servletContext.getContextPath();
                                            pathClazzMethods = pathClazz.getMethods();
                                            Annotation rootContectAnno = clazz.getAnnotation(pathClazz);
                                            String subContext;
                                            if (rootContectAnno != null) {
                                                subContext = invokeMethod(pathClazzMethods[0], rootContectAnno,
                                                        STRING);
                                                if (subContext != null && !subContext.isEmpty()) {
                                                    if (subContext.trim().startsWith("/")) {
                                                        rootContext = rootContext + subContext;
                                                    } else {
                                                        rootContext = rootContext + "/" + subContext;
                                                    }
                                                }
                                                if (log.isDebugEnabled()) {
                                                    log.debug("API Root  Context = " + rootContext);
                                                }
                                            }
                                            Method[] annotatedMethods = clazz.getDeclaredMethods();
                                            resourceList = getApiResources(rootContext, annotatedMethods);
                                            apiResourceConfig.setResources(resourceList);
                                        }

                                    } catch (Throwable throwable) {
                                        log.error("Error encountered while scanning for annotations",
                                                throwable);
                                    }
                                }
                            } catch (ClassNotFoundException e1) {
                                String msg = "Failed to load service class " + className
                                        + " for publishing APIs." + " This API will not be published.";
                                log.error(msg, e1);
                            } catch (RuntimeException e) {
                                log.error("Unexpected error has been occurred while publishing " + className
                                        + "hence, this API will not be published.");
                                throw new RuntimeException(e);
                            }
                            return apiResourceConfig;
                        }
                    });
            if (apiResourceConfiguration != null)
                apiResourceConfigs.add(apiResourceConfiguration);
        }
    }
    return apiResourceConfigs;
}

From source file:com.dominion.salud.pedicom.configuration.PEDICOMInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.scan("com.dominion.salud.pedicom.configuration");
    ctx.setServletContext(servletContext);
    PEDICOMConstantes._NOMBRE_CONFIG = servletContext.getInitParameter("NOMBRE_CONFIG");
    System.setProperty("pedicom.conf.home", findConfigurationAndLogger(ctx));
    ctx.refresh();//www.j ava 2  s  .co m

    // Spring Dispatcher
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(ctx));
    dispatcher.setInitParameter("contextClass", ctx.getClass().getName());
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.addMapping("/controller/*");
    servletContext.addListener(new ContextLoaderListener(ctx));

    // Configuracion general
    PEDICOMConstantes._HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator)
            ? servletContext.getRealPath("/")
            : servletContext.getRealPath("/") + File.separator;
    PEDICOMConstantes._CONF_HOME = ctx.getEnvironment().getProperty("pedicom.conf.home");
    PEDICOMConstantes._TEMP = PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "temp" + File.separator;
    PEDICOMConstantes._VERSION = ResourceBundle.getBundle("version").getString("version");
    PEDICOMConstantes._LOGS = PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator
            + "logs";
    PEDICOMConstantes._CONTEXT_NAME = servletContext.getServletContextName();
    PEDICOMConstantes._CONTEXT_PATH = servletContext.getContextPath();
    PEDICOMConstantes._CONTEXT_SERVER = servletContext.getServerInfo();
    PEDICOMConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("pedicom.enable.technical.information"))
                    ? Boolean.parseBoolean(ResourceBundle.getBundle("application")
                            .getString("pedicom.enable.technical.information"))
                    : false;
    PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = StringUtils
            .isNotBlank(ResourceBundle.getBundle("application").getString("pedicom_scheduler_send_mail_cron"))
                    ? PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = ResourceBundle.getBundle("application")
                            .getString("pedicom_scheduler_send_mail_cron")
                    : PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON;
    PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("pedicom_scheduler_update_existencias_cron"))
                    ? PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = ResourceBundle.getBundle("application")
                            .getString("pedicom_scheduler_update_existencias_cron")
                    : PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON;

    // Configuracion de LOGS DEL MODULO
    if (StringUtils.isBlank(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())) {
        ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE"))
                .setFile(PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator
                        + "logs" + File.separator + "mpr-desktop.log");
    }
    PEDICOMConstantes._LOGS = new File(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())
                    .getParent();

    Environment env = ctx.getEnvironment();

    XmlUnmarshaler xml = new XmlUnmarshaler();
    Datos datos = (Datos) xml.unmarshal();
    logger.info("          Datasources");
    for (Datasources dat : datos.getDatasources()) {
        if (dat.getNombreDatasource().equals("Central")) {
            PEDICOMConstantes.EXISTENCIAS_EXISTE = true;
        }
        logger.info("               codCentro: " + dat.getCodCentro());
        logger.info("               nombreDatasource: " + dat.getNombreDatasource());
        logger.info("               driverClassName: " + dat.getDriverClassName());
        logger.info("               jndi: " + dat.getJndi());
        logger.info("               url: " + dat.getUrl());
        logger.info("               username: " + dat.getUsername());
        logger.info("               usernameEmail: " + dat.getUsernameEmail());
        logger.info("               passwordEmail: " + dat.getPasswordEmail());
        logger.info("               from: " + dat.getFrom());
        logger.info("               host: " + dat.getHost());
        logger.info("               port: " + dat.getPort());
        logger.info("               TLS: " + dat.getTLS());
        logger.info("               SSL: " + dat.getSSL());
    }
    //        ctx.refresh();
    //        PropertyConfigurator.configureAndWatch("log4j");

    logger.info("          Configuracion general del sistema");
    logger.info("               pedicom.home: " + PEDICOMConstantes._HOME);
    logger.info("               pedicom.conf.home: " + PEDICOMConstantes._CONF_HOME);
    logger.info("               pedicom.temp: " + PEDICOMConstantes._TEMP);
    logger.info("               pedicom.version: " + PEDICOMConstantes._VERSION);
    logger.info("               pedicom.logs: " + PEDICOMConstantes._LOGS);
    logger.info("               pedicom.context.name: " + PEDICOMConstantes._CONTEXT_NAME);
    logger.info("               pedicom.context.path: " + PEDICOMConstantes._CONTEXT_PATH);
    logger.info("               pedicom.context.server: " + PEDICOMConstantes._CONTEXT_SERVER);
    logger.info("          Parametrizacion del sistema");
    logger.info("               pedicom.enable.technical.information: "
            + PEDICOMConstantes._ENABLE_TECHNICAL_INFORMATION);
    logger.info(
            "               pedicom_scheduler_send_mail_cron: " + PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON);
    logger.info("               pedicom_scheduler_update_existencias_cron: "
            + PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON);
    logger.info("     Modulo configurado correctamente");
    logger.info("MODULO INICIADO CORRECTAMENTE");
}