Java Code Examples for org.wso2.carbon.context.PrivilegedCarbonContext#getThreadLocalCarbonContext()

The following examples show how to use org.wso2.carbon.context.PrivilegedCarbonContext#getThreadLocalCarbonContext() . 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: StratosApiV40.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/cookie")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getCookie() {

    HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    httpSession.setAttribute("userName", carbonContext.getUsername());
    httpSession.setAttribute("tenantDomain", carbonContext.getTenantDomain());
    httpSession.setAttribute("tenantId", carbonContext.getTenantId());

    String sessionId = httpSession.getId();
    return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON).
            entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build();
}
 
Example 2
Source File: CertificateMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static CertificateManagementService getCertificateManagementService() {

        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        CertificateManagementService certificateManagementService = (CertificateManagementService)
                ctx.getOSGiService(CertificateManagementService.class, null);

        if (certificateManagementService == null) {
            String msg = "CertificateManagementAdminServiceImpl Management service not initialized.";
            log.error(msg);
            throw new IllegalStateException(msg);
        }

        return certificateManagementService;
    }
 
Example 3
Source File: APIUtil.java    From product-iots with Apache License 2.0 5 votes vote down vote up
public static DeviceManagementProviderService getDeviceManagementService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    DeviceManagementProviderService deviceManagementProviderService =
            (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
    if (deviceManagementProviderService == null) {
        String msg = "Device Management service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return deviceManagementProviderService;
}
 
Example 4
Source File: RegistryManager.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Persist a serializable object in the registry with the given resource path.
 *
 * @param serializableObject object to be persisted.
 */
public synchronized void persist(String resourcePath, Serializable serializableObject) throws RegistryException {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Persisting resource in registry: [resource-path] %s", resourcePath));
    }

    Registry registry = getRegistry();

    try {
        PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        ctx.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        ctx.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        registry.beginTransaction();
        Resource nodeResource = registry.newResource();
        nodeResource.setContent(serializeToByteArray(serializableObject));
        registry.put(resourcePath, nodeResource);
        registry.commitTransaction();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Resource persisted successfully in registry: [resource-path] %s",
                    resourcePath));
        }
    } catch (Exception e) {
       try {
           registry.rollbackTransaction();
       }catch (Exception e1){
           if (log.isErrorEnabled()) {
               log.error("Could not rollback transaction", e1);
           }
       }
        String msg = "Failed to persist resource in registry: " + resourcePath;
        throw new RegistryException(msg, e);
    }
}
 
Example 5
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static PolicyManagerService getPolicyManagementService() {
    PolicyManagerService policyManagementService;
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    policyManagementService =
            (PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null);
    if (policyManagementService == null) {
        String msg = "PolicyImpl Management service not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return policyManagementService;
}
 
Example 6
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static EventsPublisherService getEventPublisherService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    EventsPublisherService eventsPublisherService =
            (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null);
    if (eventsPublisherService == null) {
        String msg = "Event Publisher service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return eventsPublisherService;
}
 
Example 7
Source File: ServiceHolder.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public static ConfigurationContextService getConfigurationContext() {
    PrivilegedCarbonContext carbonContext =
            PrivilegedCarbonContext.getThreadLocalCarbonContext();
    ConfigurationContextService configurationContextService =
            (ConfigurationContextService) carbonContext.getOSGiService(ConfigurationContextService.class);
    return configurationContextService;
}
 
Example 8
Source File: CookieBasedAuthenticationHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    if (AuthenticationContext.isAthenticated()) {
        return null;
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) message.get("HTTP.REQUEST");
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null && isUserLoggedIn(httpSession)) { // if sesion
        // is
        // avaialble
        String userName = (String) httpSession.getAttribute("userName");
        String tenantDomain = (String) httpSession.getAttribute("tenantDomain");
        int tenantId = (Integer) httpSession.getAttribute("tenantId");
        // the following will get used by the authorization handler..
        PrivilegedCarbonContext carbonContext =
                PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setUsername(userName);
        carbonContext.setTenantDomain(tenantDomain);
        carbonContext.setTenantId(tenantId);

        AuthenticationContext.setAuthenticated(true);
        if (log.isDebugEnabled()) {
            log.debug("authenticated using the " +
                    CookieBasedAuthenticationHandler.class.getName() + "for username  :" +
                    userName + "tenantDomain : " + tenantDomain + " tenantId : " + tenantId);
        }
        return null;

    }
    return Response.status(Response.Status.FORBIDDEN).type(MediaType.APPLICATION_JSON)
            .entity(Utils.buildMessage("The endpoint requires authentication")).build();
}
 
