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:edu.cornell.mannlib.vitro.webapp.search.solr.SolrSetup.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    StartupStatus ss = StartupStatus.getBean(context);

    /* setup the http connection with the solr server */
    String solrServerUrlString = ConfigurationProperties.getBean(sce).getProperty("vitro.local.solr.url");
    if (solrServerUrlString == null) {
        ss.fatal(this, "Could not find vitro.local.solr.url in deploy.properties.  "
                + "Vitro application needs a URL of a solr server that it can use to index its data. "
                + "It should be something like http://localhost:${port}" + context.getContextPath() + "solr");
        return;/*www  .  j a  v a2  s  .  c o  m*/
    }

    URL solrServerUrl = null;
    try {
        solrServerUrl = new URL(solrServerUrlString);
    } catch (MalformedURLException e) {
        ss.fatal(this,
                "Can't connect with the solr server. "
                        + "The value for vitro.local.solr.url in deploy.properties is not a valid URL: "
                        + solrServerUrlString);
        return;
    }

    try {
        CommonsHttpSolrServer server;
        boolean useMultiPartPost = true;
        //It would be nice to use the default binary handler but there seem to be library problems
        server = new CommonsHttpSolrServer(solrServerUrl, null, new XMLResponseParser(), useMultiPartPost);
        server.setSoTimeout(10000); // socket read timeout
        server.setConnectionTimeout(10000);
        server.setDefaultMaxConnectionsPerHost(100);
        server.setMaxTotalConnections(100);
        server.setMaxRetries(1);

        context.setAttribute(SOLR_SERVER, server);

        /* set up the individual to solr doc translation */
        OntModel jenaOntModel = ModelContext.getJenaOntModel(context);
        Model displayModel = ModelContext.getDisplayModel(context);

        /* try to get context attribute DocumentModifiers 
         * and use that as the start of the list of DocumentModifier 
         * objects.  This allows other ContextListeners to add to 
         * the basic set of DocumentModifiers. */
        @SuppressWarnings("unchecked")
        List<DocumentModifier> modifiers = (List<DocumentModifier>) context.getAttribute("DocumentModifiers");
        if (modifiers == null)
            modifiers = new ArrayList<DocumentModifier>();

        modifiers.add(new NameFields(RDFServiceUtils.getRDFServiceFactory(context)));
        modifiers.add(new NameBoost(1.2f));
        modifiers.add(new ThumbnailImageURL(jenaOntModel));

        /* try to get context attribute SearchIndexExcludes 
         * and use that as the start of the list of exclude 
         * objects.  This allows other ContextListeners to add to 
         * the basic set of SearchIndexExcludes . */
        @SuppressWarnings("unchecked")
        List<SearchIndexExcluder> excludes = (List<SearchIndexExcluder>) context
                .getAttribute("SearchIndexExcludes");
        if (excludes == null)
            excludes = new ArrayList<SearchIndexExcluder>();

        excludes.add(new ExcludeBasedOnNamespace(INDIVIDUAL_NS_EXCLUDES));
        excludes.add(new ExcludeBasedOnTypeNamespace(TYPE_NS_EXCLUDES));
        excludes.add(new ExcludeBasedOnType(OWL_TYPES_EXCLUDES));
        excludes.add(new ExcludeNonFlagVitro());
        excludes.add(new SyncingExcludeBasedOnType(displayModel));

        IndividualToSolrDocument indToSolrDoc = new IndividualToSolrDocument(excludes, modifiers);

        /* setup solr indexer */
        SolrIndexer solrIndexer = new SolrIndexer(server, indToSolrDoc);

        // This is where the builder gets the list of places to try to
        // get objects to index. It is filtered so that non-public text
        // does not get into the search index.
        WebappDaoFactory wadf = (WebappDaoFactory) context.getAttribute("webappDaoFactory");
        VitroFilters vf = VitroFilterUtils.getPublicFilter(context);
        wadf = new WebappDaoFactoryFiltering(wadf, vf);

        // make objects that will find additional URIs for context nodes etc
        List<StatementToURIsToUpdate> uriFinders = makeURIFinders(jenaOntModel, wadf.getIndividualDao());

        // Make the IndexBuilder
        IndexBuilder builder = new IndexBuilder(solrIndexer, wadf, uriFinders);
        // Save it to the servlet context so we can access it later in the webapp.
        context.setAttribute(IndexBuilder.class.getName(), builder);

        // set up listeners so search index builder is notified of changes to model
        ServletContext ctx = sce.getServletContext();
        SearchReindexingListener srl = new SearchReindexingListener(builder);
        ModelContext.registerListenerForChanges(ctx, srl);

        ss.info(this, "Setup of Solr index completed.");
    } catch (Throwable e) {
        ss.fatal(this, "could not setup local solr server", e);
    }

}

