javax.servlet.ServletContext Java Examples

The following examples show how to use javax.servlet.ServletContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IWAUIAuthenticator.java    From carbon-identity with Apache License 2.0 7 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void authenticate(HttpServletRequest request) throws AuthenticationException {

    String userName = request.getRemoteUser();
    userName = userName.substring(userName.indexOf("\\") + 1);

    if (log.isDebugEnabled()) {
        log.debug("Authenticate request received : Authtype - " + request.getAuthType() +
                ", User - " + userName);
    }

    ServletContext servletContext = request.getSession().getServletContext();
    HttpSession session = request.getSession();
    String backendServerURL = request.getParameter("backendURL");
    if (backendServerURL == null) {
        backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
    }

    session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);
    String rememberMe = request.getParameter("rememberMe");

    handleSecurity(userName, (rememberMe != null), request);
    request.setAttribute("username", userName);
}
 
Example #2
Source File: JSR356WebsocketInitializer.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    // Destroy any AtmosphereFramework instance we have initialized.
    // This must be done here to ensure that we cleanup Atmosphere instances
    // related to servlets which are never initialized
    ServletContext servletContext = sce.getServletContext();
    Enumeration<String> attributeNames = servletContext.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String attributeName = attributeNames.nextElement();
        if (isAtmosphereFrameworkAttribute(attributeName)) {
            Object value = servletContext.getAttribute(attributeName);
            if (value instanceof AtmosphereFramework) {
                // This might result in calling destroy() twice, once from
                // here and once from PushRequestHandler but
                // AtmosphereFramework.destroy() deals with that
                ((AtmosphereFramework) value).destroy();
            }
        }
    }
}
 
Example #3
Source File: PluginContextListener.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {

   ServletContext context = servletContextEvent.getServletContext();

   plugin = new HawtioPlugin();
   plugin.setContext((String)context.getInitParameter("plugin-context"));
   plugin.setName(context.getInitParameter("plugin-name"));
   plugin.setScripts(context.getInitParameter("plugin-scripts"));
   plugin.setDomain(null);

   try {
      plugin.init();
   } catch (Exception e) {
      throw createServletException(e);
   }

   LOG.info("Initialized {} plugin", plugin.getName());
}
 
Example #4
Source File: WebConfigurer.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Spring and Spring MVC.
 */
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
    LOGGER.debug("Configuring Spring Web application context");
    AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
    dispatcherServletConfiguration.setParent(rootContext);
    dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);

    LOGGER.debug("Registering Spring MVC Servlet");
    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
    dispatcherServlet.addMapping("/service/*");
    dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.setAsyncSupported(true);

    return dispatcherServlet;
}
 
Example #5
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    // Register and map servlet
    Servlet s = new TesterServlet();
    ServletRegistration.Dynamic sr = ctx.addServlet("test", s);
    sr.addMapping("/test");

    // Add a constraint with uncovered methods
    HttpConstraintElement hce = new HttpConstraintElement(
            TransportGuarantee.NONE, "tomcat");
    HttpMethodConstraintElement hmce =
            new HttpMethodConstraintElement("POST", hce);
    Set<HttpMethodConstraintElement> hmces = new HashSet<>();
    hmces.add(hmce);
    ServletSecurityElement sse = new ServletSecurityElement(hmces);
    sr.setServletSecurity(sse);
}
 
Example #6
Source File: UrlRewriteResponseTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolve() throws Exception {

  UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );

  ServletContext context = EasyMock.createNiceMock( ServletContext.class );
  EasyMock.expect( context.getServletContextName() ).andReturn( "test-cluster-name" ).anyTimes();
  EasyMock.expect( context.getInitParameter( "test-init-param-name" ) ).andReturn( "test-init-param-value" ).anyTimes();
  EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();

  FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
  EasyMock.expect( config.getInitParameter( "test-filter-init-param-name" ) ).andReturn( "test-filter-init-param-value" ).anyTimes();
  EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();

  HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
  HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );

  EasyMock.replay( rewriter, context, config, request, response );

  UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );

  List<String> names = rewriteResponse.resolve( "test-filter-init-param-name" );
  assertThat( names.size(), is( 1 ) );
  assertThat( names.get( 0 ), is( "test-filter-init-param-value" ) );
}
 
