Example usage for javax.servlet.http HttpServlet getServletContext

List of usage examples for javax.servlet.http HttpServlet getServletContext

Introduction

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

Prototype

public ServletContext getServletContext() 

Source Link

Document

Returns a reference to the ServletContext in which this servlet is running.

Usage

From source file:edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties.java

public static ConfigurationProperties getBean(HttpServlet servlet) {
    if (servlet == null) {
        throw new NullPointerException("servlet may not be null.");
    }//from w w w  . j  a  va 2s .c om
    return getBean(servlet.getServletContext());
}

From source file:com.arm.connector.bridge.core.Utils.java

public static String readHTMLFileIntoString(HttpServlet svc, ErrorLogger err, String filename) {
    try {//  w  w w  .  j  a va2s  . c o m
        String text = null;
        String file = "";
        ServletContext context = svc.getServletContext();
        try (InputStream is = context.getResourceAsStream("/" + filename);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader reader = new BufferedReader(isr)) {
            while ((text = reader.readLine()) != null) {
                file += text;
            }
        }
        return file;
    } catch (IOException ex) {
        err.critical("error while trying to read HTML template: " + filename, ex);
    }
    return null;
}

From source file:gov.nih.nci.ccts.grid.service.LabConsumerServiceImpl.java

/**
 * Will try to locate a pre-existent {@link ApplicationContext}; if failed,
 * will create it explicitly./*from   w  w  w. ja  v  a2 s .com*/
 * 
 * @see http://jira.semanticbits.com/browse/CAAERS-4291
 */
private synchronized void initialize() {
    if (this.consumer == null) {
        ApplicationContext ctx = null;
        String exp = ContainerConfig.getConfig().getOption(SPRING_CLASSPATH_EXPRESSION,
                DEFAULT_SPRING_CLASSPATH_EXPRESSION);
        String bean = ContainerConfig.getConfig().getOption(LAB_CONSUMER_BEAN_NAME,
                DEFAULT_LAB_CONSUMER_BEAN_NAME);

        // see http://jira.semanticbits.com/browse/CAAERS-4291
        // let's see if ApplicationContext is already available as a
        // WebApplicationContext
        // if so, use it; otherwise, fall back to standard approach for
        // backward compatibility.
        SOAPMessageContext messageContext = MessageContext.getCurrentContext();
        if (messageContext != null) {
            HttpServlet srv = (HttpServlet) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLET);
            if (srv != null) {
                ServletContext servletContext = srv.getServletContext();
                ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
            }
        }

        if (ctx == null) {
            System.out.println(
                    "LabConsumerServiceImpl: unable to find pre-existing spring context in servlet context; falling back to direct context creation.");
            System.out.println("LabConsumerServiceImpl: Creating spring context explicitly...");
            ctx = new ClassPathXmlApplicationContext(exp);

        }

        if (ctx != null)
            this.consumer = (LabConsumerServiceI) ctx.getBean(bean);

    }
}

From source file:de.micromata.genome.gwiki.page.GWikiStandaloneContext.java

public GWikiStandaloneContext(GWikiWeb wikiWeb, HttpServlet servlet, String contextPath, String servletPath) {
    super(wikiWeb, servlet, new StandaloneHttpServletRequest(getContextPath(wikiWeb, contextPath),
            getServletPath(wikiWeb, servletPath)), new StandaloneHttpServletResponse());
    ServletContext servletContext = null;
    if (servlet != null) {
        servletContext = servlet.getServletContext();
    }/*from  w  ww.  ja v  a  2 s.  c  om*/
    standAlonepageContext = new StandAlonePageContext(jspWriter, servletContext, getRequest(), getResponse());
    setPageContext(standAlonepageContext);
    standaloneRequest = (StandaloneHttpServletRequest) getRequest();
    standaloneResponse = (StandaloneHttpServletResponse) getResponse();
}

From source file:org.onebusaway.webapp.impl.WebappServiceServletImpl.java

/**
 * Used by HybridServiceServlet./*from  ww w .  j a v a2 s  . c o m*/
 */
