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:fr.paris.lutece.portal.service.spring.SpringContextService.java

/**
 * Returns a name for this context/*from   w ww.ja v  a  2s  . com*/
 * @param servletContext the servlet context
 * @return name for this context
 */
private static String getContextName(ServletContext servletContext) {
    String name = "lutece";

    if (servletContext != null) {
        String contextName = servletContext.getServletContextName();

        if (contextName == null) {
            contextName = servletContext.getContextPath();
        }

        if (StringUtils.isNotBlank(contextName)) {
            name = contextName;
        }
    }

    return name;
}

From source file:org.red5.net.websocket.WebSocketPlugin.java

/**
 * Returns a new instance of WsServerContainer if one does not already exist.
 * // w w  w  . j a va  2 s . co  m
 * @param servletContext
 * @return WsServerContainer
 */
public static ServerContainer getWsServerContainerInstance(ServletContext servletContext) {
    String path = servletContext.getContextPath();
    // handle root
    if (path.length() == 0) {
        path = "/";
    }
    log.info("getWsServerContainerInstance: {}", path);
    DefaultWsServerContainer container;
    if (containerMap.containsKey(path)) {
        container = containerMap.get(path);
    } else {
        // instance a server container for WS
        container = new DefaultWsServerContainer(servletContext);
        if (log.isDebugEnabled()) {
            log.debug("Attributes: {} params: {}", Collections.list(servletContext.getAttributeNames()),
                    Collections.list(servletContext.getInitParameterNames()));
        }
        // get a configurator instance
        ServerEndpointConfig.Configurator configurator = (ServerEndpointConfig.Configurator) WebSocketPlugin
                .getWsConfiguratorInstance();
        // check for sub protocols
        log.debug("Checking for subprotocols");
        List<String> subProtocols = new ArrayList<>();
        Optional<Object> subProtocolsAttr = Optional
                .ofNullable(servletContext.getInitParameter("subProtocols"));
        if (subProtocolsAttr.isPresent()) {
            String attr = (String) subProtocolsAttr.get();
            log.debug("Subprotocols: {}", attr);
            if (StringUtils.isNotBlank(attr)) {
                if (attr.contains(",")) {
                    // split them up
                    Stream.of(attr.split(",")).forEach(entry -> {
                        subProtocols.add(entry);
                    });
                } else {
                    subProtocols.add(attr);
                }
            }
        } else {
            // default to allowing any subprotocol
            subProtocols.add("*");
        }
        log.debug("Checking for CORS");
        // check for allowed origins override in this servlet context
        Optional<Object> crossOpt = Optional.ofNullable(servletContext.getAttribute("crossOriginPolicy"));
        if (crossOpt.isPresent() && Boolean.valueOf((String) crossOpt.get())) {
            Optional<String> opt = Optional.ofNullable((String) servletContext.getAttribute("allowedOrigins"));
            if (opt.isPresent()) {
                ((DefaultServerEndpointConfigurator) configurator).setAllowedOrigins(opt.get().split(","));
            }
        }
        log.debug("Checking for endpoint override");
        // check for endpoint override and use default if not configured
        String wsEndpointClass = Optional.ofNullable((String) servletContext.getAttribute("wsEndpointClass"))
                .orElse("org.red5.net.websocket.server.DefaultWebSocketEndpoint");
        try {
            // locate the endpoint class
            Class<?> endpointClass = Class.forName(wsEndpointClass);
            log.debug("startWebSocket - endpointPath: {} endpointClass: {}", path, endpointClass);
            // build an endpoint config
            ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(endpointClass, path)
                    .configurator(configurator).subprotocols(subProtocols).build();
            // set the endpoint on the server container
            container.addEndpoint(serverEndpointConfig);
        } catch (Throwable t) {
            log.warn("WebSocket endpoint setup exception", t);
        }
        // store container for lookup
        containerMap.put(path, container);
        // add session listener
        servletContext.addListener(new HttpSessionListener() {

            @Override
            public void sessionCreated(HttpSessionEvent se) {
                log.debug("sessionCreated: {}", se.getSession().getId());
                ServletContext sc = se.getSession().getServletContext();
                // Don't trigger WebSocket initialization if a WebSocket Server Container is already present
                if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) {
                    // grab the container using the servlet context for lookup
                    DefaultWsServerContainer serverContainer = (DefaultWsServerContainer) WebSocketPlugin
                            .getWsServerContainerInstance(sc);
                    // set the container to the context for lookup
                    sc.setAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE, serverContainer);
                }
            }

            @Override
            public void sessionDestroyed(HttpSessionEvent se) {
                log.debug("sessionDestroyed: {}", se);
                container.closeAuthenticatedSession(se.getSession().getId());
            }

        });
    }
    // set the container to the context for lookup
    servletContext.setAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE, container);
    return container;
}

