Search in sources :

Example 6 with APIUtil.handleException

use of org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException in project carbon-apimgt by wso2.

the class APIProviderImpl method getMonetizationImplClass.

/**
 * 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.getClassInstance(monetizationImplClass);
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                APIUtil.handleException("Failed to load monetization implementation class.", e);
            }
        }
    }
    return monetizationImpl;
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) DefaultMonetizationImpl(org.wso2.carbon.apimgt.impl.monetization.DefaultMonetizationImpl)

Example 7 with APIUtil.handleException

use of org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException in project carbon-apimgt by wso2.

the class AbstractApplicationRegistrationWorkflowExecutor method dogenerateKeysForApplication.

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
        // Here the default flow is set expecting an ID as the keymanager as this flow only involves new applications
        String keyManagerId = workflowDTO.getKeyManager();
        KeyManagerConfigurationDTO km = dao.getKeyManagerConfigurationByUUID(keyManagerId);
        String tenantDomain = km.getOrganization();
        String keyManagerName = km.getName();
        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, keyManagerId);
        // change create application status in to completed.
        dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED, workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerId);
        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);
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) Application(org.wso2.carbon.apimgt.api.model.Application) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 8 with APIUtil.handleException

use of org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException in project carbon-apimgt by wso2.

the class APIConsumerImpl method getMonetizationImplClass.

/**
 * 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 = 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.getClassInstance(monetizationImplClass);
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                APIUtil.handleException("Failed to load monetization implementation class.", e);
            }
        }
    }
    return monetizationImpl;
}
Also used : Monetization(org.wso2.carbon.apimgt.api.model.Monetization) DefaultMonetizationImpl(org.wso2.carbon.apimgt.impl.monetization.DefaultMonetizationImpl)

Example 9 with APIUtil.handleException

use of org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException in project carbon-apimgt by wso2.

the class APIAdminImpl method deleteCategory.

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);
}
Also used : APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 10 with APIUtil.handleException

use of org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException in project carbon-apimgt by wso2.

the class RestApiAdminUtils method importTenantTheme.

/**
 * Import the content of the provided tenant theme archive to the file system and the database
 *
 * @param themeContentInputStream content relevant to the tenant theme
 * @param tenantDomain            tenant to which the theme is imported
 * @throws APIManagementException if an error occurs while importing the tenant theme
 * @throws IOException            if an error occurs while performing file or directory related operations
 */
public static void importTenantTheme(InputStream themeContentInputStream, String tenantDomain) throws APIManagementException, IOException {
    ZipInputStream zipInputStream = null;
    byte[] buffer = new byte[1024];
    InputStream existingTenantTheme = null;
    InputStream themeContent = null;
    File tenantThemeDirectory;
    File backupDirectory = null;
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        // add or update the tenant theme in the database
        if (apiAdmin.isTenantThemeExist(tenantId)) {
            existingTenantTheme = apiAdmin.getTenantTheme(tenantId);
            apiAdmin.updateTenantTheme(tenantId, themeContentInputStream);
        } else {
            apiAdmin.addTenantTheme(tenantId, themeContentInputStream);
        }
        // retrieve the tenant theme from the database to import it to the file system
        themeContent = apiAdmin.getTenantTheme(tenantId);
        // import the tenant theme to the file system
        String outputFolder = getTenantThemeDirectoryPath(tenantDomain);
        tenantThemeDirectory = new File(outputFolder);
        if (!tenantThemeDirectory.exists()) {
            if (!tenantThemeDirectory.mkdirs()) {
                APIUtil.handleException("Unable to create tenant theme directory at " + outputFolder);
            }
        } else {
            // copy the existing tenant theme as a backup in case a restoration is needed to take place
            String tempPath = getTenantThemeBackupDirectoryPath(tenantDomain);
            backupDirectory = new File(tempPath);
            FileUtils.copyDirectory(tenantThemeDirectory, backupDirectory);
            // remove existing files inside the directory
            FileUtils.cleanDirectory(tenantThemeDirectory);
        }
        // get the zip file content
        zipInputStream = new ZipInputStream(themeContent);
        // get the zipped file list entry
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            APIUtil.validateFileName(fileName);
            File newFile = new File(outputFolder + File.separator + fileName);
            String canonicalizedNewFilePath = newFile.getCanonicalPath();
            String canonicalizedDestinationPath = new File(outputFolder).getCanonicalPath();
            if (!canonicalizedNewFilePath.startsWith(canonicalizedDestinationPath)) {
                APIUtil.handleException("Attempt to upload invalid zip archive with file at " + fileName + ". File path is " + "outside target directory");
            }
            if (zipEntry.isDirectory()) {
                if (!newFile.exists()) {
                    boolean status = newFile.mkdir();
                    if (!status) {
                        APIUtil.handleException("Error while creating " + newFile.getName() + " directory");
                    }
                }
            } else {
                String ext = FilenameUtils.getExtension(zipEntry.getName());
                if (EXTENSION_WHITELIST.contains(ext)) {
                    // create all non exists folders
                    // else you will hit FileNotFoundException for compressed folder
                    new File(newFile.getParent()).mkdirs();
                    FileOutputStream fileOutputStream = new FileOutputStream(newFile);
                    int len;
                    while ((len = zipInputStream.read(buffer)) > 0) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.close();
                } else {
                    APIUtil.handleException("Unsupported file is uploaded with tenant theme by " + tenantDomain + " : file name : " + zipEntry.getName());
                }
            }
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.closeEntry();
        zipInputStream.close();
        if (backupDirectory != null) {
            FileUtils.deleteDirectory(backupDirectory);
        }
    } catch (APIManagementException | IOException e) {
        // if an error occurs, revert the changes that were done when importing a tenant theme
        revertTenantThemeImportChanges(tenantDomain, existingTenantTheme);
        throw new APIManagementException(e.getMessage(), e, ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, e.getMessage()));
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(themeContent);
        IOUtils.closeQuietly(themeContentInputStream);
    }
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) ZipEntry(java.util.zip.ZipEntry) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

UserStoreException (org.wso2.carbon.user.api.UserStoreException)4 Monetization (org.wso2.carbon.apimgt.api.model.Monetization)3 DefaultMonetizationImpl (org.wso2.carbon.apimgt.impl.monetization.DefaultMonetizationImpl)3 UserStoreManager (org.wso2.carbon.user.api.UserStoreManager)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 ZipEntry (java.util.zip.ZipEntry)1 ZipInputStream (java.util.zip.ZipInputStream)1 APIAdmin (org.wso2.carbon.apimgt.api.APIAdmin)1 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)1 APICategory (org.wso2.carbon.apimgt.api.model.APICategory)1 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)1 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)1 Application (org.wso2.carbon.apimgt.api.model.Application)1 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)1 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)1 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)1