org.osgi.service.http.HttpContext Java Examples

The following examples show how to use org.osgi.service.http.HttpContext. 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: HttpClientFactoryTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testStart_dmFound() throws Exception {

	// Mock
	Bundle b = Mockito.mock( Bundle.class );
	Mockito.when( b.getSymbolicName()).thenReturn( "net.roboconf.dm" );

	this.factory.httpService = Mockito.mock( HttpService.class );
	this.factory.bundleContext = Mockito.mock( BundleContext.class );
	Mockito.when( this.factory.bundleContext.getBundles()).thenReturn( new Bundle[] { b });

	// Start
	this.factory.start();

	// Check
	Mockito.verify( this.factory.httpService, Mockito.times( 1 )).registerServlet(
			Mockito.eq( HttpConstants.DM_SOCKET_PATH ),
			Mockito.any( Servlet.class ),
			Mockito.any( Dictionary.class ),
			Mockito.isNull( HttpContext.class ));
}
 
Example #2
Source File: HttpServiceImpl.java    From fuchsia with Apache License 2.0 6 votes vote down vote up
public void registerServlet(String context, Servlet servlet, Dictionary dictionary, HttpContext httpContext) throws ServletException, NamespaceException {

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        server.setHandler(contexts);
        ServletContextHandler root = new ServletContextHandler(contexts, "/",
                ServletContextHandler.SESSIONS);
        ServletHolder servletHolder = new ServletHolder(servlet);
        root.addServlet(servletHolder, context);

        if (!server.getServer().getState().equals(server.STARTED)) {
            try {
                server.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
 
Example #3
Source File: ServletContextManager.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized ServletContext getServletContext(final HttpContext httpContext,
                                                     String realPath)
{

  if (realPath == null) {
    realPath = "";
  }

  final ContextKey key = new ContextKey(httpContext, realPath);
  ServletContextImpl context = contextMap.get(key);
  if (context == null) {
    context =
      new ServletContextImpl(httpContext, realPath, httpConfig, log,
                             registrations);
    keyMap.put(context, key);
    contextMap.put(key, context);
  } else {
    keyMap.get(context).referenceCount++;
  }

  return context;
}
 
Example #4
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean addConstraintMapping(HttpContext httpContext, WebContainer service, Object cm) {
    if (cm instanceof ConstraintMapping) {
        ConstraintMapping constraintMapping = (ConstraintMapping) cm;
        Constraint constraint = constraintMapping.getConstraint();
        String[] roles = constraint.getRoles();
        // name property is unavailable on constraint object :/

        String name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);

        int dataConstraint = constraint.getDataConstraint();
        String dataConstraintStr;
        switch (dataConstraint) {
            case Constraint.DC_UNSET:
                dataConstraintStr = null;
                break;
            case Constraint.DC_NONE:
                dataConstraintStr = "NONE";
                break;
            case Constraint.DC_CONFIDENTIAL:
                dataConstraintStr = "CONFIDENTIAL";
                break;
            case Constraint.DC_INTEGRAL:
                dataConstraintStr = "INTEGRAL";
                break;
            default:
                log.warnv("Unknown data constraint: " + dataConstraint);
                dataConstraintStr = "CONFIDENTIAL";
        }
        List<String> rolesList = Arrays.asList(roles);

        log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getPathSpec() + ", dataConstraint=" + dataConstraintStr + ", canAuthenticate="
                + constraint.getAuthenticate() + ", roles=" + rolesList);
        service.registerConstraintMapping(name, constraintMapping.getPathSpec(), null, dataConstraintStr, constraint.getAuthenticate(), rolesList, httpContext);
        return true;
    }
    return false;
}
 
Example #5
Source File: HttpContextFactoryServiceImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void httpContextShouldCallgetResourceOnBundle() {
    HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
    context.getResource(RESOURCE);

    verify(httpContext).wrap(bundle);
    verify(bundle).getResource(RESOURCE);
}
 
Example #6
Source File: HttpContextFactoryServiceImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateHttpContext() {
    HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
    assertThat(context, is(notNullValue()));

    verify(httpContext).wrap(bundle);
}
 
Example #7
Source File: HttpContextFactoryServiceImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void httpContextShouldCallgetResourceOnBundleWithoutLeadingSlash() {
    HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
    context.getResource("/" + RESOURCE);

    verify(httpContext).wrap(bundle);
    verify(bundle).getResource(RESOURCE);
}
 
Example #8
Source File: LoggedInUserFilter.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	if (httpRequest.getRemoteUser() != null) {
		chain.doFilter(request, response);
		return;
	}

	String login;
	if (redirect) {
		login = authenticationService.authenticateUser(httpRequest, httpResponse);
		if (login == null) {
			return;
		}
	} else {
		login = authenticationService.getAuthenticatedUser(httpRequest, httpResponse);
		if (login == null) {
			chain.doFilter(request, response);
			return;
		}
	}

	request.setAttribute(HttpContext.REMOTE_USER, login);
	request.setAttribute(HttpContext.AUTHENTICATION_TYPE, authenticationService.getAuthType());
	chain.doFilter(request, response);
}
 