Example 9
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    DeviceAccessAuthorizationService deviceAccessAuthorizationService =
            (DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
    if (deviceAccessAuthorizationService == null) {
        String msg = "DeviceAccessAuthorization service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return deviceAccessAuthorizationService;
}
 
Example 10
Source File: PolicyPublishExecutor.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public void run() {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        context.setTenantDomain(tenantDomain);
        context.setTenantId(tenantId);
        context.setUsername(userName);
        try {
            publish();
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }

    }
 
Example 11
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static DeviceTypeGeneratorService getDeviceTypeGeneratorService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    DeviceTypeGeneratorService deviceTypeGeneratorService =
            (DeviceTypeGeneratorService) ctx.getOSGiService(DeviceTypeGeneratorService.class, null);
    if (deviceTypeGeneratorService == null) {
        String msg = "DeviceTypeGeneratorService service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return deviceTypeGeneratorService;
}
 
Example 12
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static GroupManagementProviderService getGroupManagementProviderService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    GroupManagementProviderService groupManagementProviderService =
            (GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null);
    if (groupManagementProviderService == null) {
        String msg = "GroupImpl Management service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return groupManagementProviderService;
}
 
Example 13
Source File: APIUtil.java    From product-iots with Apache License 2.0 5 votes vote down vote up
public static APIManagementProviderService getAPIManagementProviderService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    APIManagementProviderService apiManagementProviderService =
            (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
    if (apiManagementProviderService == null) {
        String msg = "API management provider service has not initialized.";
        log.error(msg);
        throw new IllegalStateException(msg);
    }
    return apiManagementProviderService;
}
 
Example 14
Source File: DeviceMgtAPIUtils.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public static GeoLocationProviderService getGeoService() {
    PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    GeoLocationProviderService
            geoService = (GeoLocationProviderService) ctx.getOSGiService(GeoLocationProviderService.class, null);
    if (geoService == null) {
        throw new IllegalStateException("Geo Service has not been initialized.");
    }
    return geoService;
}
 
Example 15
Source File: OAuthHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public boolean isAuthenticated(Message message, ClassResourceInfo classResourceInfo) {
    // get the map of protocol headers
    Map protocolHeaders = (TreeMap) message.get(Message.PROTOCOL_HEADERS);
    // get the value for Authorization Header
    List authzHeaders = (ArrayList) protocolHeaders
            .get(SCIMConstants.AUTHORIZATION_HEADER);
    if (authzHeaders != null) {
        // get the authorization header value, if provided
        String authzHeader = (String) authzHeaders.get(0);

        // extract access token
        String accessToken = authzHeader.trim().substring(7).trim();
        // validate access token
        try {
            OAuth2ClientApplicationDTO validationApp = this.validateAccessToken(accessToken);
            OAuth2TokenValidationResponseDTO validationResponse = null;

            if (validationApp != null) {
                validationResponse = validationApp.getAccessTokenValidationResponse();
            }

            if (validationResponse != null && validationResponse.isValid()) {
                String userName = validationResponse.getAuthorizedUser();
                authzHeaders.set(0, userName);

                // setup thread local variable to be consumed by the provisioning framework.
                RealmService realmService = (RealmService) PrivilegedCarbonContext
                        .getThreadLocalCarbonContext().getOSGiService(RealmService.class);
                ThreadLocalProvisioningServiceProvider serviceProvider = new ThreadLocalProvisioningServiceProvider();
                serviceProvider.setServiceProviderName(validationApp.getConsumerKey());
                serviceProvider
                        .setServiceProviderType(ProvisioningServiceProviderType.OAUTH);
                serviceProvider.setClaimDialect(SCIMProviderConstants.DEFAULT_SCIM_DIALECT);
                serviceProvider.setTenantDomain(MultitenantUtils.getTenantDomain(userName));
                IdentityApplicationManagementUtil
                        .setThreadLocalProvisioningServiceProvider(serviceProvider);
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                String tenantDomain = MultitenantUtils.getTenantDomain(userName);
                carbonContext.setUsername(MultitenantUtils.getTenantAwareUsername(userName));
                carbonContext.setTenantId(realmService.getTenantManager().getTenantId(tenantDomain));
                carbonContext.setTenantDomain(tenantDomain);
                return true;
            }
        } catch (Exception e) {
            String error = "Error in validating OAuth access token.";
            log.error(error, e);
        }
    }
    return false;
}
 
Example 16
Source File: AbstractProvisioningConnectorFactory.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * @param identityProviderName
 * @param tenantDomain
 * @throws IdentityProvisioningException
 */
public void destroyConnector(String identityProviderName, String tenantDomain)
        throws IdentityProvisioningException {

    String tenantDomainName = null;
    int tenantId = -1234;

    if (CarbonContext.getThreadLocalCarbonContext() != null) {
        tenantDomainName = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    }

    try {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
                .getThreadLocalCarbonContext();
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        ProvisioningConnectorCacheKey cacheKey = new ProvisioningConnectorCacheKey(identityProviderName, tenantDomain);
        ProvisioningConnectorCacheEntry entry = ProvisioningConnectorCache.getInstance().getValueFromCache(cacheKey);

        if (entry != null) {
            ProvisioningConnectorCache.getInstance().clearCacheEntry(cacheKey);

            if (log.isDebugEnabled()) {
                log.debug("Provisioning cached entry removed for idp " + identityProviderName
                        + " from the connector " + getConnectorType());
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Provisioning cached entry not found for idp " + identityProviderName
                        + " from the connector " + getConnectorType());
            }
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();

        if (tenantDomain != null) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
                    tenantDomainName);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        }
    }
}
 