private static SerializationPolicy customLoadSerializationPolicy(HttpServlet servlet,
        HttpServletRequest request, String moduleBaseURL, String strongName) {

    // The request can tell you the path of the web app relative to the
    // container root.
    String contextPath = request.getContextPath();

    String modulePath = null;
    if (moduleBaseURL != null) {
        try {
            modulePath = new URL(moduleBaseURL).getPath();
        } catch (MalformedURLException ex) {
            // log the information, we will default
            servlet.log("Malformed moduleBaseURL: " + moduleBaseURL, ex);
        }
    }

    SerializationPolicy serializationPolicy = null;

    /*
     * Check that the module path must be in the same web app as the servlet
     * itself. If you need to implement a scheme different than this, override
     * this method.
     */
    if (modulePath == null) {
        String message = "ERROR: The module path requested, " + modulePath
                + ", is not in the same web application as this servlet, " + contextPath
                + ".  Your module may not be properly configured or your client and server code maybe out of date.";
        servlet.log(message, null);
    } else {

        // TODO : Hack for Nokia demo
        // /Users/bdferris/Documents/Aptana%20Studio%20Workspace/nokia-hello-world/
        if (modulePath.endsWith("nokia-hello-world/"))
            modulePath = "/where/mobile/";

        if (!modulePath.startsWith(contextPath))
            modulePath = contextPath + modulePath;

        // Strip off the context path from the module base URL. It should be a
        // strict prefix.
        String contextRelativePath = modulePath.substring(contextPath.length());

        String serializationPolicyFilePath = SerializationPolicyLoader
                .getSerializationPolicyFileName(contextRelativePath + strongName);

        // Open the RPC resource file and read its contents.
        InputStream is = servlet.getServletContext().getResourceAsStream(serializationPolicyFilePath);
        try {
            if (is != null) {
                try {
                    serializationPolicy = SerializationPolicyLoader.loadFromStream(is, null);
                } catch (ParseException e) {
                    servlet.log("ERROR: Failed to parse the policy file '" + serializationPolicyFilePath + "'",
                            e);
                } catch (IOException e) {
                    servlet.log("ERROR: Could not read the policy file '" + serializationPolicyFilePath + "'",
                            e);
                }
            } else {
                String message = "ERROR: The serialization policy file '" + serializationPolicyFilePath
                        + "' was not found; did you forget to include it in this deployment?";
                servlet.log(message, null);
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // Ignore this error
                }
            }
        }
    }

    return serializationPolicy;
}

From source file:net.jawr.web.bundle.processor.BundleProcessor.java

/**
 * Creates the bundles in the destination directory
 * // ww w .j  a v  a  2s  .  c  om
 * @param servlet
 *            the servlet
 * @param bundleHandler
 *            the bundles handler
 * @param destDirPath
 *            the destination directory path
 * @param servletMapping
 *            the mapping of the servlet
 * @param keepUrlMapping
 *            the flag indicating if we must keep the URL mapping
 * @throws IOException
 *             if an IO exception occurs
 * @throws ServletException
 *             if a servlet exception occurs
 */
protected void createBundles(HttpServlet servlet, ResourceBundlesHandler bundleHandler, String destDirPath,
        String servletMapping, boolean keepUrlMapping) throws IOException, ServletException {

    List<JoinableResourceBundle> bundles = bundleHandler.getContextBundles();

    Iterator<JoinableResourceBundle> bundleIterator = bundles.iterator();
    MockServletResponse response = new MockServletResponse();
    MockServletRequest request = new MockServletRequest(JAWR_BUNDLE_PROCESSOR_CONTEXT_PATH);
    MockServletSession session = new MockServletSession(servlet.getServletContext());
    request.setSession(session);

    String resourceType = servlet.getServletConfig().getInitParameter(TYPE_INIT_PARAMETER);
    if (resourceType == null) {
        resourceType = JawrConstant.JS_TYPE;
    }

    // For the list of bundle defines, create the file associated
    while (bundleIterator.hasNext()) {
        JoinableResourceBundle bundle = (JoinableResourceBundle) bundleIterator.next();

        // Check if there is a resource file, which could be in conflict
        // with the bundle name
        URL url = servlet.getServletContext().getResource(bundle.getId());
        if (url != null) {
            logger.error(
                    "It is not recommended to use a bundle name which could be in conflict with a resource.\n"
                            + "Please rename your bundle '" + bundle.getId() + "' to avoid any issue");

        }

        List<Map<String, String>> allVariants = VariantUtils.getAllVariants(bundle.getVariants());

        if (allVariants == null) {
            allVariants = new ArrayList<Map<String, String>>();
        }

        if (allVariants.isEmpty()) {
            allVariants.add(new HashMap<String, String>());
        }
        // Creates the bundle file for each local variant
        for (Iterator<Map<String, String>> it = allVariants.iterator(); it.hasNext();) {
            Map<String, String> variantMap = (Map<String, String>) it.next();

            List<RenderedLink> linksToBundle = createLinkToBundle(bundleHandler, bundle.getId(), resourceType,
                    variantMap);
            for (Iterator<RenderedLink> iteratorLinks = linksToBundle.iterator(); iteratorLinks.hasNext();) {
                RenderedLink renderedLink = iteratorLinks.next();
                String path = renderedLink.getLink();

                // Force the debug mode of the config to match what was used
                // in the generated link
                JawrConfig config = bundleHandler.getConfig();
                config.setDebugModeOn(renderedLink.isDebugMode());

                String finalBundlePath = null;
                if (keepUrlMapping) {
                    finalBundlePath = path;
                } else {
                    finalBundlePath = getFinalBundlePath(path, config, variantMap);
                }

                // Sets the request URL
                setRequestUrl(request, variantMap, path, config);

                // We can't use path for generated resources because it's
                // not a valid file path ( /jawr_generator.js?xxx.... )
                if (!(path.indexOf("?") != -1) || !keepUrlMapping) {
                    File bundleFile = new File(destDirPath, finalBundlePath);
                    createBundleFile(servlet, response, request, path, bundleFile, servletMapping);
                }
            }
        }
    }
}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

