Java Code Examples for org.wso2.carbon.apimgt.impl.utils.APIUtil#handleException()

The following examples show how to use org.wso2.carbon.apimgt.impl.utils.APIUtil#handleException() . 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: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This methods loads the monetization implementation class
 *
 * @return monetization implementation class
 * @throws APIManagementException if failed to load monetization implementation class
 */
public Monetization getMonetizationImplClass() throws APIManagementException {

    APIManagerConfiguration configuration = org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.
            getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    Monetization monetizationImpl = null;
    if (configuration == null) {
        log.error("API Manager configuration is not initialized.");
    } else {
        String monetizationImplClass = configuration.getFirstProperty(APIConstants.Monetization.MONETIZATION_IMPL);
        if (monetizationImplClass == null) {
            monetizationImpl = new DefaultMonetizationImpl();
        } else {
            try {
                monetizationImpl = (Monetization) APIUtil.getClassForName(monetizationImplClass).newInstance();
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                APIUtil.handleException("Failed to load monetization implementation class.", e);
            }
        }
    }
    return monetizationImpl;
}
 
Example 2
Source File: RegistryCacheInvalidationClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Invalidates registry cache of the resource in the given path in given server
 * @param path registry path of the resource
 * @param tenantDomain
 * @param serverURL
 * @param cookie
 * @throws AxisFault
 * @throws RemoteException
 * @throws APIManagementException
 */
public void clearCache(String path, String tenantDomain, String serverURL, String cookie) 
        throws AxisFault, RemoteException, APIManagementException {
    RegistryCacheInvalidationServiceStub registryCacheServiceStub;

    ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
    registryCacheServiceStub = getRegistryCacheInvalidationServiceStub(serverURL, ctx);
    ServiceClient client = registryCacheServiceStub._getServiceClient();
    Options options = client.getOptions();
    options.setTimeOutInMilliSeconds(TIMEOUT_IN_MILLIS);
    options.setProperty(HTTPConstants.SO_TIMEOUT, TIMEOUT_IN_MILLIS);
    options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, TIMEOUT_IN_MILLIS);
    options.setManageSession(true);
    options.setProperty(HTTPConstants.COOKIE_STRING, cookie);
    
    try {
        registryCacheServiceStub.invalidateCache(path, tenantDomain);      
    } catch (RegistryCacheInvalidationServiceAPIManagementExceptionException e) {
        APIUtil.handleException(e.getMessage(), e);
    }
}
 
Example 3
Source File: APIKeyMgtRemoteUserStoreMgtService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * validates a username,password combination. Works for any tenant domain.
 * @param username username of the user(including tenant domain)
 * @param password password of the user
 * @return true if username,password is correct
 * @throws APIManagementException
 */
public boolean authenticate(String username, String password) throws APIManagementException {

    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

    UserStoreManager userStoreManager;
    boolean isAuthenticated = false;
    try {
        userStoreManager =
                CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);

        isAuthenticated = userStoreManager.authenticate(tenantAwareUserName, password);
    } catch (UserStoreException e) {
        APIUtil.handleException("Error occurred while validating credentials of user " + username, e);
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
    }
    return isAuthenticated;
}
 
Example 4
Source File: APIKeyMgtRemoteUserStoreMgtService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get the role list of a user. Works for any tenant domain.
 * @param username username with tenant domain
 * @return list of roles
 * @throws APIManagementException
 */
public String[] getUserRoles(String username) throws APIManagementException {

    String userRoles[] = null;
    String tenantDomain = MultitenantUtils.getTenantDomain(username);

    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

    UserStoreManager userStoreManager;
    try {
        userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        userRoles = userStoreManager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username));
    } catch (UserStoreException e) {
        APIUtil.handleException("Error occurred retrieving roles of user " + username, e);
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
    }
    return userRoles;
}
 
Example 5
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new label for the tenant
 *
 * @param tenantDomain    tenant domain
 * @param label           content to add
 * @throws APIManagementException if failed add Label
 */
public Label addLabel(String tenantDomain, Label label) throws APIManagementException {

    if (isLableNameExists(tenantDomain, label)) {
        APIUtil.handleException("Label with name " + label.getName() + " already exists");
    }
    return apiMgtDAO.addLabel(tenantDomain, label);
}
 
