Search in sources :

Example 26 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class MysqlSQLStatements method prepareAttributeSearchStatementForStore.

/**
 * @see ApiDAOVendorSpecificStatements#prepareAttributeSearchStatementForStore(Connection connection, List, List,
 * Map, int, int)
 */
@Override
@SuppressFBWarnings({ "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING", "OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE" })
public PreparedStatement prepareAttributeSearchStatementForStore(Connection connection, List<String> roles, List<String> labels, Map<String, String> attributeMap, int offset, int limit) throws APIMgtDAOException {
    StringBuilder roleListBuilder = new StringBuilder();
    roleListBuilder.append("?");
    for (int i = 0; i < roles.size() - 1; i++) {
        roleListBuilder.append(",?");
    }
    StringBuilder searchQuery = new StringBuilder();
    Iterator<Map.Entry<String, String>> entries = attributeMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        searchQuery.append("LOWER(");
        if (APIMgtConstants.TAG_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.TAG_NAME_COLUMN);
        } else if (APIMgtConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.URL_PATTERN_COLUMN);
        } else {
            searchQuery.append(entry.getKey());
        }
        searchQuery.append(") LIKE ?");
        if (entries.hasNext()) {
            searchQuery.append(" AND ");
        }
    }
    // retrieve the attribute applicable for the search
    String searchAttribute = attributeMap.entrySet().iterator().next().getKey();
    // get the corresponding implementation based on the attribute to be searched
    String query = searchMap.get(searchAttribute).getStoreAttributeSearchQuery(roleListBuilder, searchQuery, offset, limit);
    query = "Select * from ( " + query + " ) A" + getStoreAPIsByLabelJoinQuery(labels);
    try {
        int queryIndex = 1;
        PreparedStatement statement = connection.prepareStatement(query);
        // include the attribute in the query (for APIs with public visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        // include user roles in the query
        for (String role : roles) {
            statement.setString(queryIndex, role);
            queryIndex++;
        }
        // include the attribute in the query (for APIs with restricted visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        for (String label : labels) {
            statement.setString(queryIndex, label);
            queryIndex++;
        }
        // setting 0 as the default offset based on store-api.yaml and MySQL specifications
        statement.setInt(queryIndex, (offset < 0) ? 0 : offset);
        statement.setInt(++queryIndex, limit);
        return statement;
    } catch (SQLException e) {
        String errorMsg = "Error occurred while searching APIs for attributes in the database.";
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 27 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class OracleSQLStatements method prepareAttributeSearchStatementForStore.

/**
 * @see ApiDAOVendorSpecificStatements#prepareAttributeSearchStatementForStore(Connection connection, List, List,
 * Map, int, int)
 */
@Override
@SuppressFBWarnings({ "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING", "OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE" })
public PreparedStatement prepareAttributeSearchStatementForStore(Connection connection, List<String> roles, List<String> labels, Map<String, String> attributeMap, int offset, int limit) throws APIMgtDAOException {
    StringBuilder roleListBuilder = new StringBuilder();
    roleListBuilder.append("?");
    for (int i = 0; i < roles.size() - 1; i++) {
        roleListBuilder.append(",?");
    }
    StringBuilder searchQuery = new StringBuilder();
    Iterator<Map.Entry<String, String>> entries = attributeMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        searchQuery.append("LOWER(");
        if (APIMgtConstants.TAG_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.TAG_NAME_COLUMN);
        } else if (APIMgtConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.URL_PATTERN_COLUMN);
        } else {
            searchQuery.append(entry.getKey());
        }
        searchQuery.append(") LIKE ?");
        if (entries.hasNext()) {
            searchQuery.append(" AND ");
        }
    }
    // retrieve the attribute applicable for the search
    String searchAttribute = attributeMap.entrySet().iterator().next().getKey();
    // get the corresponding implementation based on the attribute to be searched
    String query = searchMap.get(searchAttribute).getStoreAttributeSearchQuery(roleListBuilder, searchQuery, offset, limit);
    query = "SELECT * FROM (SELECT A.*, rownum rnum FROM (Select * from ( " + query + " ) " + getStoreAPIsByLabelJoinQuery(labels) + " ORDER BY NAME) A WHERE rownum <= ?) " + "WHERE rnum >= ?";
    try {
        int queryIndex = 1;
        PreparedStatement statement = connection.prepareStatement(query);
        // include the attribute in the query (for APIs with public visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        // include user roles in the query
        for (String role : roles) {
            statement.setString(queryIndex, role);
            queryIndex++;
        }
        // include the attribute in the query (for APIs with restricted visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        for (String label : labels) {
            statement.setString(queryIndex, label);
            queryIndex++;
        }
        // setting 0 as the default offset based on store-api.yaml and Oracle specifications
        statement.setInt(queryIndex, (offset < 0) ? 0 : offset);
        queryIndex++;
        statement.setInt(queryIndex, limit);
        return statement;
    } catch (SQLException e) {
        String errorMsg = "Error occurred while searching APIs for attributes in the database.";
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 28 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class APIStoreImpl method mapApplicationKeys.

@Override
public OAuthApplicationInfo mapApplicationKeys(String applicationId, String keyType, String clientId, String clientSecret) throws APIManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Semi-manual client registering for App: " + applicationId + " and Client ID: " + clientId);
    }
    if (StringUtils.isEmpty(applicationId) || StringUtils.isEmpty(clientId) || StringUtils.isEmpty(clientSecret)) {
        String msg = "One of input values is null or empty. Application Id: " + applicationId + " Client Id: " + clientId + (StringUtils.isEmpty(clientSecret) ? " Client Secret: " + clientSecret : "");
        log.error(msg);
        throw new APIManagementException(msg, ExceptionCodes.OAUTH2_APP_MAP_FAILED);
    }
    // Checking whether given consumer key and secret match with an existing OAuth app.
    // If they does not match, throw an exception.
    OAuthApplicationInfo oAuthApp = getKeyManager().retrieveApplication(clientId);
    if (oAuthApp == null || !clientSecret.equals(oAuthApp.getClientSecret())) {
        String msg = "Unable to find OAuth app. The provided Client Id is invalid. Client Id: " + clientId;
        throw new APIManagementException(msg, ExceptionCodes.OAUTH2_APP_MAP_FAILED);
    }
    try {
        getApplicationDAO().addApplicationKeys(applicationId, keyType, clientId);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while saving key data.";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
    log.debug("Application keys are successfully saved in the database");
    List<SubscriptionValidationData> subscriptionValidationData = getApiSubscriptionDAO().getAPISubscriptionsOfAppForValidation(applicationId, keyType);
    if (subscriptionValidationData != null && !subscriptionValidationData.isEmpty()) {
        getApiGateway().addAPISubscription(subscriptionValidationData);
    }
    if (log.isDebugEnabled()) {
        log.debug("Semi-manual client registration was successful for application: " + applicationId + " and Client ID: " + clientId);
    }
    return oAuthApp;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) SubscriptionValidationData(org.wso2.carbon.apimgt.core.models.SubscriptionValidationData)