@Override
public void serviceFile(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp)
        throws ServletException, IOException {
    req = new HTTPServletRequestWrap(req);
    CFMLFactory factory = getCFMLFactory(servlet.getServletConfig(), req);
    ConfigWeb config = factory.getConfig();
    PageSource ps = config.getPageSourceExisting(null, null, req.getServletPath(), false, true, true, false);
    //Resource res = ((ConfigWebImpl)config).getPhysicalResourceExistingX(null, null, req.getServletPath(), false, true, true); 

    if (ps == null) {
        rsp.sendError(404);/*from  www.  j  av  a 2  s.co  m*/
    } else {
        Resource res = ps.getResource();
        if (res == null) {
            rsp.sendError(404);
        } else {
            ReqRspUtil.setContentLength(rsp, res.length());
            String mt = servlet.getServletContext().getMimeType(req.getServletPath());
            if (!StringUtil.isEmpty(mt))
                ReqRspUtil.setContentType(rsp, mt);
            IOUtil.copy(res, rsp.getOutputStream(), true);
        }
    }
}

From source file:org.apache.axis.transport.http.AxisServletBase.java

/**
 * This is a uniform method of initializing AxisServer in a servlet
 * context./*from w w w.  j  a  v a 2s .com*/
 * @todo add catch for not being able to cast the context attr to an
 * engine and reinit the engine if so.
 */
public static AxisServer getEngine(HttpServlet servlet) throws AxisFault {
    AxisServer engine = null;
    if (isDebug)
        log.debug("Enter: getEngine()");

    ServletContext context = servlet.getServletContext();
    synchronized (context) {
        engine = retrieveEngine(servlet);
        if (engine == null) {
            Map environment = getEngineEnvironment(servlet);

            // Obtain an AxisServer by using whatever AxisServerFactory is
            // registered.  The default one will just use the provider we
            // passed in, and presumably JNDI ones will use the ServletContext
            // to figure out a JNDI name to look up.
            //
            // The point of doing this rather than just creating the server
            // manually with the provider above is that we will then support
            // configurations where the server instance is managed by the
            // container, and pre-registered in JNDI at deployment time.  It
            // also means we put the standard configuration pattern in one
            // place.
            engine = AxisServer.getServer(environment);
            //              attach the AxisServer with the current Servlet
            engine.setName(servlet.getServletName());
            storeEngine(servlet, engine);
        }
    }

    if (isDebug)
        log.debug("Exit: getEngine()");

    return engine;
}

From source file:org.apache.axis.transport.http.AxisServletBase.java

/**
 * put the engine back in to the context.
 * @param context servlet context to use
 * @param engine reference to the engine. If null, the engine is removed
 *///from  w  w  w.  ja va  2  s.  c  o m
private static void storeEngine(HttpServlet servlet, AxisServer engine) {
    ServletContext context = servlet.getServletContext();
    String axisServletName = servlet.getServletName();
    if (engine == null) {
        context.removeAttribute(axisServletName + ATTR_AXIS_ENGINE);
        // find if there is other AxisEngine in Context
        AxisServer server = (AxisServer) context.getAttribute(ATTR_AXIS_ENGINE);

        // no other AxisEngine in ServletContext
        if (server != null && servlet.getServletName().equals(server.getName())) {
            context.removeAttribute(ATTR_AXIS_ENGINE);
        }
    } else {
        if (context.getAttribute(ATTR_AXIS_ENGINE) == null) {
            // first Axis servlet to store its AxisEngine
            // use default name
            context.setAttribute(ATTR_AXIS_ENGINE, engine);
        }
        context.setAttribute(axisServletName + ATTR_AXIS_ENGINE, engine);
    }
}

From source file:org.apache.axis.transport.http.AxisServletBase.java

/**
 * Get an engine from the servlet context; robust againt serialization
 * issues of hot-updated webapps. Remember than if a webapp is marked
 * as distributed, there is more than 1 servlet context, hence more than
 * one AxisEngine instance/* w ww  . ja va  2s.c  o m*/
 * @param servlet
 * @return the engine or null if either the engine couldnt be found or
 *         the attribute wasnt of the right type
 */
private static AxisServer retrieveEngine(HttpServlet servlet) {
    Object contextObject = servlet.getServletContext()
            .getAttribute(servlet.getServletName() + ATTR_AXIS_ENGINE);
    if (contextObject == null) {
        // if AxisServer not found :
        // fall back to the "default" AxisEngine
        contextObject = servlet.getServletContext().getAttribute(ATTR_AXIS_ENGINE);
    }
    if (contextObject instanceof AxisServer) {
        AxisServer server = (AxisServer) contextObject;
        // if this is "our" Engine
        if (server != null && servlet.getServletName().equals(server.getName())) {
            return server;
        }
        return null;
    } else {
        return null;
    }
}