Example 6
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Delete an existing label
 *
 * @param labelId Label identifier
 * @throws APIManagementException If failed to delete label
 */
public void deleteLabel(String user, String labelId) throws APIManagementException {

    if (isAttachedLabel(user, labelId)) {
        APIUtil.handleException("Unable to delete the label. It is attached to an API");
    }
    apiMgtDAO.deleteLabel(labelId);
}
 
Example 7
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public APICategory addCategory(APICategory category, String userName) throws APIManagementException {

        int tenantID = APIUtil.getTenantId(userName);
        if (isCategoryNameExists(category.getName(), null, tenantID)) {
            APIUtil.handleException("Category with name '" + category.getName() + "' already exists");
        }
        return apiMgtDAO.addCategory(tenantID, category);
    }
 
Example 8
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void deleteCategory(String categoryID, String username) throws APIManagementException {

        APICategory category = getAPICategoryByID(categoryID);
        int attchedAPICount = isCategoryAttached(category, username);
        if (attchedAPICount > 0) {
            APIUtil.handleException("Unable to delete the category. It is attached to API(s)");
        }
        apiMgtDAO.deleteCategory(categoryID);
    }
 
Example 9
Source File: APIKeyMgtRemoteUserStoreMgtService.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public BasicAuthValidationInfoDTO getUserAuthenticationInfo(String username, String password)
        throws APIManagementException {

    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);

    UserStoreManager userStoreManager;
    BasicAuthValidationInfoDTO basicAuthValidationInfoDTO = new BasicAuthValidationInfoDTO();
    boolean isAuthenticated;
    String userRoles[];
    String domainQualifiedUsername;
    try {
        userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        isAuthenticated = userStoreManager
                .authenticate(MultitenantUtils.getTenantAwareUsername(username), password);
        if (isAuthenticated) {
            basicAuthValidationInfoDTO.setAuthenticated(true);
            domainQualifiedUsername = UserCoreUtil.addDomainToName(username, UserCoreUtil.getDomainFromThreadLocal());
            basicAuthValidationInfoDTO.setDomainQualifiedUsername(domainQualifiedUsername);
        } else {
            //return default validation DTO with authentication false
            return basicAuthValidationInfoDTO;
        }
        //Get role list of user.
        //Should give the domain qualified username when getting the role list of user.
        userRoles = userStoreManager
                .getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(domainQualifiedUsername));
        basicAuthValidationInfoDTO.setUserRoleList(userRoles);
    } catch (UserStoreException e) {
        APIUtil.handleException("Error occurred while retrieving user authentication info of user " + username, e);
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
    }
    return basicAuthValidationInfoDTO;
}
 
Example 10
Source File: AbstractApplicationRegistrationWorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO)
        throws APIManagementException{
    log.debug("Registering Application and creating an Access Token... ");
    Application application = workflowDTO.getApplication();
    Subscriber subscriber = application.getSubscriber();
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
        dao.populateAppRegistrationWorkflowDTO(workflowDTO);
    }

    try {
        //get new key manager
        String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
        String keyManagerName = workflowDTO.getKeyManager();
        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        if (keyManager == null){
            throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
        }
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo()
                   .setClientName(application.getName());

        // set applications attributes to the oAuthApplicationInfo
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo()
                .putAllAppAttributes(application.getApplicationAttributes());

        //createApplication on oAuthorization server.
        OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());

        //update associateApplication
        ApplicationUtils
                .updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerName);

        //change create application status in to completed.
        dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED,
                workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerName);

        workflowDTO.setApplicationInfo(oAuthApplication);
        AccessTokenInfo tokenInfo;
        Object enableTokenGeneration = keyManager.getKeyManagerConfiguration()
                .getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
            if (enableTokenGeneration != null && (Boolean) enableTokenGeneration &&
                    oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
                AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager,
                        oAuthApplication, null);
                tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
            } else {
                tokenInfo = new AccessTokenInfo();
                tokenInfo.setAccessToken("");
                tokenInfo.setValidityPeriod(0L);
                String[] noScopes = new String[] {"N/A"};
                tokenInfo.setScope(noScopes);
                oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
            }
        workflowDTO.setAccessTokenInfo(tokenInfo);
    } catch (Exception e) {
        APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
    }
}