Example #7
Source File: TestPluginMonitoringFilter.java    From javamelody with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws ServletException {
	pluginMonitoringFilter = new MyPluginMonitoringFilter();
	final FilterConfig config = createNiceMock(FilterConfig.class);
	final ServletContext context = createNiceMock(ServletContext.class);
	expect(config.getServletContext()).andReturn(context).anyTimes();
	//		expect(config.getFilterName()).andReturn(FILTER_NAME).anyTimes();
	expect(context.getMajorVersion()).andReturn(2).anyTimes();
	expect(context.getMinorVersion()).andReturn(5).anyTimes();
	expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
	expect(context.getServerInfo()).andReturn("mockJetty").anyTimes();
	replay(config);
	replay(context);
	pluginMonitoringFilter.init(config);
	verify(config);
	verify(context);
}
 
Example #8
Source File: UtilHttp.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Create a map from a ServletContext object
 * @return The resulting Map
 */
public static Map<String, Object> getServletContextMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
    Map<String, Object> servletCtxMap = new HashMap<>();

    // look at all servlet context attributes
    ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
    Enumeration<String> applicationAttrNames = UtilGenerics.cast(servletContext.getAttributeNames());
    while (applicationAttrNames.hasMoreElements()) {
        String attrName = applicationAttrNames.nextElement();
        if (namesToSkip != null && namesToSkip.contains(attrName)) {
            continue;
        }

        Object attrValue = servletContext.getAttribute(attrName);
        servletCtxMap.put(attrName, attrValue);
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("Made ServletContext Attribute Map with [" + servletCtxMap.size() + "] Entries", module);
        Debug.logVerbose("ServletContext Attribute Map Entries: " + System.getProperty("line.separator") + UtilMisc.printMap(servletCtxMap), module);
    }

    return servletCtxMap;
}
 
Example #9
Source File: PrometheusServlet.java    From dropwizard-prometheus with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    final ServletContext context = config.getServletContext();
    if (null == registry) {
        final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
        if (registryAttr instanceof MetricRegistry) {
            this.registry = (MetricRegistry) registryAttr;
        } else {
            throw new ServletException("Couldn't find a MetricRegistry instance.");
        }
    }

    filter = (MetricFilter) context.getAttribute(METRIC_FILTER);
    if (filter == null) {
        filter = MetricFilter.ALL;
    }

    this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN);
}
 
Example #10
Source File: ServletDeployer.java    From flow with Apache License 2.0 6 votes vote down vote up
private void logServletCreation(VaadinServletCreation servletCreation,
        ServletContext servletContext, boolean productionMode) {
    Logger logger = getLogger();

    if (servletCreation == null || productionMode) {
        // the servlet creation is explicitly disabled or production mode
        // activated - just info
        logger.info(servletCreationMessage);
    } else if (servletCreation == VaadinServletCreation.NO_CREATION) {
        // debug mode and servlet not created for some reason - make it more
        // visible with warning
        logger.warn(servletCreationMessage);
    } else {
        logger.info(servletCreationMessage);
        ServletRegistration vaadinServlet = findVaadinServlet(
                servletContext);
        logAppStartupToConsole(servletContext,
                servletCreation == VaadinServletCreation.SERVLET_CREATED
                        || vaadinServlet != null
                                && "com.vaadin.cdi.CdiServletDeployer"
                                        .equals(vaadinServlet.getName()));
    }
}
 