Example 29 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class ApiStoreSdkGenerationManager method generateSdkForApi.

/*
        * This method generates the client side SDK for the API with API ID (apiID) and SDK language (language)
        *
        * @param apiId ID for the specific API
        * @param language preferred language to generate the SDK
        * @throws ApiStoreSdkGenerationException if failed to generate the SDK
        * */
public String generateSdkForApi(String apiId, String language, String userName) throws ApiStoreSdkGenerationException, APIManagementException {
    APIStore apiStore = APIManagerFactory.getInstance().getAPIConsumer(userName);
    API api = apiStore.getAPIbyUUID(apiId);
    if (api == null) {
        String errorMessage = "Cannot find API for specified API ID";
        throw new APIManagementException(errorMessage, ExceptionCodes.API_NOT_FOUND);
    }
    String apiName = api.getName();
    String apiVersion = api.getVersion();
    String swaggerDefinitionForApi = null;
    try {
        swaggerDefinitionForApi = apiStore.getApiSwaggerDefinition(apiId);
    } catch (APIManagementException e) {
        handleSdkGenException("Error retrieving swagger definition for API " + apiId + " from database.", e);
    }
    Swagger swaggerDoc = new SwaggerParser().parse(swaggerDefinitionForApi);
    if (swaggerDoc == null) {
        handleSdkGenException("Error while parsing retrieved swagger definition");
    }
    // Format the swagger definition as a string before writing to the file.
    String formattedSwaggerDefinitionForSdk = Json.pretty(swaggerDoc);
    Path tempSdkGenDir = null;
    File swaggerDefJsonFile = null;
    try {
        // Create a temporary directory to store the API files
        tempSdkGenDir = Files.createTempDirectory(apiName + "_" + language + "_" + apiVersion);
        // Create a temporary file to store the swagger definition
        swaggerDefJsonFile = Files.createTempFile(tempSdkGenDir, apiId + "_" + language, APIMgtConstants.APIFileUtilConstants.JSON_EXTENSION).toFile();
    } catch (IOException e) {
        handleSdkGenException("Error creating temporary directory or json file for swagger definition!", e);
    }
    String tempZipFilePath = "";
    if (swaggerDefJsonFile.exists()) {
        try (Writer swaggerFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(swaggerDefJsonFile.getAbsoluteFile()), "UTF-8"))) {
            swaggerFileWriter.write(formattedSwaggerDefinitionForSdk);
            log.debug("Writing the swagger definition was sucessful to file {}", swaggerDefJsonFile.getAbsolutePath());
        } catch (IOException e) {
            handleSdkGenException("Error writing swagger definition to file in " + tempSdkGenDir, e);
        }
        // Generate the SDK for the specified language
        generateSdkForSwaggerDef(language, swaggerDefJsonFile.getAbsolutePath(), tempSdkGenDir.toString());
        log.debug("Generating SDK for the swagger definition {} was successful.", swaggerDefJsonFile.getAbsolutePath());
        String archiveName = apiName + "_" + language + "_" + apiVersion;
        tempZipFilePath = tempSdkGenDir + File.separator + archiveName + ".zip";
        APIFileUtils.archiveDirectory(tempSdkGenDir.toString(), tempSdkGenDir.toString(), archiveName);
        log.debug("Generating the archive was successful for directory {}.", tempSdkGenDir.toString());
    } else {
        handleSdkGenException("Swagger definition file not found!");
    }
    try {
        // Set deleteOnExit property to generated SDK directory, all sub directories and files.
        recursiveDeleteOnExit(tempSdkGenDir);
    } catch (IOException e) {
        handleSdkGenException("Error while deleting temporary directory " + tempSdkGenDir, e);
    }
    return tempZipFilePath;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) SwaggerParser(io.swagger.parser.SwaggerParser) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Swagger(io.swagger.models.Swagger) FileOutputStream(java.io.FileOutputStream) API(org.wso2.carbon.apimgt.core.models.API) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 30 with Database

