Java Code Examples for javax.servlet.ServletContext

The following are top voted examples for showing how to use javax.servlet.ServletContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ssm-demo   File: LoadImageController.java   Source Code and License 9 votes vote down vote up
/**
 *
 *
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping("/upload")
public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception {
    ServletContext sc = request.getSession().getServletContext();
    String dir = sc.getRealPath("/upload");
    String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    String imgName = "";
    if (type.equals("jpg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpg";
    } else if (type.equals("png")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".png";
    } else if (type.equals("jpeg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpeg";
    } else {
        return null;
    }
    FileUtils.writeByteArrayToFile(new File(dir, imgName), file.getBytes());
    response.getWriter().print("upload/" + imgName);
    return null;
}
 
Example 2
Project: Smart-Shopping   File: WebMvcInitialiser.java   Source Code and License 8 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
	//register config classes
	AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
	rootContext.register(WebMvcConfig.class);
	rootContext.register(JPAConfig.class);
	rootContext.register(WebSecurityConfig.class);
	rootContext.register(ServiceConfig.class);
	//set session timeout
	servletContext.addListener(new SessionListener(maxInactiveInterval));
	//set dispatcher servlet and mapping
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
			new DispatcherServlet(rootContext));
	dispatcher.addMapping("/");
	dispatcher.setLoadOnStartup(1);
	
	//register filters
	FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("endcodingFilter", new CharacterEncodingFilter());
	filterRegistration.setInitParameter("encoding", "UTF-8");
	filterRegistration.setInitParameter("forceEncoding", "true");
	//make sure encodingFilter is matched first
	filterRegistration.addMappingForUrlPatterns(null, false, "/*");
	//disable appending jsessionid to the URL
	filterRegistration = servletContext.addFilter("disableUrlSessionFilter", new DisableUrlSessionFilter());
	filterRegistration.addMappingForUrlPatterns(null, true, "/*");
}
 
Example 3
Project: incubator-sdap-mudrod   File: MudrodContextListener.java   Source Code and License 6 votes vote down vote up
/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent arg0) {
  me = new MudrodEngine();
  Properties props = me.loadConfig();
  me.setESDriver(new ESDriver(props));
  me.setSparkDriver(new SparkDriver(props));

  ServletContext ctx = arg0.getServletContext();
  Searcher searcher = new Searcher(props, me.getESDriver(), null);
  Ranker ranker = new Ranker(props, me.getESDriver(), me.getSparkDriver(), "SparkSVM");
  Ontology ontImpl = new OntologyFactory(props).getOntology();
  ctx.setAttribute("MudrodInstance", me);
  ctx.setAttribute("MudrodSearcher", searcher);
  ctx.setAttribute("MudrodRanker", ranker);
  ctx.setAttribute("Ontology", ontImpl);
}
 
Example 4
Project: ysoserial-modified   File: MyfacesTest.java   Source Code and License 6 votes vote down vote up
private static FacesContext createMockFacesContext () throws MalformedURLException {
    FacesContext ctx = Mockito.mock(FacesContext.class);
    CompositeELResolver cer = new CompositeELResolver();
    FacesELContext elc = new FacesELContext(cer, ctx);
    ServletRequest requestMock = Mockito.mock(ServletRequest.class);
    ServletContext contextMock = Mockito.mock(ServletContext.class);
    URL url = new URL("file:///");
    Mockito.when(contextMock.getResource(Matchers.anyString())).thenReturn(url);
    Mockito.when(requestMock.getServletContext()).thenReturn(contextMock);
    Answer<?> attrContext = new MockRequestContext();
    Mockito.when(requestMock.getAttribute(Matchers.anyString())).thenAnswer(attrContext);
    Mockito.doAnswer(attrContext).when(requestMock).setAttribute(Matchers.anyString(), Matchers.any());
    cer.add(new MockELResolver(requestMock));
    cer.add(new BeanELResolver());
    cer.add(new MapELResolver());
    Mockito.when(ctx.getELContext()).thenReturn(elc);
    return ctx;
}
 
Example 5
Project: uavstack   File: JettyPlusIT.java   Source Code and License 6 votes vote down vote up
/**
 * getBasePath
 * 
 * @param context
 * @param sContext
 */