Example #11
Source File: InterfaceX_ServiceSideServer.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    ServletContext context = servletConfig.getServletContext();
    String controllerClassName =
            context.getInitParameter("InterfaceX_Service");
    try {
        Class controllerClass = Class.forName(controllerClassName);

        // If the class has a getInstance() method, call that method rather than
        // calling a constructor (& thus instantiating 2 instances of the class)
        try {
            Method instMethod = controllerClass.getDeclaredMethod("getInstance");
            _controller = (InterfaceX_Service) instMethod.invoke(null);
        }
        catch (NoSuchMethodException nsme) {
            _controller = (InterfaceX_Service) controllerClass.newInstance();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #12
Source File: SpringWebInitializer.java    From Spring-5.0-Cookbook with MIT License 6 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);

	FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter());
	corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE");
	corsFilter.addMappingForUrlPatterns(null, true, "/*");

	FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter());
	filter.addMappingForServletNames(null, true, "/*");

	FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter());
	multipartFilter.addMappingForUrlPatterns(null, true, "/*");

}
 
Example #13
Source File: WebUtils.java    From spring-analysis-note with MIT 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 #14
Source File: WebUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the real path of the given path within the web application,
 * as provided by the servlet container.
 * <p>Prepends a slash if the path does not already start with a slash,
 * and throws a FileNotFoundException if the path cannot be resolved to
 * a resource (in contrast to ServletContext's {@code getRealPath},
 * which returns null).
 * @param servletContext the servlet context of the web application
 * @param path the path within the web application
 * @return the corresponding real path
 * @throws FileNotFoundException if the path cannot be resolved to a resource
 * @see javax.servlet.ServletContext#getRealPath
 */
public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	// Interpret location as relative to the web application root directory.
	if (!path.startsWith("/")) {
		path = "/" + path;
	}
	String realPath = servletContext.getRealPath(path);
	if (realPath == null) {
		throw new FileNotFoundException(
				"ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +
				"web application archive not expanded?");
	}
	return realPath;
}
 
Example #15
Source File: WarResourceFetcher.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
public WarResourceFetcher(ServletContext servletContext, Path homeDir) {
	if (homeDir != null) {
		addPath(homeDir);
	}
	String realPath = servletContext.getRealPath("/");
	if (!realPath.endsWith("/")) {
		realPath = realPath + "/";
	}
	addPath(Paths.get(realPath + "WEB-INF"));
}
 
Example #16
Source File: JSR356WebsocketInitializer.java    From flow with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes Atmosphere for use with Vaadin servlets found in the given
 * context.
 * <p>
 * For JSR 356 websockets to work properly, the initialization must be done
 * in the servlet context initialization phase.
 *
 * @param servletContext
 *            The servlet context
 */
public void init(ServletContext servletContext) {
    if (!atmosphereAvailable) {
        return;
    }
    getLogger().debug("Atmosphere available, initializing");

    Map<String, ? extends ServletRegistration> regs = servletContext
            .getServletRegistrations();
    for (Entry<String, ? extends ServletRegistration> entry : regs
            .entrySet()) {
        String servletName = entry.getKey();
        ServletRegistration servletRegistration = entry.getValue();

        getLogger().debug("Checking if {} is a Vaadin Servlet",
                servletRegistration.getName());

        if (isVaadinServlet(servletRegistration, servletContext)) {
            try {
                initAtmosphereForVaadinServlet(servletRegistration,
                        servletContext);
            } catch (Exception e) {
                getLogger().warn("Failed to initialize Atmosphere for {}",
                        servletName, e);
            }
        }
    }
}
 
Example #17
Source File: PresenceManager.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SipURI getOutboundInterface(final ServletConfig config) {
final ServletContext context = config.getServletContext();
SipURI result = null;
@SuppressWarnings("unchecked")
final List<SipURI> uris = (List<SipURI>)context.getAttribute(OUTBOUND_INTERFACES);
for(final SipURI uri : uris) {
	final String transport = uri.getTransportParam();
	if("udp".equalsIgnoreCase(transport)) {
		result = uri;
	}
}
return result;
 }
 
Example #18
Source File: RedisHttpSessionRepository.java    From RedisHttpSession with Apache License 2.0 5 votes vote down vote up
/**
 * get session according to token
 *
 * @param token
 * @param servletContext
 * @return session associate to token or null if the token is invalid
 */