use of org.wso2.carbon.humantask.core.db.Database in project carbon-apimgt by wso2.

the class H2SQLStatements method prepareAttributeSearchStatementForStore.

/**
 * @see ApiDAOVendorSpecificStatements#prepareAttributeSearchStatementForStore(Connection connection, List, List,
 * Map, int, int)
 */
@Override
@SuppressFBWarnings({ "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING", "OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE" })
public PreparedStatement prepareAttributeSearchStatementForStore(Connection connection, List<String> roles, List<String> labels, Map<String, String> attributeMap, int offset, int limit) throws APIMgtDAOException {
    StringBuilder roleListBuilder = new StringBuilder();
    roleListBuilder.append("?");
    for (int i = 0; i < roles.size() - 1; i++) {
        roleListBuilder.append(",?");
    }
    StringBuilder searchQuery = new StringBuilder();
    Iterator<Map.Entry<String, String>> entries = attributeMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        searchQuery.append("LOWER(");
        if (APIMgtConstants.TAG_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.TAG_NAME_COLUMN);
        } else if (APIMgtConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.URL_PATTERN_COLUMN);
        } else {
            searchQuery.append(entry.getKey());
        }
        searchQuery.append(") LIKE ?");
        if (entries.hasNext()) {
            searchQuery.append(" AND ");
        }
    }
    // retrieve the attribute applicable for the search
    String searchAttribute = attributeMap.entrySet().iterator().next().getKey();
    // get the corresponding implementation based on the attribute to be searched
    String query = searchMap.get(searchAttribute).getStoreAttributeSearchQuery(roleListBuilder, searchQuery, offset, limit);
    query = "Select * from ( " + query + " ) " + getStoreAPIsByLabelJoinQuery(labels);
    try {
        int queryIndex = 1;
        PreparedStatement statement = connection.prepareStatement(query);
        // include the attribute in the query (for APIs with public visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        // include user roles in the query
        for (String role : roles) {
            statement.setString(queryIndex, role);
            queryIndex++;
        }
        // include the attribute in the query (for APIs with restricted visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        for (String label : labels) {
            statement.setString(queryIndex, label);
            queryIndex++;
        }
        // setting 0 as the default offset based on store-api.yaml and H2 specifications
        statement.setInt(queryIndex, (offset < 0) ? 0 : offset);
        statement.setInt(++queryIndex, limit);
        return statement;
    } catch (SQLException e) {
        String errorMsg = "Error occurred while searching APIs for attributes in the database.";
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

SQLException (java.sql.SQLException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)24 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)23 ResultSet (java.sql.ResultSet)16 ArrayList (java.util.ArrayList)13 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)12 Map (java.util.Map)6 DeviceMgtPluginException (org.wso2.iot.sampledevice.plugin.exception.DeviceMgtPluginException)6 HashMap (java.util.HashMap)5 BpelDatabase (org.apache.ode.bpel.engine.BpelDatabase)5 File (java.io.File)4 InstanceFilter (org.apache.ode.bpel.common.InstanceFilter)4 BpelDAOConnection (org.apache.ode.bpel.dao.BpelDAOConnection)4 InstanceManagementException (org.wso2.carbon.bpel.skeleton.ode.integration.mgt.services.InstanceManagementException)4 Device (org.wso2.carbon.device.mgt.common.Device)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3 DataSource (javax.sql.DataSource)3 ProcessInstanceDAO (org.apache.ode.bpel.dao.ProcessInstanceDAO)3