private void getBasePath(InterceptContext context, ServletContext sContext) {

    String basePath = sContext.getRealPath("");

    if (basePath == null) {
        return;
    }

    if (basePath.lastIndexOf("/") == (basePath.length() - 1)
            || basePath.lastIndexOf("\\") == (basePath.length() - 1)) {
        basePath = basePath.substring(0, basePath.length() - 1);
    }

    context.put(InterceptConstants.BASEPATH, basePath);
}
 
Example 6
Project: lams   File: UrlController.java   Source Code and License 6 votes vote down vote up
/**
 * Method associated to a tile and called immediately before the tile 
 * is included.  This implementation calls an <code>Action</code>. 
 * No servlet is set by this method.
 *
 * @param tileContext Current tile context.
 * @param request Current request.
 * @param response Current response.
 * @param servletContext Current servlet context.
 */
public void perform(
	ComponentContext tileContext,
	HttpServletRequest request,
	HttpServletResponse response,
	ServletContext servletContext)
	throws ServletException, IOException {

	RequestDispatcher rd = servletContext.getRequestDispatcher(url);
	if (rd == null) {
		throw new ServletException(
			"Controller can't find url '" + url + "'.");
	}

	rd.include(request, response);
}
 
Example 7
Project: autopivot   File: AutoPivotWebAppInitializer.java   Source Code and License 6 votes vote down vote up
/**
 * Configure the given {@link ServletContext} with any servlets, filters, listeners
 * context-params and attributes necessary for initializing this web application. See examples
 * {@linkplain WebApplicationInitializer above}.
 *
 * @param servletContext the {@code ServletContext} to initialize
 * @throws ServletException if any call against the given {@code ServletContext} throws a {@code ServletException}
 */
public void onStartup(ServletContext servletContext) throws ServletException {
	// Spring Context Bootstrapping
	AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
	rootAppContext.register(AutoPivotConfig.class);
	servletContext.addListener(new ContextLoaderListener(rootAppContext));

	// Set the session cookie name. Must be done when there are several servers (AP,
	// Content server, ActiveMonitor) with the same URL but running on different ports.
	// Cookies ignore the port (See RFC 6265).
	CookieUtil.configure(servletContext.getSessionCookieConfig(), CookieUtil.COOKIE_NAME);

	// The main servlet/the central dispatcher
	final DispatcherServlet servlet = new DispatcherServlet(rootAppContext);
	servlet.setDispatchOptionsRequest(true);
	Dynamic dispatcher = servletContext.addServlet("springDispatcherServlet", servlet);
	dispatcher.addMapping("/*");
	dispatcher.setLoadOnStartup(1);

	// Spring Security Filter
	final FilterRegistration.Dynamic springSecurity = servletContext.addFilter(SPRING_SECURITY_FILTER_CHAIN, new DelegatingFilterProxy());
	springSecurity.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

}
 