From source file:com.liferay.arquillian.DeployerServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    try {/* ww w .  j av a  2  s. co  m*/
        InputStream bundleInputStream = getUploadedBundleInputStream(request);

        BundleContext bundleContext = _bundle.getBundleContext();

        Bundle newBundle = bundleContext.installBundle(_deployerServletInstallLocation, bundleInputStream);

        newBundle.start();

        Filter bundleContextFilter = bundleContext
                .createFilter("(&(objectClass=com.liferay.httpservice.internal.servlet."
                        + "BundleServletContext)(bundle.id=" + newBundle.getBundleId() + "))");

        ServiceTracker servletContextServiceTracker = new ServiceTracker(bundleContext, bundleContextFilter,
                null);

        servletContextServiceTracker.open();

        ServletContext servletContext = (ServletContext) servletContextServiceTracker
                .waitForService(_installTimeout);

        Servlet arquillianServletRunner = waitForServlet(servletContext, "ArquillianServletRunner",
                _installTimeout);

        if (arquillianServletRunner == null) {
            throw new TimeoutException(
                    "The arquillian servlet runner is taking more than " + _installTimeout + " to deploy");
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(TEXT);
        response.setHeader(_contextPathHeader, servletContext.getContextPath());
    } catch (Exception e) {
        signalError(e, response);
    } finally {
        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.flush();
    }
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Gets an absolute path to CKFinder file or folder for which path was provided as parameter.
 *
 * @param path relative or absolute path to a CKFinder resource (file or folder).
 * @param isAbsolute flag indicating if path to resource is absolute e.g. /usr/john/userfiles or "C:\\userfiles". If this parameter is
 * set to true path will be returned as is.
 * @param shouldExist flag indicating if resource, represented by path parameter, should exist (e.g. configuration file) in file system
 * or not (e.g. userfiles folder).<br>
 * If this parameter is set to true, path to file will only be returned if such file exists. If file can't be found, method will return
 * null./* w ww. j a v a  2 s. c om*/
 * @return an absolute path to a resource in CKFinder
 * @throws ConnectorException when {@code ServletContext} is {@code null} or full path to resource cannot be obtained.
 */
public static String getFullPath(String path, boolean isAbsolute, boolean shouldExist)
        throws ConnectorException {
    if (path != null && !path.equals("")) {
        if (isAbsolute) {
            if (path.startsWith("/")) {
                //Check if this isn't Windows Path.
                String temporary = PathUtils.removeSlashFromBeginning(path);
                if (isStartsWithPattern(drivePatt, temporary)) {
                    path = temporary;
                }
            }
            return checkAndReturnPath(shouldExist, path);
        } else {
            ServletContext sc = ServletContextFactory.getServletContext();
            String tempPath = PathUtils.addSlashToEnd(PathUtils.addSlashToBeginning(path));
            try {
                java.net.URL url = sc.getResource(tempPath);
                //For srevers like Tomcat 6-7 the getResource method returns JNDI URL.
                if (url != null && url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("jndi")) {
                    //Assume file is inside application context and try to get path.
                    //This method will fail if war is not exploaded.
                    String result = sc.getRealPath(tempPath.replace(sc.getContextPath(), ""));
                    if (result != null) {
                        return result;
                    } else {
                        //If application is packed, we have to try constructing the path manually.
                        result = getClassPath();
                        if (tempPath.indexOf(sc.getContextPath() + "/") >= 0
                                && result.indexOf(sc.getContextPath() + "/") >= 0) {
                            result = result.substring(0, result.indexOf(sc.getContextPath()));
                            result = result + tempPath;
                        } else if (result.indexOf(sc.getContextPath() + "/") >= 0) {
                            result = result.substring(0,
                                    result.indexOf(sc.getContextPath()) + sc.getContextPath().length());
                            result = result + tempPath;
                        }

                        result = checkAndReturnPath(shouldExist, result);
                        if (result != null) {
                            return result;
                        }
                    }

                    //At this stage path is not in application context and is not absolute.
                    //We need to reset url as we cannot determine path from it.
                    if (result == null) {
                        url = null;
                    }
                }

                //For servers like Tomact 8 getResource method should return file:// url.
                if (path.startsWith("/") || isStartsWithPattern(drivePatt, path)) {
                    //This is most likely absolute path.
                    String absolutePath = checkAndReturnPath(shouldExist, path);
                    if (absolutePath != null && !absolutePath.equals("")) {
                        return absolutePath;
                    } else {
                        //If absolute path has failed, give it one last try with relative path.
                        //Either path or null will be returned.
                        return sc.getRealPath(path.replace(sc.getContextPath(), ""));
                    }
                }
            } catch (IOException ioex) {
                throw new ConnectorException(ioex);
            }
        }
    }
    return null;
}

From source file:org.projectforge.web.wicket.WicketApplication.java

@Override
protected void init() {
    super.init();
    // Own error page for deployment mode and UserException and AccessException.
    getRequestCycleListeners().add(new AbstractRequestCycleListener() {
        /**// w w  w.j a va2s.c  o m
         * Log only non ProjectForge exceptions.
         * @see org.apache.wicket.request.cycle.AbstractRequestCycleListener#onException(org.apache.wicket.request.cycle.RequestCycle,
         *      java.lang.Exception)
         */
        @Override
        public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
            // in case of expired session, please redirect to home page
            if (ex instanceof PageExpiredException) {
                return new RenderPageRequestHandler(new PageProvider(getHomePage()));
            }
            final Throwable rootCause = ExceptionHelper.getRootCause(ex);
            // log.error(rootCause.getMessage(), ex);
            // if (rootCause instanceof ProjectForgeException == false) {
            // return super.onException(cycle, ex);
            // }
            // return null;
            if (isDevelopmentSystem() == true) {
                log.error(ex.getMessage(), ex);
                if (rootCause instanceof SQLException) {
                    SQLException next = (SQLException) rootCause;
                    while ((next = next.getNextException()) != null) {
                        log.error(next.getMessage(), next);
                    }
                }
                return super.onException(cycle, ex);
            } else {
                // Show always this error page in production mode:
                return new RenderPageRequestHandler(new PageProvider(new ErrorPage(ex)));
            }
        }
    });

    getApplicationSettings().setDefaultMaximumUploadSize(Bytes.megabytes(100));
    getMarkupSettings().setDefaultMarkupEncoding("utf-8");
    final MyAuthorizationStrategy authStrategy = new MyAuthorizationStrategy();
    getSecuritySettings().setAuthorizationStrategy(authStrategy);
    getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy);
    // Prepend the resource bundle for overwriting some Wicket default localizations (such as StringValidator.*)
    getResourceSettings().getStringResourceLoaders().add(new BundleStringResourceLoader(RESOURCE_BUNDLE_NAME));
    getResourceSettings().setThrowExceptionOnMissingResource(false); // Don't throw MissingResourceException for missing i18n keys.
    getApplicationSettings().setPageExpiredErrorPage(PageExpiredPage.class); // Don't show expired page.
    // getSessionSettings().setMaxPageMaps(20); // Map up to 20 pages per session (default is 5).
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
    getApplicationSettings().setInternalErrorPage(ErrorPage.class);
    // getRequestCycleSettings().setGatherExtendedBrowserInfo(true); // For getting browser width and height.

    // Select2:
    // final ApplicationSettings select2Settings = ApplicationSettings.get();
    // select2Settings.setIncludeJavascript(false);

    final XmlWebApplicationContext webApplicationContext = (XmlWebApplicationContext) WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    final ConfigurableListableBeanFactory beanFactory = webApplicationContext.getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) beanFactory
            .getBean("&sessionFactory");

    // if ("true".equals(System.getProperty(SYSTEM_PROPERTY_HSQLDB_18_UPDATE)) == true) {
    // try {
    // log.info("Send SHUTDOWN COMPACT to upgrade data-base version:");
    // final DataSource dataSource = (DataSource)beanFactory.getBean("dataSource");
    // dataSource.getConnection().createStatement().execute("SHUTDOWN COMPACT");
    // log.fatal("************ PLEASE RESTART APPLICATION NOW FOR PROPER INSTALLATION !!!!!!!!!!!!!! ************");
    // return;
    // } catch (final SQLException ex) {
    // log.fatal("Data-base SHUTDOWN COMPACT failed: " + ex.getMessage());
    // }
    // }
    final org.hibernate.cfg.Configuration hibernateConfiguration = localSessionFactoryBean.getConfiguration();
    HibernateUtils.setConfiguration(hibernateConfiguration);
    final ServletContext servletContext = getServletContext();
    final String configContextPath = configXml.getServletContextPath();
    String contextPath;
    if (StringUtils.isBlank(configContextPath) == true) {
        contextPath = servletContext.getContextPath();
        configXml.setServletContextPath(contextPath);
    } else {
        contextPath = configContextPath;
    }
    log.info("Using servlet context path: " + contextPath);
    if (configuration.getBeanFactory() == null) {
        configuration.setBeanFactory(beanFactory);
    }
    configuration.setConfigurationDao(configurationDao);
    SystemInfoCache.internalInitialize(systemInfoCache);
    WicketUtils.setContextPath(contextPath);
    UserFilter.initialize(userDao, contextPath);
    if (this.wicketApplicationFilter != null) {
        this.wicketApplicationFilter.setApplication(this);
    } else {
        throw new RuntimeException("this.wicketApplicationFilter is null");
    }
    daoRegistry.init();

    final PluginsRegistry pluginsRegistry = PluginsRegistry.instance();
    pluginsRegistry.set(beanFactory, getResourceSettings());
    pluginsRegistry.set(systemUpdater);
    pluginsRegistry.initialize();

    for (final Map.Entry<String, Class<? extends WebPage>> mountPage : WebRegistry.instance().getMountPages()
            .entrySet()) {
        final String path = mountPage.getKey();
        final Class<? extends WebPage> pageClass = mountPage.getValue();
        mountPage(path, pageClass);
        mountedPages.put(pageClass, path);
    }
    if (isDevelopmentSystem() == true) {
        if (isStripWicketTags() == true) {
            log.info("Strip Wicket tags also in development mode at default (see context.xml).");
            Application.get().getMarkupSettings().setStripWicketTags(true);
        }
        getDebugSettings().setOutputMarkupContainerClassName(true);
    }
    log.info("Default TimeZone is: " + TimeZone.getDefault());
    if ("UTC".equals(TimeZone.getDefault().getID()) == false) {
        for (final String str : UTC_RECOMMENDED) {
            log.fatal(str);
        }
        for (final String str : UTC_RECOMMENDED) {
            System.err.println(str);
        }
    }
    log.info("user.timezone is: " + System.getProperty("user.timezone"));
    cronSetup.initialize();
    log.info(AppVersion.APP_ID + " " + AppVersion.NUMBER + " (" + AppVersion.RELEASE_TIMESTAMP
            + ") initialized.");

    PFUserContext.setUser(DatabaseUpdateDao.__internalGetSystemAdminPseudoUser()); // Logon admin user.
    if (systemUpdater.isUpdated() == false) {
        // Force redirection to update page:
        UserFilter.setUpdateRequiredFirst(true);
    }
    PFUserContext.setUser(null);
    UserXmlPreferencesCache.setInternalInstance(userXmlPreferencesCache);
    LoginHandler loginHandler;
    if (StringUtils.isNotBlank(configXml.getLoginHandlerClass()) == true) {
        loginHandler = (LoginHandler) BeanHelper.newInstance(configXml.getLoginHandlerClass());
    } else {
        loginHandler = new LoginDefaultHandler();
    }
    if (loginHandler == null) {
        log.error("Can't load login handler '" + configXml.getLoginHandlerClass()
                + "'. No login will be possible!");
    } else {
        loginHandler.initialize();
        Login.getInstance().setLoginHandler(loginHandler);
    }
    try {
        StorageClient.getInstance(); // Initialize storage
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
    }
    getPageSettings().setRecreateMountedPagesAfterExpiry(false);

    // initialize ical4j to be more "relaxed"
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);

    // initialize styles compiler
    try {
        final LessWicketApplicationInstantiator lessInstantiator = new LessWicketApplicationInstantiator(this,
                "styles", "projectforge.less", "projectforge.css");
        lessInstantiator.instantiate();
    } catch (final Exception e) {
        log.error("Unable to instantiate wicket less compiler", e);
    }
}