public HttpSession getSession(String token, ServletContext servletContext) {
    checkConnection();
    if (redisConnection.exists(RedisHttpSession.SESSION_PREFIX + token)) {
        RedisHttpSession redisHttpSession = RedisHttpSession.createWithExistSession(token, servletContext, redisConnection);
        return (HttpSession) new RedisHttpSessionProxy().bind(redisHttpSession);
    } else {
        throw new IllegalStateException("The HttpSession has already be invalidated.");
    }
}
 
Example #19
Source File: AbstractMgwtManifestServletTest.java    From gwt-appcache with Apache License 2.0 5 votes vote down vote up
@Override
public ServletContext getServletContext()
{
  if ( null == _servletContext )
  {
    _servletContext = mock( ServletContext.class );
  }
  return _servletContext;
}
 
Example #20
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static InputStream getJSONFromServletContext(ServletContext servletContext) {
    String json = servletContext.getInitParameter(AdapterConstants.AUTH_DATA_PARAM_NAME);
    if (json == null) {
        return null;
    }
    return new ByteArrayInputStream(json.getBytes());
}
 
Example #21
Source File: StaticResourceServletTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private HttpServletResponse doGetTest(final String uri,
                                      final Map<String, String> headers) throws ServletException,
        IOException {
    final StaticResourceServlet servlet = Mockito
            .mock(StaticResourceServlet.class);
    Mockito.doCallRealMethod()
           .when(servlet)
           .doGet(Matchers.any(HttpServletRequest.class),
                   Matchers.any(HttpServletResponse.class));
    final ServletContext servletContext = Mockito
            .mock(ServletContext.class);
    Mockito.when(servletContext.getRealPath(uri)).thenReturn(
            new File(rootDirectory, uri).getAbsolutePath());
    Mockito.when(servlet.getServletContext()).thenReturn(servletContext);

    final HttpServletRequest request = Mockito
            .mock(HttpServletRequest.class);
    Mockito.when(request.getServletPath()).thenReturn(uri);
    Mockito.when(request.getHeader(Matchers.anyString())).thenAnswer(
            new Answer<String>() {

                @Override
                public String answer(final InvocationOnMock invocation)
                        throws Throwable {
                    return headers.get(invocation.getArguments()[0]);
                }
            });
    final HttpServletResponse response = Mockito
            .mock(HttpServletResponse.class);
    final ServletOutputStream responseBody = Mockito
            .mock(ServletOutputStream.class);
    Mockito.when(response.getOutputStream()).thenReturn(responseBody);
    servlet.doGet(request, response);
    return response;
}
 
Example #22
Source File: DfsServlet.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link NameNode} proxy from the current {@link ServletContext}. 
 */
protected ClientProtocol createNameNodeProxy(UnixUserGroupInformation ugi
    ) throws IOException {
  ServletContext context = getServletContext();
  InetSocketAddress nnAddr = (InetSocketAddress)context.getAttribute("name.node.address");
  if (nnAddr == null) {
    throw new IOException("The namenode is not out of safemode yet");
  }
  Configuration conf = new Configuration(
      (Configuration)context.getAttribute("name.conf"));
  UnixUserGroupInformation.saveToConf(conf,
      UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi);
  return DFSClient.createNamenode(nnAddr, conf);
}
 
Example #23
Source File: ReplicatedContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public ServletContext getServletContext() {
    if (context == null) {
        context = new ReplApplContext(this);
        if (getAltDDName() != null)
            context.setAttribute(Globals.ALT_DD_ATTR,getAltDDName());
    }

    return ((ReplApplContext)context).getFacade();

}
 
Example #24
Source File: FsckServlet.java    From big-c with Apache License 2.0 5 votes vote down vote up
/** Handle fsck request */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response
    ) throws IOException {
  @SuppressWarnings("unchecked")
  final Map<String,String[]> pmap = request.getParameterMap();
  final PrintWriter out = response.getWriter();
  final InetAddress remoteAddress = 
    InetAddress.getByName(request.getRemoteAddr());
  final ServletContext context = getServletContext();    
  final Configuration conf = NameNodeHttpServer.getConfFromContext(context);

  final UserGroupInformation ugi = getUGI(request, conf);
  try {
    ugi.doAs(new PrivilegedExceptionAction<Object>() {
      @Override
      public Object run() throws Exception {
        NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context);
        
        final FSNamesystem namesystem = nn.getNamesystem();
        final BlockManager bm = namesystem.getBlockManager();
        final int totalDatanodes = 
            namesystem.getNumberOfDatanodes(DatanodeReportType.LIVE); 
        new NamenodeFsck(conf, nn,
            bm.getDatanodeManager().getNetworkTopology(), pmap, out,
            totalDatanodes, remoteAddress).fsck();
        
        return null;
      }
    });
  } catch (InterruptedException e) {
    response.sendError(400, e.getMessage());
  }
}
 