Example 8
Project: alvisnlp   File: DRMAAExecutor.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(ServletContext servletContext, PlanBuilder planBuilder, Run run, boolean async) {
	SessionFactory sessionFactory = SessionFactory.getFactory();
	Session session = sessionFactory.getSession();
	try {
		session.init("");
		JobTemplate jobTemplate = createJobTemplate(servletContext, session, run);
		String jobId = enqueue(session, run, jobTemplate);
		if (async) {
			String status = waitForStatus(session, jobId);
			if (status != null) {
				run.addStatus(status, "", true);
			}
		}
		session.deleteJobTemplate(jobTemplate);
		session.exit();
	}
	catch (DrmaaException e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
Project: parabuild-ci   File: ServletConverter.java   Source Code and License 6 votes vote down vote up
public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx)
{
    WebContext webcx = WebContextFactory.get();

    if (HttpServletRequest.class.isAssignableFrom(paramType))
    {
        return webcx.getHttpServletRequest();
    }

    if (HttpServletResponse.class.isAssignableFrom(paramType))
    {
        return webcx.getHttpServletResponse();
    }

    if (ServletConfig.class.isAssignableFrom(paramType))
    {
        return webcx.getServletConfig();
    }

    if (ServletContext.class.isAssignableFrom(paramType))
    {
        return webcx.getServletContext();
    }

    if (HttpSession.class.isAssignableFrom(paramType))
    {
        return webcx.getSession(true);
    }

    return null;
}
 
Example 10
Project: scott-eu   File: WarehouseControllerManager.java   Source Code and License 6 votes vote down vote up
public static void contextInitializeServletListener(final ServletContextEvent servletContextEvent)
{
    
    // Start of user code contextInitializeServletListener
    final ServletContext context = servletContextEvent.getServletContext();
    final String queryUri = context.getInitParameter(
            "se.ericsson.cf.scott.sandbox.store.query");
    final String updateUri = context.getInitParameter(
            "se.ericsson.cf.scott.sandbox.store.update");
    try {
        store = StoreFactory.sparql(queryUri, updateUri);
        // TODO [email protected]: Remember to deactivate when switch to more persistent arch
        store.removeAll();
    } catch (IOException |ARQException e) {
        log.error("SPARQL Store failed to initialise with the URIs query={};update={}",
                queryUri, updateUri, e);
    }
    // End of user code
}
 
Example 11
Project: lams   File: I18nFactorySet.java   Source Code and License 6 votes vote down vote up
/**
 * Initialization method.
 * Init the factory by reading appropriate configuration file.
 * This method is called exactly once immediately after factory creation in
 * case of internal creation (by DefinitionUtil).
 * @param servletContext Servlet Context passed to newly created factory.
 * @param proposedFilename File names, comma separated, to use as  base file names.
 * @throws DefinitionsFactoryException An error occur during initialization.
 */
protected void initFactory(
    ServletContext servletContext,
    String proposedFilename)
    throws DefinitionsFactoryException, FileNotFoundException {

    // Init list of filenames
    StringTokenizer tokenizer = new StringTokenizer(proposedFilename, ",");
    this.filenames = new ArrayList(tokenizer.countTokens());
    while (tokenizer.hasMoreTokens()) {
        this.filenames.add(tokenizer.nextToken().trim());
    }

    loaded = new HashMap();
    defaultFactory = createDefaultFactory(servletContext);
    if (log.isDebugEnabled())
        log.debug("default factory:" + defaultFactory);
}
 
Example 12
Project: lams   File: JspServletWrapper.java   Source Code and License 6 votes vote down vote up
public JspServletWrapper(ServletContext servletContext,
		     Options options,
		     String tagFilePath,
		     TagInfo tagInfo,
		     JspRuntimeContext rctxt,
		     URL tagFileJarUrl)
    throws JasperException {

this.isTagFile = true;
       this.config = null;	// not used
       this.options = options;
this.jspUri = tagFilePath;
this.tripCount = 0;
       ctxt = new JspCompilationContext(jspUri, tagInfo, options,
				 servletContext, this, rctxt,
				 tagFileJarUrl);
   }
 
Example 13
Project: apache-tomcat-7.0.73-with-comment   File: JspServletWrapper.java   Source Code and License 6 votes vote down vote up
public JspServletWrapper(ServletContext servletContext,
                         Options options,
                         String tagFilePath,
                         TagInfo tagInfo,
                         JspRuntimeContext rctxt,
                         JarResource tagJarResource) {

    this.isTagFile = true;
    this.config = null;        // not used
    this.options = options;
    this.jspUri = tagFilePath;
    this.tripCount = 0;
    unloadByCount = options.getMaxLoadedJsps() > 0 ? true : false;
    unloadByIdle = options.getJspIdleTimeout() > 0 ? true : false;
    unloadAllowed = unloadByCount || unloadByIdle ? true : false;
    ctxt = new JspCompilationContext(jspUri, tagInfo, options,
                                     servletContext, this, rctxt,
                                     tagJarResource);
}
 
Example 14
Project: lazycat   File: JspContextWrapper.java   Source Code and License 5 votes vote down vote up
@Override
public ServletContext getServletContext() {
	if (servletContext == null) {
		servletContext = rootJspCtxt.getServletContext();
	}
	return servletContext;
}
 
Example 15
Project: javaee-design-patterns   File: OpenApiUpdater.java   Source Code and License 5 votes vote down vote up
@Override
public void afterScan(Reader reader, OpenAPI openAPI) {
    openAPI.info(
            new Info()
                    .title("Simple Project Api")
                    .version(getClass().getPackage().getImplementationVersion())
    );
    openAPI.servers(Collections.singletonList(new Server().description("Current Server").url(CDI.current().select(ServletContext.class).get().getContextPath())));
    //error
    Schema errorObject = ModelConverters.getInstance().readAllAsResolvedSchema(ErrorValueObject.class).schema;
    openAPI.getComponents().addSchemas("Error", errorObject);
    openAPI.getPaths()
            .values()
            .stream()
            .flatMap(pathItem -> pathItem.readOperations().stream())
            .forEach(operation -> {
                ApiResponses responses = operation.getResponses();
                responses
                        .addApiResponse(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()),
                                new ApiResponse().description("Unexpected exception. Error code = 1")
                                        .content(
                                                new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
                                                        .schema(errorObject))));
                if (operation.getParameters() != null && !operation.getParameters().isEmpty()) {
                    responses
                            .addApiResponse(String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()),
                                    new ApiResponse().description("Bad request. Error code = 2")
                                            .content(
                                                    new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
                                                            .schema(errorObject))));
                }
            });
}
 