Example 17
Source File: ProxyTimerTask.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
public void run() {

        synchronized (axisConfig) {
            PrivilegedCarbonContext.startTenantFlow();
            try {
                PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
                privilegedCarbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                privilegedCarbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

                AxisServiceGroup proxyAxisServiceGroup =
                        axisConfig.getServiceGroup(WSDL2FormGenerator.TRYIT_SG_NAME);
                if (proxyAxisServiceGroup != null) {
                    List removeServiceList = new ArrayList();
                    for (Iterator iterator = proxyAxisServiceGroup.getServices();
                         iterator.hasNext();) {
                        AxisService axisServce = (AxisService) iterator.next();
                        Long longTime =
                                (Long) axisServce
                                        .getParameterValue(WSDL2FormGenerator.LAST_TOUCH_TIME);
                        if ((System.currentTimeMillis() - longTime.longValue()) > WSDL2FormGenerator
                                .PERIOD) {
                            removeServiceList.add(axisServce.getName());
                        }

                    }
                    if (removeServiceList.size() > 0) {
                        for (Iterator iterator = removeServiceList.iterator(); iterator.hasNext();)
                        {
                            String axisServiceName = (String) iterator.next();
                            proxyAxisServiceGroup.removeService(axisServiceName);
                        }
                    }
                    boolean isLast = proxyAxisServiceGroup.getServices().hasNext();
                    if (!isLast) {
                        axisConfig.removeServiceGroup(WSDL2FormGenerator.TRYIT_SG_NAME);
                    }
                }
            } catch (AxisFault axisFault) {
                String msg = "Fault occured when manipulating Tryit proxy service group";
                log.error(msg, axisFault);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }

        }
    }
 
Example 18
Source File: ServiceHolder.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public static TenantManager getTenantManager() {
    PrivilegedCarbonContext carbonContext =
            PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class);
    return realmService.getTenantManager();
}
 
Example 19
Source File: ServiceHolder.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public static RealmService getRealmService() {
    PrivilegedCarbonContext carbonContext =
            PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class);
    return realmService;
}
 
Example 20
Source File: ServiceHolder.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
public static RegistryService getRegistryService() {
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    RegistryService registryService = (RegistryService) carbonContext.getOSGiService(RegistryService.class);
    return registryService;
}