Example #9
Source File: RequestImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public String getAuthType()
{
  final Object o = getAttribute(HttpContext.AUTHENTICATION_TYPE);
  if (o instanceof String) {
    return (String) o;
  }
  return null;
}
 
Example #10
Source File: ServletContextImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
ServletContextImpl(final HttpContext httpContext, final String realPath,
                   final HttpConfig httpConfig, final LogRef log,
                   final Registrations registrations)
{

  this.httpContext = httpContext;
  this.realPath = realPath;
  this.httpConfig = httpConfig;
  this.log = log;
  this.registrations = registrations;
}
 
Example #11
Source File: RequestImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public String getRemoteUser()
{
  final Object o = getAttribute(HttpContext.REMOTE_USER);
  if (o instanceof String) {
    return (String) o;
  }
  return null;
}
 
Example #12
Source File: ResourceRegistration.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ResourceRegistration(final String alias, final String realPath,
                            final HttpContext httpContext,
                            final ServletContextManager contextManager,
                            long newDate)
{
  this.alias = alias;
  this.httpContext = httpContext;
  this.contextManager = contextManager;
  // HACK CSM
  lastModificationDate = newDate;

  context = contextManager.getServletContext(httpContext, realPath);
  config = new ServletConfigImpl(new Hashtable<String, String>(), context);
}
 
Example #13
Source File: RequestDispatcherImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * HACK CSM
 */
RequestDispatcherImpl(final String servletPath, final Servlet servlet,
                      final HttpContext httpContext,
                      final ServletConfig config, long newDate, URL resourceURL)
{
  this.servletPath = servletPath;
  this.servlet = servlet;
  this.httpContext = httpContext;
  this.config = config;
  lastModificationDate = newDate;
  this.resourceURL = resourceURL;
}
 
Example #14
Source File: HttpServiceImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void registerResources(String alias,
                              String realPath,
                              HttpContext httpContext)
    throws NamespaceException
{
  if (closed) {
    throw new IllegalStateException("Service has been unget");
  }

  if (realPath.length() > 0 && realPath.charAt(realPath.length() - 1) == '/') {
    throw new IllegalArgumentException(
                                       "The name parameter must not end with slash: "
                                           + realPath);
  }

  if (httpContext == null) {
    if (defaultBundleContext == null) {
      defaultBundleContext = createDefaultHttpContext();
    }
    httpContext = defaultBundleContext;
  }

  // HACK CSM now caching "last updated" time
  register(alias,
           new ResourceRegistration(alias, realPath, httpContext,
                                    contextManager, System
                                        .currentTimeMillis()));
}
 
Example #15
Source File: ServletRegistration.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ServletRegistration(final String alias, final Servlet servlet,
                           Dictionary<String, String> parameters,
                           final HttpContext httpContext,
                           final ServletContextManager contextManager,
                           final Registrations registrations)
  throws ServletException
{
  if (parameters == null) {
    parameters = new Hashtable<String, String>();
  }

  if (parameters.get(HttpUtil.SERVLET_NAME_KEY) == null) {
    parameters.put(HttpUtil.SERVLET_NAME_KEY, servlet.getClass().getName());
  }

  this.contextManager = contextManager;
  this.registrations = registrations;

  // Fail fast if servlet already registered!
  registrations.addServlet(servlet);

  final ServletContext context =
    contextManager.getServletContext(httpContext, null);
  final ServletConfig config = new ServletConfigImpl(parameters, context);
  servlet.init(config);

  dispatcher =
    new RequestDispatcherImpl(alias, servlet, httpContext,
                              lastModificationDate);
}
 