From source file:com.datascience.gal.service.Service.java

private void setup(ServletContext scontext) throws IOException, ClassNotFoundException, SQLException {
    if (dscache == null) {
        logger.info("loading props file with context:" + scontext.getContextPath());
        Properties props = new Properties();
        props.load(scontext.getResourceAsStream("/WEB-INF/classes/dawidskene.properties"));
        dscache = new DawidSkeneCache(props);
    }/* ww  w  .  j  a  v  a 2  s.  c  o m*/
}

From source file:com.nec.harvest.servlet.listener.WebApplicationContextLoaderListener.java

/**
 * Initialize the root web application context
 *///w  w  w  . ja  v  a2 s  .co  m
@Override
public void contextInitialized(ServletContextEvent event) {
    super.contextInitialized(event);

    // Starting Harvest environment initialization...
    if (logger.isDebugEnabled()) {
        logger.debug("Starting Harvest environment initialization...");
    }

    /// You can get Servlet Context
    ServletContext servletContext = event.getServletContext();
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    String jasperReportPath = getReportPath(webApplicationContext);

    // Create new a folder to store all of reports
    logger.info("Trying to create a new local storage {} folder for all reports", jasperReportPath);

    File folder = new File(jasperReportPath);
    if (!folder.exists()) {
        folder.mkdirs();
    }

    // ????
    logger.info("Successfully created a report storage folder to store all of temporary reports");

    // 
    logger.info("Context instance: {}", webApplicationContext);
    logger.info("Application name: {} && path: {}", webApplicationContext.getApplicationName(),
            servletContext.getContextPath());
}

