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.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager.java

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {//from  w w  w. java  2 s .com
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantDomain(), parts[0],
                        parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {
                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                            // throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

From source file:org.red5.server.war.RootContextLoaderServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *///from  w w  w  .j  a v a 2s  . c om
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (instance) {
        logger.info("Webapp shutdown");
        // XXX Paul: grabbed this from
        // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
        // in hopes that we can clear all the issues with J2EE containers
        // during shutdown
        try {
            ServletContext ctx = sce.getServletContext();
            // if the ctx being destroyed is root then kill the timer
            if (ctx.getContextPath().equals("/ROOT")) {
                timer.cancel();
            } else {
                // remove from registered list
                registeredContexts.remove(ctx);
            }
            // prepare spring for shutdown
            Introspector.flushCaches();
            // dereg any drivers
            for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
                Driver driver = (Driver) e.nextElement();
                if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
            // shutdown jmx
            JMXAgent.shutdown();
            // shutdown spring
            Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (attr != null) {
                // get web application context from the servlet context
                ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr;
                ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
                // for (String scope : factory.getRegisteredScopeNames()) {
                // logger.debug("Registered scope: " + scope);
                // }
                try {
                    for (String singleton : factory.getSingletonNames()) {
                        logger.debug("Registered singleton: " + singleton);
                        factory.destroyScopedBean(singleton);
                    }
                } catch (RuntimeException e) {
                }
                factory.destroySingletons();

                ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                applicationContext.close();
            }
            instance.getContextLoader().closeWebApplicationContext(ctx);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
            // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
            LogFactory.release(Thread.currentThread().getContextClassLoader());
        }
    }
}

From source file:com.siberhus.web.ckeditor.servlet.OpenFileManagerConnectorServlet.java

/**
 * Filemanager connector/*from w  w w .  j av  a 2 s .  co  m*/
 * 
 */
public StreamingResult fileManager(HttpServletRequest request, HttpServletResponse response) throws Exception {
    log.debug("Begin fileManager()");
    String mode = request.getParameter("mode");
    String type = request.getParameter("type");
    String space = request.getParameter("space");
    boolean showThumbs = "true".equalsIgnoreCase(request.getParameter("showThumbs"));
    ServletContext servletContext = request.getSession().getServletContext();
    String contextPath = servletContext.getContextPath();
    String baseUrl = PathUtils.getBaseUrl(request, space, type);
    String baseDir = getBaseDir(request, baseUrl);

    if (log.isDebugEnabled()) {
        log.debug("OFM Parameters ================================");
        log.debug("mode = {}", mode);
        log.debug("baseDir = {}", baseDir);
        log.debug("baseUrl = {}", baseUrl);
        log.debug("type = {}", type);
        log.debug("space = {}", space);
        log.debug("showThumbs = {}", showThumbs);
        log.debug("==============================================");
    }
    String resp = null;
    if ("getinfo".equals(mode)) {
        resp = getInfo(request, contextPath, baseDir, baseUrl);
    } else if ("getfolder".equals(mode)) {
        resp = getFolder(request, contextPath, baseDir, baseUrl, showThumbs);
    } else if ("rename".equals(mode)) {
        resp = rename(request, baseDir, type);
    } else if ("delete".equals(mode)) {
        resp = delete(request, baseDir);
    } else if ("add".equals(mode)) {
        resp = add((MultipartServletRequest) request, baseDir, type);
        return new StreamingResult("text/html", resp);
    } else if ("addfolder".equals(mode)) {
        resp = addFolder(request, baseDir);
    } else if ("download".equals(mode)) {
        resp = download(request, response, baseDir);
    }
    if (log.isDebugEnabled()) {
        log.debug("End fileManager()");
        log.debug("QueryString={}", request.getQueryString());
        log.debug("ResponseString={}", resp);
    }
    if (resp != null) {
        return new StreamingResult("application/json", resp);
    } else {
        return new StreamingResult("application/json", "");
    }
}

From source file:org.dspace.rest.RestIndex.java

/**
 * Return html page with information about REST api. It contains methods all
 * methods provide by REST api.//from ww  w .j  ava2  s.  c o m
 *
 * @param servletContext
 *     Context of the servlet container.
 * @return HTML page which has information about all methods of REST API.
 */
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello(@Context ServletContext servletContext) {
    // TODO Better graphics, add arguments to all methods. (limit, offset, item and so on)
    return "<html><title>DSpace REST - index</title>" + "<body>" + "<h1>DSpace REST API</h1>" + "Server path: "
            + servletContext.getContextPath() + "<h2>Index</h2>" + "<ul>" + "<li>GET / - Return this page.</li>"
            + "<li>GET /test - Return the string \"REST api is running\" for testing purposes.</li>"
            + "<li>POST /login - Method for logging into the DSpace RESTful API. You must post the parameters \"email\" and \"password\". Example: \"email=test@dspace&password=pass\". Returns a JSESSIONID cookie which can be used for future authenticated requests.</li>"
            + "<li>POST /logout - Method for logging out of the DSpace RESTful API. The request must include the \"rest-dspace-token\" token</li> header."
            + "</ul>" + "<h2>Communities</h2>" + "<ul>"
            + "<li>GET /communities - Return an array of all communities in DSpace.</li>"
            + "<li>GET /communities/top-communities - Returns an array of all top-leve communities in DSpace.</li>"
            + "<li>GET /communities/{communityId} - Returns a community with the specified ID.</li>"
            + "<li>GET /communities/{communityId}/collections - Returns an array of collections of the specified community.</li>"
            + "<li>GET /communities/{communityId}/communities - Returns an array of subcommunities of the specified community.</li>"
            + "<li>POST /communities - Create a new top-level community. You must post a community.</li>"
            + "<li>POST /communities/{communityId}/collections - Create a new collection in the specified community. You must post a collection.</li>"
            + "<li>POST /communities/{communityId}/communities - Create a new subcommunity in the specified community. You must post a community.</li>"
            + "<li>PUT /communities/{communityId} - Update the specified community.</li>"
            + "<li>DELETE /communities/{communityId} - Delete the specified community.</li>"
            + "<li>DELETE /communities/{communityId}/collections/{collectionId} - Delete the specified collection in the specified community.</li>"
            + "<li>DELETE /communities/{communityId}/communities/{communityId2} - Delete the specified subcommunity (communityId2) in the specified community (communityId).</li>"
            + "</ul>" + "<h2>Collections</h2>" + "<ul>"
            + "<li>GET /collections - Return all DSpace collections in array.</li>"
            + "<li>GET /collections/{collectionId} - Return a collection with the specified ID.</li>"
            + "<li>GET /collections/{collectionId}/items - Return all items of the specified collection.</li>"
            + "<li>POST /collections/{collectionId}/items - Create an item in the specified collection. You must post an item.</li>"
            + "<li>POST /collections/find-collection - Find a collection by name.</li>"
            + "<li>PUT /collections/{collectionId} </li> - Update the specified collection. You must post a collection."
            + "<li>DELETE /collections/{collectionId} - Delete the specified collection from DSpace.</li>"
            + "<li>DELETE /collections/{collectionId}/items/{itemId} - Delete the specified item (itemId) in the specified collection (collectionId). </li>"
            + "</ul>" + "<h2>Items</h2>" + "<ul>" + "<li>GET /items - Return a list of items.</li>"
            + "<li>GET /items/{item id} - Return the specified item.</li>"
            + "<li>GET /items/{item id}/metadata - Return metadata of the specified item.</li>"
            + "<li>GET /items/{item id}/bitstreams - Return bitstreams of the specified item.</li>"
            + "<li>POST /items/find-by-metadata-field - Find items by the specified metadata value.</li>"
            + "<li>POST /items/{item id}/metadata - Add metadata to the specified item.</li>"
            + "<li>POST /items/{item id}/bitstreams - Add a bitstream to the specified item.</li>"
            + "<li>PUT /items/{item id}/metadata - Update metadata in the specified item.</li>"
            + "<li>DELETE /items/{item id} - Delete the specified item.</li>"
            + "<li>DELETE /items/{item id}/metadata - Clear metadata of the specified item.</li>"
            + "<li>DELETE /items/{item id}/bitstreams/{bitstream id} - Delete the specified bitstream of the specified item.</li>"
            + "</ul>" + "<h2>Bitstreams</h2>" + "<ul>"
            + "<li>GET /bitstreams - Return all bitstreams in DSpace.</li>"
            + "<li>GET /bitstreams/{bitstream id} - Return the specified bitstream.</li>"
            + "<li>GET /bitstreams/{bitstream id}/policy - Return policies of the specified bitstream.</li>"
            + "<li>GET /bitstreams/{bitstream id}/retrieve - Return the contents of the specified bitstream.</li>"
            + "<li>POST /bitstreams/{bitstream id}/policy - Add a policy to the specified bitstream.</li>"
            + "<li>PUT /bitstreams/{bitstream id}/data - Update the contents of the specified bitstream.</li>"
            + "<li>PUT /bitstreams/{bitstream id} - Update metadata of the specified bitstream.</li>"
            + "<li>DELETE /bitstreams/{bitstream id} - Delete the specified bitstream from DSpace.</li>"
            + "<li>DELETE /bitstreams/{bitstream id}/policy/{policy_id} - Delete the specified bitstream policy.</li>"
            + "</ul>" + "<h2>Hierarchy</h2>" + "<ul>"
            + "<li>GET /hierarchy - Return hierarchy of communities and collections in tree form. Each object is minimally populated (name, handle, id) for efficient retrieval.</li>"
            + "</ul>" + "<h2>Metadata and Schema Registry</h2>" + "<ul>"
            + "<li>GET /registries/schema - Return the list of metadata schemas in the registry</li>"
            + "<li>GET /registries/schema/{schema_prefix} - Returns the specified metadata schema</li>"
            + "<li>GET /registries/schema/{schema_prefix}/metadata-fields/{element} - Returns the metadata field within a schema with an unqualified element name</li>"
            + "<li>GET /registries/schema/{schema_prefix}/metadata-fields/{element}/{qualifier} - Returns the metadata field within a schema with a qualified element name</li>"
            + "<li>POST /registries/schema/ - Add a schema to the schema registry</li>"
            + "<li>POST /registries/schema/{schema_prefix}/metadata-fields - Add a metadata field to the specified schema</li>"
            + "<li>GET /registries/metadata-fields/{field_id} - Return the specified metadata field</li>"
            + "<li>PUT /registries/metadata-fields/{field_id} - Update the specified metadata field</li>"
            + "<li>DELETE /registries/metadata-fields/{field_id} - Delete the specified metadata field from the metadata field registry</li>"
            + "<li>DELETE /registries/schema/{schema_id} - Delete the specified schema from the schema registry</li>"
            + "</ul>" + "<h2>Query/Reporting Tools</h2>" + "<ul>"
            + "<li>GET /reports - Return a list of report tools built on the rest api</li>"
            + "<li>GET /reports/{nickname} - Return a redirect to a specific report</li>"
            + "<li>GET /filters - Return a list of use case filters available for quality control reporting</li>"
            + "<li>GET /filtered-collections - Return collections and item counts based on pre-defined filters</li>"
            + "<li>GET /filtered-collections/{collection_id} - Return items and item counts for a collection based on pre-defined filters</li>"
            + "<li>GET /filtered-items - Retrieve a set of items based on a metadata query and a set of filters</li>"
            + "</ul>" + "</body></html> ";
}

From source file:alfio.config.Initializer.java

private void configureSessionCookie(ServletContext servletContext) {
    SessionCookieConfig config = servletContext.getSessionCookieConfig();

    config.setHttpOnly(true);/*from   w  w  w. ja v a 2 s .c  o  m*/

    Validate.notNull(environment, "environment cannot be null!");
    // set secure cookie only if current environment doesn't strictly need HTTP
    config.setSecure(!environment.acceptsProfiles(PROFILE_HTTP));
    //

    // FIXME and CHECKME what a mess, ouch: https://issues.jboss.org/browse/WFLY-3448 ?
    config.setPath(servletContext.getContextPath() + "/");
    //
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

protected void registerFrontAppServlet(ServletContext servletContext) {
    boolean hasFrontApp = false;
    try {//from www . j a v  a  2 s.  c  o  m
        hasFrontApp = servletContext.getResource("/" + FRONT_CONTEXT_NAME) != null;
    } catch (MalformedURLException e) {
        //Do nothing
    }
    if (hasFrontApp) {
        String contextPath = servletContext.getContextPath();
        String baseUrl = System.getProperty("cuba.front.baseUrl");
        if (baseUrl == null || baseUrl.length() == 0) {
            String path = "/" + FRONT_CONTEXT_NAME + "/";
            System.setProperty("cuba.front.baseUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        String apiUrl = System.getProperty("cuba.front.apiUrl");
        if (apiUrl == null || apiUrl.length() == 0) {
            String path = "/rest/";
            System.setProperty("cuba.front.apiUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        DispatcherServlet frontServlet;
        try {
            Class frontServletClass = ReflectionHelper.getClass("com.haulmont.cuba.web.sys.AppFrontServlet");
            frontServlet = (DispatcherServlet) ReflectionHelper.newInstance(frontServletClass,
                    FRONT_CONTEXT_NAME, (Supplier<ApplicationContext>) AppContext::getApplicationContext);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Unable to instantiate app front servlet", e);
        }
        ServletRegistration.Dynamic cubaServletReg = servletContext.addServlet("app_front_servlet",
                frontServlet);
        cubaServletReg.setLoadOnStartup(3);
        cubaServletReg.setAsyncSupported(true);
        cubaServletReg.addMapping(String.format("/%s/*", FRONT_CONTEXT_NAME));
    }
}

From source file:org.jaggeryjs.jaggery.app.mgt.TomcatJaggeryWebappsDeployer.java

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {/*from  ww w .j a  v a2  s  .co  m*/
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantId(), parts[0],
                        parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {
                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                            throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

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

@POST
@Path("/preview/lang/{language}")
public Response getFormPreview(FormPreviewDTO dto, @PathParam("language") String language,
        @Context ServletContext context, @Context HttpServletRequest request) {
    setContext(context);//  w  ww .j av a 2 s. c  o m
    try {
        URL url = createTemplate(language, dto);
        Map<String, Object> inputs = dto.getInputsAsMap();
        Renderer renderer = getRenderer(language);
        inputs.put(Renderer.BASE_CONTEXT_PATH, context.getContextPath());
        Locale locale = request.getLocale();
        inputs.put(Renderer.BASE_LOCALE, locale == null ? "default" : locale.getDisplayName(locale));
        Object html = renderer.render(url, inputs);
        String htmlUrl = createHtmlTemplate(html, language, context);
        return Response.ok(htmlUrl, MediaType.TEXT_PLAIN).build();
    } catch (FormEncodingException e) {
        return error("Problem encoding form preview", e);
    } catch (TranslatorException e) {
        return error("Problem transforming form preview to " + language + " language", e);
    } catch (RendererException e) {
        return error("Problem rendering form preview in " + language + " language", e);
    } catch (IOException e) {
        return error("Problem writing form preview in " + language + " language", e);
    }
}

From source file:no.kantega.publishing.common.ContentIdHelperImpl.java

@Override
public void setServletContext(ServletContext servletContext) {
    CONTENT_URL_PATTERN = Pattern.compile(
            ContentPatterns.getPatternWithContextPath(servletContext.getContextPath()),
            Pattern.UNICODE_CHARACTER_CLASS);
}

From source file:org.jasig.resourceserver.utils.aggr.ResourcesElementsProviderImpl.java

/**
 * If the resource serving servlet context is available and the resource
 * is available in the context, create a URL to the resource in that context.
 * If not, create a local URL for the requested resource.
 *///  w  ww.  ja va 2s  .co m
protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
    final String resourceContextPath = this.getResourceServerContextPath();

    this.logger.debug("Attempting to locate resource serving webapp with context path: {}",
            resourceContextPath);

    //Try to resolve the 
    final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
    if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
        this.logger.warn(
                "Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application",
                resourceContextPath);
        return request.getContextPath();
    }

    this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);

    URL url = null;
    try {
        url = resourceContext.getResource(resource);
    } catch (MalformedURLException e) {
        //Ignore
    }

    if (url == null) {
        this.logger.debug(
                "Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.",
                resourceContextPath, resource);
        return request.getContextPath();
    }

    this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.",
            resourceContextPath, resource);
    return resourceContextPath;
}