Example #16
Source File: JspBundle.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public JspBundle ( final Bundle bundle, final HttpService service, final HttpContext context ) throws ServletException, NamespaceException
{
    this.service = service;

    this.alias = String.format ( "/bundle/%s/WEB-INF", bundle.getBundleId () );
    this.servlet = new JspServlet ( bundle, "/WEB-INF", this.alias );

    logger.info ( "Registering JSP servlet - resources: /WEB-INF, alias: {}, bundle: {}", this.alias, bundle.getSymbolicName () );

    final Dictionary<String, String> initparams = new Hashtable<> ( 2 );
    initparams.put ( "compilerSourceVM", "1.8" );
    initparams.put ( "compilerTargetVM", "1.8" );

    this.service.registerServlet ( this.alias, this.servlet, initparams, context );
}
 
Example #17
Source File: JaxRSServerContainer.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, Object> exportRemoteService(RSARemoteServiceRegistration reg) {
	// Create Servlet
	Servlet servlet = createServlet(reg);
	if (servlet == null)
		throw new NullPointerException(
				"Servlet is null.  It cannot be null to export Jax RS servlet.   See subclass implementation of JaxRSServerContainer.createServlet()");
	// Create servletProps
	@SuppressWarnings("rawtypes")
	Dictionary servletProperties = createServletProperties(reg);
	// Create HttpContext
	HttpContext servletContext = createServletContext(reg);
	// Get servlet alias
	String servletAlias = getServletAlias(reg);
	// Get HttpService instance
	HttpService httpService = getHttpService();
	if (httpService == null)
		throw new NullPointerException("HttpService cannot cannot be null");
	synchronized (this.registrations) {
		try {
			httpService.registerServlet(servletAlias, servlet, servletProperties, servletContext);
		} catch (ServletException | NamespaceException e) {
			throw new RuntimeException("Cannot register servlet with alias=" + servletAlias, e);
		}
		this.registrations.put(servletAlias, reg);
	}
	return createExtraExportProperties(servletAlias, reg);
}
 
Example #18
Source File: HttpContextFactoryServiceImplTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldCreateHttpContext() {
    HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
    assertThat(context, is(notNullValue()));

    verify(httpContext).wrap(bundle);
}
 
Example #19
Source File: HttpContextFactoryServiceImplTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void httpContextShouldCallgetResourceOnBundle() {
    HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
    context.getResource(RESOURCE);

    verify(httpContext).wrap(bundle);
    verify(bundle).getResource(RESOURCE);
}
 
Example #20
Source File: HttpContextFactoryServiceImplTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void httpContextShouldCallgetResourceOnBundleWithoutLeadingSlash() {
    HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
    context.getResource("/" + RESOURCE);

    verify(httpContext).wrap(bundle);
    verify(bundle).getResource(RESOURCE);
}
 
Example #21
Source File: WebAppServlet.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Activate
protected void activate(Map<String, Object> configProps, BundleContext bundleContext) {
    config.applyConfig(configProps);
    HttpContext httpContext = createHttpContext(bundleContext.getBundle());

    super.activate(WEBAPP_ALIAS + "/" + SERVLET_NAME, httpContext);
    try {
        httpService.registerResources(WEBAPP_ALIAS, "web", httpContext);
    } catch (NamespaceException e) {
        logger.error("Could not register static resources under {}", WEBAPP_ALIAS, e);
    }
}
 
Example #22
Source File: WebAppServlet.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Activate
protected void activate(Map<String, Object> configProps, BundleContext bundleContext) {
    HttpContext httpContext = createHttpContext(bundleContext.getBundle());
    super.activate(WEBAPP_ALIAS + "/" + SERVLET_NAME, httpContext);

    try {
        httpService.registerResources(WEBAPP_ALIAS, "web", httpContext);
    } catch (NamespaceException e) {
        logger.error("Could not register static resources under {}", WEBAPP_ALIAS, e);
    }

    config.applyConfig(configProps);
}
 
Example #23
Source File: LgTvMessageReader.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a {@link SecureHttpContext} which handles the security for this
 * servlet
 * 
 * @return a {@link SecureHttpContext}
 */
protected HttpContext createHttpContext() {
    if (httpService == null) {
        logger.warn("Cannot create HttpContext because the httpService is null");
        return null;
    } else {
        HttpContext defaultHttpContext = httpService.createDefaultHttpContext();
        return new SecureHttpContext(defaultHttpContext, "openHAB.org");
    }
}
 