Example 16
Project: hevelian-activemq   File: WebBrokerInitializerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void contextInitialized() throws Exception {
	ServletContext sc = mock(ServletContext.class);

	BrokerService broker = mock(BrokerService.class);
	doReturn(true).when(broker).waitUntilStarted();

	WebBrokerInitializer i = spy(WebBrokerInitializer.class);
	doReturn(broker).when(i).createBroker(sc);

	i.contextInitialized(new ServletContextEvent(sc));
}
 
Example 17
Project: parabuild-ci   File: DwrGuiceUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the servlet context from the current web context, if one exists,
 * otherwise gets it from the thread-local stash.
 */
static ServletContext getServletContext()
{
    WebContext webcx = WebContextFactory.get();
    if (webcx != null)
    {
        return webcx.getServletContext();
    }
    else
    {
        return servletContexts.get().getFirst();
    }
}
 
Example 18
Project: auto-questions-service   File: TextInfoRetriever.java   Source Code and License 5 votes vote down vote up
public TextInfoRetriever(String text, String filterType, ServletContext servletContext) {
    DBPediaSpotlightClient dbPediaSpotlightClient = new DBPediaSpotlightClient();
    dbPediaSpotlightClient.init(servletContext);
    DBPediaSpotlightResult response;
    response = dbPediaSpotlightClient.annotatePost(text, filterType);
    dbPediaResources = response.getDBPediaResources();
}
 
Example 19
Project: lazycat   File: WebappLoader.java   Source Code and License 5 votes vote down vote up
private boolean buildClassPath(ServletContext servletContext, StringBuilder classpath, ClassLoader loader) {
	if (loader instanceof URLClassLoader) {
		URL repositories[] = ((URLClassLoader) loader).getURLs();
		for (int i = 0; i < repositories.length; i++) {
			String repository = repositories[i].toString();
			if (repository.startsWith("file://"))
				repository = utf8Decode(repository.substring(7));
			else if (repository.startsWith("file:"))
				repository = utf8Decode(repository.substring(5));
			else if (repository.startsWith("jndi:"))
				repository = servletContext.getRealPath(repository.substring(5));
			else
				continue;
			if (repository == null)
				continue;
			if (classpath.length() > 0)
				classpath.append(File.pathSeparator);
			classpath.append(repository);
		}
	} else {
		String cp = getClasspath(loader);
		if (cp == null) {
			log.info("Unknown loader " + loader + " " + loader.getClass());
		} else {
			if (classpath.length() > 0)
				classpath.append(File.pathSeparator);
			classpath.append(cp);
		}
		return false;
	}
	return true;
}
 
Example 20
Project: Hi-Framework   File: I18nStarter.java   Source Code and License 5 votes vote down vote up
public static I18nStarter createInstance(ServletContext servletContext,
                                         I18nConfiguration configuration){

    Set<URL> libraries = BootstrapUtils.getLibraries(servletContext);
    return  new I18nStarter(configuration,
            libraries,servletContext);

}
 