Example #25
Source File: TesterServletContainerInitializer1.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new TesterServlet();
    ServletRegistration.Dynamic r = ctx.addServlet("TesterServlet1", s);
    r.addMapping("/TesterServlet1");
}
 
Example #26
Source File: GroovyScriptUtils.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
public static void addSiteItemScriptVariables(Map<String, Object> variables, HttpServletRequest request,
                                              HttpServletResponse response, ServletContext servletContext,
                                              SiteItem item, Object templateModel) {
    addCommonVariables(variables, request, response, servletContext);
    addSecurityVariables(variables);
    addContentModelVariable(variables, item);
    addTemplateModelVariable(variables, templateModel);
}
 
Example #27
Source File: DashboardServlet.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * lastUploaded
 */
private void lastUploaded(HttpServletRequest request, HttpServletResponse response) throws
		PathNotFoundException, RepositoryException, IOException, ServletException, DatabaseException, OKMException {
	log.debug("lastUploaded({}, {})", request, response);
	ServletContext sc = getServletContext();
	sc.setAttribute("action", WebUtils.getString(request, "action"));
	sc.setAttribute("dashboardDocs", new com.openkm.servlet.frontend.DashboardServlet().getUserLastUploadedDocuments());
	sc.getRequestDispatcher("/" + Config.MOBILE_CONTEXT + "/dashboard_browse.jsp").forward(request, response);
}
 
Example #28
Source File: ServletContextAwareProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void servletContextAwareWithNullServletContextAndNonNullServletConfig() {
	ServletContext servletContext = new MockServletContext();
	ServletConfig servletConfig = new MockServletConfig(servletContext);
	ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig);
	ServletContextAwareBean bean = new ServletContextAwareBean();
	assertNull(bean.getServletContext());
	processor.postProcessBeforeInitialization(bean, "testBean");
	assertNotNull("ServletContext should have been set", bean.getServletContext());
	assertEquals(servletContext, bean.getServletContext());
}
 
Example #29
Source File: UrlRewriteServletEnvironmentTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAttribute() throws Exception {
  ServletContext context = EasyMock.createNiceMock( ServletContext.class );
  EasyMock.expect(  context.getAttribute( "test-attribute-name" ) ).andReturn( "test-attribute-value" ).anyTimes();
  EasyMock.replay( context );
  UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
  assertThat(env.getAttribute( "test-attribute-name" ), is( "test-attribute-value" ) );
}
 
Example #30
Source File: BridgeResource.java    From pxf with Apache License 2.0 5 votes vote down vote up
/**
 * Handles read data request. Parses the request, creates a bridge instance and iterates over its
 * records, printing it out to the outgoing stream. Outputs GPDBWritable or Text formats.
 *
 * Parameters come via HTTP headers.
 *
 * @param servletContext Servlet context contains attributes required by SecuredHDFS
 * @param headers Holds HTTP headers from request
 * @return response object containing stream that will output records
 */
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response read(@Context final ServletContext servletContext,
                     @Context HttpHeaders headers) {

    RequestContext context = parseRequest(headers);
    Bridge bridge = bridgeFactory.getReadBridge(context);

    // THREAD-SAFE parameter has precedence
    boolean isThreadSafe = context.isThreadSafe() && bridge.isThreadSafe();
    LOG.debug("Request for {} will be handled {} synchronization", context.getDataSource(), (isThreadSafe ? "without" : "with"));

    return readResponse(bridge, context, isThreadSafe);
}