From source file:org.wso2.carbon.apimgt.everywhere.webapp.publisher.APIPublisherLifecycleListener.java

private static void showAPIinfo(ServletContext context, Class<?> clazz, Class<Path> pathClazz) {

    Annotation rootContectAnno = clazz.getAnnotation(pathClazz);

    log.info("======================== API INFO ======================= ");
    if (context != null) {
        log.info("Application Context root = " + context.getContextPath());
    }//w  w w.j a va2 s  .  c o  m

    if (rootContectAnno != null) {
        InvocationHandler handler = Proxy.getInvocationHandler(rootContectAnno);
        Method[] methods = pathClazz.getMethods();
        String root;

        try {
            root = (String) handler.invoke(rootContectAnno, methods[0], null);

            log.info("API Root  Context = " + root);
            log.info("API Sub Context List ");
            for (Method method : clazz.getDeclaredMethods()) {
                Annotation methodContextAnno = method.getAnnotation(pathClazz);
                if (methodContextAnno != null) {
                    InvocationHandler methodHandler = Proxy.getInvocationHandler(methodContextAnno);
                    String subCtx = (String) methodHandler.invoke(methodContextAnno, methods[0], null);
                    ;
                    log.info("  " + root + "/" + subCtx);
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        log.info("===================================================== ");
        //todo log.info summery of the api context info resulting from the scan
    }
}

From source file:org.artifactory.util.HttpUtils.java

public synchronized static String getContextId(ServletContext servletContext) {
    //If running servlet API 2.4, just return the servlet context name
    if (SERVLET_24) {
        return servletContext.getServletContextName();
    }/*w  ww. j a v  a  2s.com*/

    //If running v2.5, return proper context path
    String contextUniqueName = PathUtils.trimLeadingSlashes(servletContext.getContextPath());
    contextUniqueName = StringUtils.capitalize(contextUniqueName);
    return contextUniqueName;
}

From source file:com.ericsson.eif.hansoft.HansoftManager.java

/**
 * Hansoft adapter properties from adapter.properties
 * @param servletContext/*  w  w w  .  jav  a2 s.c o  m*/
 */
private static void init(ServletContext servletContext) {

    Properties props = new Properties();
    try {
        PROVIDER_CONTEXT_PATH = servletContext.getContextPath();
        if (PROVIDER_CONTEXT_PATH.isEmpty()) {
            String message = "No servlet context name provided, will exit.";
            logger.error(message);
            throw new RuntimeException(message);
        }

        String adapterHome = System.getenv("ADAPTER_HOME");
        if (adapterHome == null) {
            // default to user home
            adapterHome = System.getProperty("user.home");
        }

        // The PROVIDER_CONTEXT_PATH has a beginning "/" - remove
        String contextPath = PROVIDER_CONTEXT_PATH.substring(1);
        adapterServletHome = adapterHome + File.separator + contextPath;

        // Need the properties file - if not found, exit
        try {
            File propsPath = new File(adapterServletHome + File.separator + "adapter.properties");
            if (propsPath.exists()) {
                props.load(new FileInputStream(propsPath.toString()));
            } else {
                String message = "The adapter.properties file not found, will exit.";
                logger.error(message);
                throw new RuntimeException(message);
            }
        } catch (Exception e) {
            String message = "Failed to read the adapter.properties file, will exit.";
            logger.error(message, e);
            throw new RuntimeException(message);
        }

        // It is ok not having a log4j configuration file, but recommended
        try {
            File log4jPropsPath = new File(adapterServletHome + File.separator + "log4j.properties");
            if (log4jPropsPath.exists()) {
                // Allow using adapter home path in log4j file
                System.setProperty("hansoft.adapter_servlet_home", adapterServletHome);
                PropertyConfigurator.configure(log4jPropsPath.getPath());
            } else {
                logger.warn("The log4j.properties file not found.");
            }
        } catch (Exception e) {
            logger.warn("Failed to read the log4j.properties file.", e);
        }

        logger.info("Initialize of Hansoft adapter started ...");

        // We need to set the JNI path early, and failed when trying to
        // pass as input argument. Solution as below is working:
        //
        // From
        // http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/
        //
        // At first the system property is updated with the new value.
        // This might be a relative path  or maybe you want to create that
        // path dynamically.
        //
        // The Classloader has a static field (sys_paths) that contains the
        // paths. If that field is set to null, it is initialized
        // automatically. Therefore forcing that field to null will result
        // into the reevaluation of the library path as soon as
        // loadLibrary() is called
        hansoftSDKVersion = props.getProperty("hansoft_sdk_version", "").trim();
        if (hansoftSDKVersion == "") {
            String message = "SDK version not set, will exit.";
            logger.error(message);
            throw new RuntimeException(message);
        }

        try {
            hansoftLib = adapterHome + File.separator + "hansoft_libs" + File.separator + hansoftSDKVersion;
            File libPath = new File(hansoftLib);
            if (libPath.exists()) {
                System.setProperty("java.library.path", libPath.toString());
                Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
                fieldSysPath.setAccessible(true);
                fieldSysPath.set(null, null);
            } else {
                String message = "Hansoft libs for SDK version: " + hansoftSDKVersion
                        + " not found, will exit.";
                logger.error(message);
                throw new RuntimeException(message);
            }
        } catch (Exception e) {
            String message = "Failed configuring path for libs for SDK version: " + hansoftSDKVersion
                    + ", will exit.";
            logger.error(message);
            throw new RuntimeException(message);
        }

        hansoftWorkingDir = props.getProperty("hansoft_working_dir", "").trim();
        hansoftChangeLogDir = props.getProperty("hansoft_change_log_dir", "").trim();
        hansoftLogDir = props.getProperty("hansoft_log_dir", "").trim();
        hansoftServer = props.getProperty("hansoft_server", "").trim();
        hansoftPort = Integer.parseInt(props.getProperty("hansoft_port", "-1"));
        hansoftDatabase = props.getProperty("hansoft_database", "").trim();
        hansoftSDK = props.getProperty("hansoft_sdk_user", "").trim();
        hansoftSDKPassword = props.getProperty("hansoft_sdk_password", "").trim();
        hansoftAdapterServer = props.getProperty("hansoft_adapter_server", "").trim();
        hansoftAdapterServerScheme = props.getProperty("hansoft_adapter_server_scheme", "http").trim();
        hansoftAdapterServerPort = props.getProperty("hansoft_adapter_server_port", "8080").trim();
        validate_h2h_config = props.getProperty("validate_h2h_config", "false").trim();
        h2h_config_validation_output_to_file = props.getProperty("h2h_config_validation_output_to_file", "true")
                .trim();
        h2h_config_validation_output_on_screen = props
                .getProperty("h2h_config_validation_output_on_screen", "true").trim();

        OSLC_BACKLINK_COL_NAME = props.getProperty("hansoft_backlink", "OSLC Reference").trim();
        String FPs = props.getProperty("hansoft_fps", "").trim();
        setHansoftFPs(FPs);

        logger.log(Level.INFO, "Property hansoft_adapter_server = " + hansoftAdapterServer);
        logger.log(Level.INFO, "Property hansoft_adapter_server_scheme = " + hansoftAdapterServerScheme);
        logger.log(Level.INFO, "Property hansoft_adapter_server_port = " + hansoftAdapterServerPort);
        logger.log(Level.INFO, "Property hansoft_working_dir = " + hansoftWorkingDir);
        logger.log(Level.INFO, "Property hansoft_change_log_dir = " + hansoftChangeLogDir);
        logger.log(Level.INFO, "Property hansoft_log_dir = " + hansoftLogDir);
        logger.log(Level.INFO, "Property hansoft_server = " + hansoftServer);
        logger.log(Level.INFO, "Property hansoft_port = " + hansoftPort);
        logger.log(Level.INFO, "Property hansoft_database = " + hansoftDatabase);
        logger.log(Level.INFO, "Property hansoft_sdk_user = " + hansoftSDK);
        logger.log(Level.INFO, "Property hansoft_sdk_version = " + hansoftSDKVersion);
        logger.log(Level.INFO, "Property validate_h2h_config = " + validate_h2h_config);
        logger.log(Level.INFO,
                "Property h2h_config_validation_output_to_file = " + h2h_config_validation_output_to_file);
        logger.log(Level.INFO,
                "Property h2h_config_validation_output_on_screen = " + h2h_config_validation_output_on_screen);

        getMainSession();
        loadH2HConfiguration();
        if (validate_h2h_config.equalsIgnoreCase("true")) {
            validateH2Hconfiguration();
        }

        QSchedule.getInstance();

    } catch (SecurityException | IllegalArgumentException | HPMSdkException | HPMSdkJavaException e) {
        logger.error("Failed during static init of Hansoft Adapter", e);
    }
}

From source file:org.jumpmind.vaadin.ui.common.CommonUiUtils.java

public static AceEditor createAceEditor() {
    AceEditor editor = new AceEditor();
    editor.setSizeFull();//from  ww w . j  av a 2 s  .  co m
    editor.setImmediate(true);
    ServletContext context = VaadinServlet.getCurrent().getServletContext();
    if (context.getRealPath("/ace") != null) {
        String acePath = context.getContextPath() + "/ace";
        editor.setThemePath(acePath);
        editor.setModePath(acePath);
        editor.setWorkerPath(acePath);
    } else {
        log.warn("Could not find a local version of the ace editor.  "
                + "You might want to consider installing the ace web artifacts at " + context.getRealPath(""));
    }
    editor.setTextChangeEventMode(TextChangeEventMode.EAGER);
    editor.setHighlightActiveLine(true);
    editor.setShowPrintMargin(false);
    return editor;
}

From source file:nz.co.senanque.vaadinsupport.application.SpringApplicationLoader.java

public static ApplicationContext loadContext(Application application, HttpServletRequest request) {

    // Logging/* w ww  .ja va 2 s  . co m*/
    log.info("loading application context for Vaadin application " + application.getClass().getSimpleName());
    CURRENT_APPLICATION.set(application);

    // Find the application context associated with the servlet; it will be the parent
    ServletContext servletContext;
    try {
        // getServletContext() is a servlet AIP 3.0 method, so don't freak out if it's not there
        servletContext = (ServletContext) HttpServletRequest.class.getMethod("getServletContext")
                .invoke(request);
    } catch (Exception e) {
        servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
    }
    WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(servletContext);

    // Create and configure a new application context for this Application instance
    ConfigurableWebApplicationContext context = new XmlWebApplicationContext();
    context.setId(
            ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContext.getContextPath()
                    + "/" + application.getClass().getSimpleName() + "-" + UNIQUE_INDEX.incrementAndGet());
    context.setParent(parent);
    context.setServletContext(servletContext);
    //context.setServletConfig(??);
    context.setNamespace(application.getClass().getSimpleName());

    // Refresh context
    context.refresh();

    CURRENT_APPLICATION.set(null);
    return context;
}

From source file:cn.edu.zjnu.acm.judge.config.LocaleConfiguration.java

private String getCookiePath(ServletContext container) {
    String contextPath = container.getContextPath();
    return contextPath.endsWith("/") ? contextPath : contextPath + '/';
}

From source file:ar.com.zauber.commons.web.uri.factory.ServletPathUriFactory.java

/** @see ServletContextAware#setServletContext(ServletContext) */
public final void setServletContext(final ServletContext servletContext) {
    this.contextPath = servletContext.getContextPath();
}

From source file:org.jbpm.designer.filter.InjectionConfig.java

public InjectionConfig(ServletContext sc) {
    context = sc;
    load(sc.getContextPath());
}