Example 21
Project: alfresco-remote-api   File: KerberosAuthenticationFilter.java   Source Code and License 5 votes vote down vote up
/**
     * Writes link to login page and refresh tag which cause user
     * to be redirected to the login page.
     *
     * @param context ServletContext
     * @param req HttpServletRequest
     * @param resp HttpServletResponse
     * @throws IOException
     */
    protected void writeLoginPageLink(ServletContext context, HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        resp.setContentType(MIME_HTML_TEXT);

        final PrintWriter out = resp.getWriter();
        out.println("<html><head>");
        // Remove the auto refresh to avoid refresh loop, MNT-16931
//        out.println("<meta http-equiv=\"Refresh\" content=\"0; url=" + req.getContextPath() + "/webdav\">");
        out.println("</head><body><p>Please <a href=\"" + req.getContextPath() + getLoginPageLink() +"\">log in</a>.</p>");
        out.println("</body></html>");
        out.close();
    }
 
Example 22
Project: diax-dialect   File: ChatbotAPI.java   Source Code and License 5 votes vote down vote up
@Path("/train")
@Consumes(MediaType.APPLICATION_JSON)
@POST
public void train(String JSONRequest, @Context ServletContext context) {
	JSONObject trainObject = new JSONObject(JSONRequest);
	Chatbot.createDependenciesAndIncrement(trainObject.getString("input"), trainObject.getString("output"), context);
}
 
Example 23
Project: lazycat   File: WsContextListener.java   Source Code and License 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
	ServletContext sc = sce.getServletContext();
	// Don't trigger WebSocket initialization if a WebSocket Server
	// Container is already present
	if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) {
		WsSci.init(sce.getServletContext(), false);
	}
}
 
Example 24
Project: hevelian-activemq   File: WebBrokerInitializerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void contextDestroyed() throws Exception {
	ServletContext sc = mock(ServletContext.class);

	BrokerService broker = mock(BrokerService.class);
	doReturn(true).when(broker).isStarted();
	doReturn(true).when(broker).waitUntilStarted();

	WebBrokerInitializer i = spy(WebBrokerInitializer.class);
	doReturn(broker).when(i).createBroker(sc);

	i.contextInitialized(new ServletContextEvent(sc));
	i.contextDestroyed(new ServletContextEvent(sc));
}
 
Example 25
Project: lams   File: WebUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Remove the system property that points to the web app root directory.
 * To be called on shutdown of the web application.
 * @param servletContext the servlet context of the web application
 * @see #setWebAppRootSystemProperty
 */
public static void removeWebAppRootSystemProperty(ServletContext servletContext) {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	System.getProperties().remove(key);
}
 
Example 26
Project: myfaces-trinidad   File: StateUtils.java   Source Code and License 5 votes vote down vote up
private static String findAlgorithm(ServletContext ctx)
{

    String algorithm = ctx.getInitParameter(INIT_ALGORITHM);
    
    if (algorithm == null)
    {
        algorithm = ctx.getInitParameter(INIT_ALGORITHM.toLowerCase());
    }

    return findAlgorithm( algorithm );
}
 
Example 27
Project: EasyController   File: VelocityView.java   Source Code and License 5 votes vote down vote up
static void init(ServletContext servletContext) {
    String webPath = servletContext.getRealPath("/");
    properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, webPath);

    String encoding = Constants.me().getEncoding();
    properties.setProperty(Velocity.INPUT_ENCODING, encoding);
    properties.setProperty(Velocity.OUTPUT_ENCODING, encoding);

    Velocity.init(properties);
}
 
Example 28
Project: wildfly_exporter   File: MetricFilterExtension.java   Source Code and License 5 votes vote down vote up
@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {

    if (!contextBlacklist.contains(deploymentInfo.getContextPath())) {
        LOG.info("Adding metrics filter to  deployment for context " + deploymentInfo.getContextPath());
        FilterInfo metricsFilterInfo = new FilterInfo("metricsfilter", ServletMetricsFilter.class);
        metricsFilterInfo.setAsyncSupported(true);
        metricsFilterInfo.addInitParam(ServletMetricsFilter.BUCKET_CONFIG_PARAM,System.getProperty("prometheus.wildfly.filter.buckets",""));
        deploymentInfo.addFilter(metricsFilterInfo);
        deploymentInfo.addFilterUrlMapping("metricsfilter", "/*", DispatcherType.REQUEST);
    } else {
        LOG.info("Metrics filter not added to black listed context " + deploymentInfo.getContextPath());
        LOG.info(contextBlacklist.toString());
    }
}
 