Example #24
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addConstraintMapping(HttpContext httpContext, WebContainer service, Object cm) {
    if (cm instanceof PaxWebSecurityConstraintMapping) {
        PaxWebSecurityConstraintMapping constraintMapping = (PaxWebSecurityConstraintMapping) cm;
        String name = constraintMapping.getConstraintName();
        if (name == null) {
            name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);
        }
        log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getUrl() + ", dataConstraint=" + constraintMapping.getDataConstraint() + ", canAuthenticate="
                + constraintMapping.isAuthentication() + ", roles=" + constraintMapping.getRoles());
        service.registerConstraintMapping(name, constraintMapping.getUrl(), constraintMapping.getMapping(), constraintMapping.getDataConstraint(), constraintMapping.isAuthentication(), constraintMapping.getRoles(), httpContext);
        return true;
    }
    return false;
}
 
Example #25
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addConstraintMapping(HttpContext httpContext, WebContainer service, Object cm) {
    if (cm instanceof ConstraintMapping) {
        ConstraintMapping constraintMapping = (ConstraintMapping) cm;
        Constraint constraint = constraintMapping.getConstraint();
        String[] roles = constraint.getRoles();
        // name property is unavailable on constraint object :/

        String name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);

        int dataConstraint = constraint.getDataConstraint();
        String dataConstraintStr;
        switch (dataConstraint) {
            case Constraint.DC_UNSET:
                dataConstraintStr = null;
                break;
            case Constraint.DC_NONE:
                dataConstraintStr = "NONE";
                break;
            case Constraint.DC_CONFIDENTIAL:
                dataConstraintStr = "CONFIDENTIAL";
                break;
            case Constraint.DC_INTEGRAL:
                dataConstraintStr = "INTEGRAL";
                break;
            default:
                log.warnv("Unknown data constraint: " + dataConstraint);
                dataConstraintStr = "CONFIDENTIAL";
        }
        List<String> rolesList = Arrays.asList(roles);

        log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getPathSpec() + ", dataConstraint=" + dataConstraintStr + ", canAuthenticate="
                + constraint.getAuthenticate() + ", roles=" + rolesList);
        service.registerConstraintMapping(name, constraintMapping.getPathSpec(), null, dataConstraintStr, constraint.getAuthenticate(), rolesList, httpContext);
        return true;
    }
    return false;
}
 
Example #26
Source File: PaxWebIntegrationService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean addConstraintMapping(HttpContext httpContext, WebContainer service, Object cm) {
    if (cm instanceof SecurityConstraintMappingModel) {
        SecurityConstraintMappingModel constraintMapping = (SecurityConstraintMappingModel) cm;
        String name = constraintMapping.getConstraintName();
        if (name == null) {
            name = "Constraint-" + new SecureRandom().nextInt(Integer.MAX_VALUE);
        }
        log.debug("Adding security constraint name=" + name + ", url=" + constraintMapping.getUrl() + ", dataConstraint=" + constraintMapping.getDataConstraint() + ", canAuthenticate="
                + constraintMapping.isAuthentication() + ", roles=" + constraintMapping.getRoles());
        service.registerConstraintMapping(name, constraintMapping.getUrl(), constraintMapping.getMapping(), constraintMapping.getDataConstraint(), constraintMapping.isAuthentication(), constraintMapping.getRoles(), httpContext);
        return true;
    }
    return false;
}
 
Example #27
Source File: HABotDashboardTile.java    From org.openhab.ui.habot with Eclipse Public License 1.0 5 votes vote down vote up
@Activate
protected void activate(Map<String, Object> configProps, BundleContext context) {
    try {
        Object useGzipCompression = configProps.get("useGzipCompression");
        HttpContext httpContext = new HABotHttpContext(httpService.createDefaultHttpContext(), RESOURCES_BASE,
                (useGzipCompression != null && Boolean.parseBoolean(useGzipCompression.toString())));

        httpService.registerResources(HABOT_ALIAS, RESOURCES_BASE, httpContext);
        logger.info("Started HABot at " + HABOT_ALIAS);
    } catch (NamespaceException e) {
        logger.error("Error during HABot startup: {}", e.getMessage());
    }
}
 
Example #28
Source File: ServletRegistrationComponentTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Override
public void registerResources( String alias, String name, HttpContext context ) throws NamespaceException {
	// nothing
}
 
Example #29
Source File: ServletRegistrationComponentTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings( "rawtypes" )
public void registerServlet( String alias, Servlet servlet, Dictionary initparams, HttpContext context )
throws ServletException, NamespaceException {
	this.pathToServlet.put( alias, servlet );
}
 
Example #30
Source File: ServletRegistrationComponentTest.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Override
public HttpContext createDefaultHttpContext() {
	return null;
}