From source file:org.red5.server.undertow.UndertowLoader.java

/**
 * Initialization.//from   w ww  . j ava  2  s .co  m
 */
public void start() {
    log.info("Loading undertow context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // scan the sub directories to determine our context paths
    buildContextPathList(webappFolder);
    try {
        // create our servlet container
        container = ServletContainer.Factory.newInstance();
        // create a root path handler
        final PathHandler rootHandler = new PathHandler();
        // create one server and use it everywhere
        Undertow.Builder builder = Undertow.builder();
        // loop through connectors adding listeners to the builder
        for (UndertowConnector undertowConnector : connectors) {
            InetSocketAddress addr = undertowConnector.getSocketAddress();
            builder.addListener(addr.getPort(), addr.getHostName(),
                    (undertowConnector.isSecure() ? ListenerType.HTTPS : ListenerType.HTTP));
        }
        log.trace("Classloader for undertow: {} TCL: {}", Undertow.class.getClassLoader(), originalClassLoader);
        // create references for later lookup
        LoaderBase.setApplicationLoader(new UndertowApplicationLoader(container, applicationContext));
        // loop the other contexts
        for (String contextPath : contextPaths) {
            // create a class loader for the context
            ClassLoader classLoader = buildWebClassLoader(originalClassLoader, webappFolder, contextPath);
            // create deployment info
            DeploymentInfo info = deployment().setClassLoader(classLoader)
                    .setContextPath(contextPath.equalsIgnoreCase("/ROOT") ? "/" : contextPath)
                    .setDefaultEncoding("UTF-8").setDeploymentName(contextPath.substring(1) + ".war")
                    .setUrlEncoding("UTF-8");
            // parse the web.xml and configure the context
            parseWebXml(webappFolder, contextPath, info);
            if (log.isDebugEnabled()) {
                log.debug("Deployment info - name: {} servlets: {} filters: {}", new Object[] {
                        info.getDisplayName(), info.getServlets().size(), info.getFilters().size() });
            }
            // add the new deployment to the servlet container
            DeploymentManager manager = container.addDeployment(info);
            // set a reference to the manager and deploy the context
            LoaderBase.setRed5ApplicationContext(contextPath, new UndertowApplicationContext(manager));
            // deploy
            manager.deploy();
            // add path
            rootHandler.addPrefixPath(info.getContextPath(), manager.start());
            // get deployment
            Deployment deployment = manager.getDeployment();
            // get servlet context
            final ServletContext servletContext = deployment.getServletContext();
            log.debug("Context initialized: {}", servletContext.getContextPath());
            try {
                log.debug("Context: {}", servletContext);
                final ClassLoader webClassLoader = info.getClassLoader();
                log.debug("Webapp classloader: {}", webClassLoader);
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                // set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);
                // create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(webClassLoader);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        // web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            // set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                            appctx.start();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class", e);
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
        // Dump deployments list
        if (log.isDebugEnabled()) {
            for (String deployment : container.listDeployments()) {
                log.debug("Container deployment: {}", deployment);
            }
        }
        // if everything is ok at this point then call the rtmpt and rtmps beans so they will init
        //         if (applicationContext.containsBean("rtmpt.server")) {
        //            log.debug("Initializing RTMPT");
        //            applicationContext.getBean("rtmpt.server");
        //            log.debug("Finished initializing RTMPT");
        //         } else {
        //            log.info("Dedicated RTMPT server configuration was not specified");
        //         }
        //         if (applicationContext.containsBean("rtmps.server")) {
        //            log.debug("Initializing RTMPS");
        //            applicationContext.getBean("rtmps.server");
        //            log.debug("Finished initializing RTMPS");
        //         } else {
        //            log.debug("Dedicated RTMPS server configuration was not specified");
        //         }
        // add a root handler
        builder.setHandler(rootHandler);
        // build the server instance
        server = builder.build();
        log.info("Starting Undertow");
        server.start();
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading undertow, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading undertow", e);
        }
    } finally {
        registerJMX();
    }
    log.debug("Undertow init exit");
}

From source file:org.apache.wookie.server.ContextListener.java

/**
 * Starts a watcher thread for hot-deploy of new widgets dropped into the deploy folder
 * this is controlled using the <code>widget.hot_deploy=true|false</code> property 
 * and configured to look in the folder specified by the <code>widget.deployfolder</code> property
 * @param context the current servlet context
 * @param configuration the configuration properties
 *//*from  w  w  w .  j a va  2  s.c  om*/
private void startWatcher(ServletContext context, Configuration configuration,
        final Messages localizedMessages) {
    /*
     * Start watching for widget deployment
     */
    final File deploy = new File(WidgetPackageUtils
            .convertPathToPlatform(context.getRealPath(configuration.getString("widget.deployfolder"))));
    final String UPLOADFOLDER = context.getRealPath(configuration.getString("widget.useruploadfolder"));
    final String WIDGETFOLDER = context.getRealPath(configuration.getString("widget.widgetfolder"));
    final String localWidgetFolderPath = configuration.getString("widget.widgetfolder");
    final String[] locales = configuration.getStringArray("widget.locales");
    final String contextPath = context.getContextPath();
    Thread thr = new Thread() {
        public void run() {
            int interval = 5000;
            WgtWatcher watcher = new WgtWatcher();
            watcher.setWatchDir(deploy);
            watcher.setListener(new WgtWatcher.FileChangeListener() {
                public void fileModified(File f) {
                    // get persistence manager for this thread
                    IPersistenceManager persistenceManager = PersistenceManagerFactory.getPersistenceManager();
                    try {
                        persistenceManager.begin();
                        File upload = WidgetFileUtils.dealWithDroppedFile(UPLOADFOLDER, f);
                        W3CWidgetFactory fac = new W3CWidgetFactory();
                        fac.setLocales(locales);
                        fac.setLocalPath(contextPath + localWidgetFolderPath);
                        fac.setOutputDirectory(WIDGETFOLDER);
                        fac.setFeatures(persistenceManager.findServerFeatureNames());
                        fac.setStartPageProcessor(new StartPageProcessor());
                        W3CWidget model = fac.parse(upload);
                        WidgetJavascriptSyntaxAnalyzer jsa = new WidgetJavascriptSyntaxAnalyzer(
                                fac.getUnzippedWidgetDirectory());
                        if (persistenceManager.findWidgetByGuid(model.getIdentifier()) == null) {
                            WidgetFactory.addNewWidget(model, true);
                            String message = model.getLocalName("en") + "' - "
                                    + localizedMessages.getString("WidgetAdminServlet.19");
                            _logger.info(message);
                            FlashMessage.getInstance().message(message);
                        } else {
                            String message = model.getLocalName("en") + "' - "
                                    + localizedMessages.getString("WidgetAdminServlet.20");
                            _logger.info(message);
                            FlashMessage.getInstance().message(message);
                        }
                        persistenceManager.commit();
                    } catch (IOException e) {
                        persistenceManager.rollback();
                        String error = f.getName() + ":" + localizedMessages.getString("WidgetHotDeploy.1");
                        FlashMessage.getInstance().error(error);
                        _logger.error(error);
                    } catch (BadWidgetZipFileException e) {
                        persistenceManager.rollback();
                        String error = f.getName() + ":" + localizedMessages.getString("WidgetHotDeploy.2");
                        FlashMessage.getInstance().error(error);
                        _logger.error(error);
                    } catch (BadManifestException e) {
                        persistenceManager.rollback();
                        String error = f.getName() + ":" + localizedMessages.getString("WidgetHotDeploy.3");
                        FlashMessage.getInstance().error(error);
                        _logger.error(error);
                    } catch (Exception e) {
                        persistenceManager.rollback();
                        String error = f.getName() + ":" + e.getLocalizedMessage();
                        FlashMessage.getInstance().error(error);
                        _logger.error(error);
                    } finally {
                        // close thread persistence manager
                        PersistenceManagerFactory.closePersistenceManager();
                    }
                }

                public void fileRemoved(File f) {
                    // Not implemented - the .wgt files are removed as part of the deployment process
                }
            });
            try {
                while (true) {
                    watcher.check();
                    Thread.sleep(interval);
                }
            } catch (InterruptedException iex) {
            }
        }
    };

    thr.start();

}

From source file:org.lightadmin.core.config.StandardLightAdminConfiguration.java

public StandardLightAdminConfiguration(ServletContext servletContext) {
    this.basePackage = servletContext.getInitParameter(LIGHT_ADMINISTRATION_BASE_PACKAGE);

    this.applicationBaseUrl = servletContext.getInitParameter(LIGHT_ADMINISTRATION_BASE_URL);
    this.applicationBaseNoEndSeparator = urlWithoutEndSeparator(this.applicationBaseUrl);
    this.backToSiteUrl = backToSiteUrl(servletContext);
    this.helpUrl = helpUrl(servletContext);

    this.fileStorageDirectory = fileStorageDirectory(servletContext);
    this.fileStreaming = BooleanUtils
            .toBoolean(servletContext.getInitParameter(LIGHT_ADMINISTRATION_FILE_STREAMING));

    this.demoMode = BooleanUtils.toBoolean(servletContext.getInitParameter(LIGHT_ADMINISTRATION_DEMO_MODE));

    this.securityEnabled = BooleanUtils
            .toBoolean(servletContext.getInitParameter(LIGHT_ADMINISTRATION_SECURITY));
    if (securityEnabled) {
        this.securityLogoutUrl = servletContext.getContextPath() + this.applicationBaseNoEndSeparator
                + LIGHT_ADMIN_SECURITY_LOGOUT_URL_DEFAULT;
    } else {//ww  w .  jav a2s .  co  m
        this.securityLogoutUrl = servletContext.getContextPath() + defaultIfBlank(
                servletContext.getInitParameter(LIGHT_ADMINISTRATION_SECURITY_LOGOUT_URL), "#");
    }
}

From source file:org.springframework.web.context.ContextLoader.java

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,
        ServletContext sc) {
    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);/*  w w  w.  j ava  2 s . co m*/
        } else {
            // Generate default id...
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                    + ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }

    wac.setServletContext(sc);
    String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
    if (configLocationParam != null) {
        wac.setConfigLocation(configLocationParam);
    }

    // The wac environment's #initPropertySources will be called in any case when the context
    // is refreshed; do it eagerly here to ensure servlet property sources are in place for
    // use in any post-processing or initialization that occurs below prior to #refresh
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }

    customizeContext(sc, wac);
    wac.refresh();
}