Example 29
Project: scott-eu   File: ServletListener.java   Source Code and License 5 votes vote down vote up
private static String getInitParameterOrDefault(ServletContext context, String propertyName, String defaultValue) {
    String base = context.getInitParameter(propertyName);
    if (base == null || base.trim().isEmpty()) {
        base = defaultValue;
    }
    return base;
}
 
Example 30
Project: uavstack   File: JettyPlusIT.java   Source Code and License 5 votes vote down vote up
/**
 * onAppStart
 * 
 * @param args
 */
public void onAppStart(Object... args) {

    WebAppContext sc = getWebAppContext(args);

    if (sc == null) {
        return;
    }

    InterceptSupport iSupport = InterceptSupport.instance();
    InterceptContext context = iSupport.createInterceptContext(Event.WEBCONTAINER_STARTED);
    context.put(InterceptConstants.WEBAPPLOADER, sc.getClassLoader());
    context.put(InterceptConstants.WEBWORKDIR, sc.getServletContext().getRealPath(""));
    context.put(InterceptConstants.CONTEXTPATH, sc.getContextPath());
    context.put(InterceptConstants.APPNAME, sc.getDisplayName());

    ServletContext sContext = sc.getServletContext();

    context.put(InterceptConstants.SERVLET_CONTEXT, sContext);

    getBasePath(context, sContext);

    iSupport.doIntercept(context);

    // GlobalFilter
    sc.addFilter("com.creditease.monitor.jee.filters.GlobalFilter", "/*", EnumSet.of(DispatcherType.REQUEST));
}
 
Example 31
Project: Spring-5.0-Cookbook   File: SpringWebInitializer.java   Source Code and License 5 votes vote down vote up
private void addRootContext(ServletContext container) {
  // Create the application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.register(SpringContextConfig.class); 
	 
  // Register application context with ContextLoaderListener
  container.addListener(new ContextLoaderListener(rootContext));
  container.addListener(new AppSessionListener());
  container.setInitParameter("contextConfigLocation", "org.packt.secured.mvc.core");
  container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); // if URL, enable sessionManagement URL rewriting   
}
 
Example 32
Project: lams   File: ModuleUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Select the module to which the specified request belongs, and
 * add corresponding request attributes to this request.
 *
 * @param request The servlet request we are processing
 * @param context The ServletContext for this web application
 */
public void selectModule(HttpServletRequest request, ServletContext context) {
    // Compute module name
    String prefix = getModuleName(request, context);

    // Expose the resources for this module
    this.selectModule(prefix, request, context);

}
 
Example 33
Project: hadoop-oss   File: HttpServer2.java   Source Code and License 5 votes vote down vote up
/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException
 */
public static boolean hasAdministratorAccess(
    ServletContext servletContext, HttpServletRequest request,
    HttpServletResponse response) throws IOException {
  Configuration conf =
      (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
  // If there is no authorization, anybody has administrator access.
  if (!conf.getBoolean(
      CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
    return true;
  }

  String remoteUser = request.getRemoteUser();
  if (remoteUser == null) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN,
                       "Unauthenticated users are not " +
                       "authorized to access this page.");
    return false;
  }

  if (servletContext.getAttribute(ADMINS_ACL) != null &&
      !userHasAdministratorAccess(servletContext, remoteUser)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User "
        + remoteUser + " is unauthorized to access this page.");
    return false;
  }

  return true;
}
 
Example 34
Project: lams   File: SpringServletContainerInitializer.java   Source Code and License 5 votes vote down vote up
/**
 * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
 * implementations present on the application classpath.
 *
 * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
 * Servlet 3.0+ containers will automatically scan the classpath for implementations
 * of Spring's {@code WebApplicationInitializer} interface and provide the set of all
 * such types to the {@code webAppInitializerClasses} parameter of this method.
 *
 * <p>If no {@code WebApplicationInitializer} implementations are found on the
 * classpath, this method is effectively a no-op. An INFO-level log message will be
 * issued notifying the user that the {@code ServletContainerInitializer} has indeed
 * been invoked but that no {@code WebApplicationInitializer} implementations were
 * found.
 *
 * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
 * they will be instantiated (and <em>sorted</em> if the @{@link
 * org.springframework.core.annotation.Order @Order} annotation is present or
 * the {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
 * method will be invoked on each instance, delegating the {@code ServletContext} such
 * that each instance may register and configure servlets such as Spring's
 * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
 * or any other Servlet API componentry such as filters.
 *
 * @param webAppInitializerClasses all implementations of
 * {@link WebApplicationInitializer} found on the application classpath
 * @param servletContext the servlet context to be initialized
 * @see WebApplicationInitializer#onStartup(ServletContext)
 * @see AnnotationAwareOrderComparator
 */
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
		throws ServletException {

	List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

	if (webAppInitializerClasses != null) {
		for (Class<?> waiClass : webAppInitializerClasses) {
			// Be defensive: Some servlet containers provide us with invalid classes,
			// no matter what @HandlesTypes says...
			if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
					WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
				try {
					initializers.add((WebApplicationInitializer) waiClass.newInstance());
				}
				catch (Throwable ex) {
					throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
				}
			}
		}
	}

	if (initializers.isEmpty()) {
		servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
		return;
	}

	AnnotationAwareOrderComparator.sort(initializers);
	servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);

	for (WebApplicationInitializer initializer : initializers) {
		initializer.onStartup(servletContext);
	}
}
 
Example 35
Project: Spring-5.0-Cookbook   File: SpringWebInitializer.java   Source Code and License 5 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("*.html");
  dispatcher.setLoadOnStartup(1);
}
 
Example 36
Project: hevelian-activemq   File: WebBrokerInitializerTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = BrokerLifecycleException.class)
public void contextDestroyed_excDuringWaitUntilStopped_ExcThrown() throws Exception {
	ServletContext sc = mock(ServletContext.class);

	BrokerService broker = mock(BrokerService.class);
	doReturn(true).when(broker).isStarted();
	doReturn(true).when(broker).waitUntilStarted();
	doThrow(new BrokerLifecycleException()).when(broker).waitUntilStopped();

	WebBrokerInitializer i = spy(WebBrokerInitializer.class);
	doReturn(broker).when(i).createBroker(sc);

	i.contextInitialized(new ServletContextEvent(sc));
	i.contextDestroyed(new ServletContextEvent(sc));
}
 
Example 37
Project: lazycat   File: TldLocationsCache.java   Source Code and License 5 votes vote down vote up
/**
 * Obtains the TLD location cache for the given {@link ServletContext} and
 * creates one if one does not currently exist.
 */
public static synchronized TldLocationsCache getInstance(ServletContext ctxt) {
	if (ctxt == null) {
		throw new IllegalArgumentException("ServletContext was null");
	}
	TldLocationsCache cache = (TldLocationsCache) ctxt.getAttribute(KEY);
	if (cache == null) {
		cache = new TldLocationsCache(ctxt);
		ctxt.setAttribute(KEY, cache);
	}
	return cache;
}
 
Example 38
Project: Spring-5.0-Cookbook   File: TestContextConfiguration.java   Source Code and License 5 votes vote down vote up
@Test
public void testApplicaticatonContextBeans() {
    ServletContext servletContext = ctx.getServletContext();
    Assert.assertNotNull(servletContext);
    Assert.assertNotNull(ctx.getBean("helloController"));
    Assert.assertNotNull(ctx.getBean("formController"));
}
 
Example 39
Project: Spring-Security-Third-Edition   File: WebAppInitializer.java   Source Code and License 5 votes vote down vote up
@Override
public void onStartup(final ServletContext servletContext)
        throws ServletException {

    // Register DispatcherServlet
    super.onStartup(servletContext);

    // Register H2 Admin console:
    ServletRegistration.Dynamic h2WebServlet = servletContext.addServlet("h2WebServlet",
            "org.h2.server.web.WebServlet");
    h2WebServlet.addMapping("/admin/h2/*");
    h2WebServlet.setInitParameter("webAllowOthers", "true");

}
 
Example 40
Project: myfaces-trinidad   File: CheckSerializationConfigurator.java   Source Code and License 5 votes vote down vote up
public ServletContextMonitorInvocationHandler(ServletContext context, Map<String, Object> appMap)
{
  _delegate = context;
  
  // if we already have an Application Map, use it, otherwise create a wrapper around
  // the ServletContext
  if (appMap != null)
  {
    _applicationMap = appMap;
  }
  else
  {
    _applicationMap = new ServletApplicationMap(context);
  }
}