Search in sources :

Example 76 with Label

use of org.wso2.carbon.apimgt.core.models.Label in project carbon-apimgt by wso2.

the class LabelDAOImpl method isLabelsExists.

/**
 * Checks if any labels added to DB and already available
 *
 * @return true if there are any labels available in the system
 * @throws APIMgtDAOException If an error occurs while checking labels existence
 */
private static boolean isLabelsExists(String name, String type) throws APIMgtDAOException {
    final String query = "SELECT * FROM AM_LABELS WHERE NAME=? AND TYPE_NAME=?";
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setString(1, name);
        statement.setString(2, type);
        try (ResultSet rs = statement.executeQuery()) {
            if (rs.next()) {
                return true;
            }
        }
    } catch (SQLException e) {
        String message = "Error while retrieving label [label type] " + type;
        throw new APIMgtDAOException(message, e, ExceptionCodes.LABEL_NOT_FOUND);
    }
    return false;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 77 with Label

use of org.wso2.carbon.apimgt.core.models.Label in project carbon-apimgt by wso2.

the class LabelDAOImpl method addLabel.

/**
 * Add a new label
 *
 * @param label the label to ADD
 * @return {@link Label} a label object with the newly added label ID
 * @throws APIMgtDAOException if error occurs while accessing data layer
 */
public static Label addLabel(Label label) throws APIMgtDAOException {
    final String query = "INSERT INTO AM_LABELS (LABEL_ID, NAME, TYPE_NAME) VALUES (?,?,?)";
    String labelId = null;
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        connection.setAutoCommit(false);
        labelId = UUID.randomUUID().toString();
        statement.setString(1, labelId);
        statement.setString(2, label.getName());
        statement.setString(3, label.getType().toUpperCase(Locale.ENGLISH));
        statement.executeUpdate();
        connection.commit();
        if (!label.getAccessUrls().isEmpty()) {
            insertAccessUrlMappings(labelId, label.getAccessUrls());
        }
        return new Label.Builder().id(labelId).name(label.getName()).description(label.getDescription()).accessUrls(label.getAccessUrls()).type(label.getType()).build();
    } catch (SQLException e) {
        String message = "Error occured while trying to add label " + labelId;
        throw new APIMgtDAOException(message, e, ExceptionCodes.LABEL_ADDING_FAILED);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 78 with Label

use of org.wso2.carbon.apimgt.core.models.Label 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)

Example 79 with Label

use of org.wso2.carbon.apimgt.core.models.Label in project carbon-apimgt by wso2.

the class PostgresSQLStatements 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 Postgress 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 80 with Label

use of org.wso2.carbon.apimgt.core.models.Label in project carbon-apimgt by wso2.

the class APIStateChangeWorkflow method completeWorkflow.

@Override
public WorkflowResponse completeWorkflow(WorkflowExecutor workflowExecutor) throws APIManagementException {
    WorkflowResponse response = workflowExecutor.complete(this);
    setStatus(response.getWorkflowStatus());
    if (WorkflowStatus.APPROVED == response.getWorkflowStatus()) {
        if (log.isDebugEnabled()) {
            log.debug("API state change workflow complete: Approved");
        }
        String invoker = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_LC_INVOKER);
        String currentState = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_CUR_STATE);
        String targetState = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_TARGET_STATE);
        boolean hasOwnGateway = Boolean.valueOf(getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_HAS_OWN_GATEWAY));
        String label = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_AUTOGEN_LABEL);
        if (hasOwnGateway) {
            // (CREATED to DEPRECATED)
            if ((currentState.equalsIgnoreCase(APIStatus.CREATED.getStatus()) || currentState.equalsIgnoreCase(APIStatus.MAINTENANCE.getStatus()) || currentState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus())) && (targetState.equalsIgnoreCase(APIStatus.PUBLISHED.getStatus()) || targetState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus()) || targetState.equalsIgnoreCase(APIStatus.DEPRECATED.getStatus()))) {
                try {
                    // No need to auto-generate the label again As hasOwnGateway is true.
                    // create the gateway
                    API api = apiDAO.getAPI(getWorkflowReference());
                    apiGateway.createContainerBasedGateway(label, api);
                } catch (ContainerBasedGatewayException e) {
                    // Revert already added labels
                    DedicatedGateway dedicatedGateway = new DedicatedGateway();
                    dedicatedGateway.setEnabled(false);
                    dedicatedGateway.setApiId(getWorkflowReference());
                    dedicatedGateway.setUpdatedBy(invoker);
                    List<String> labels = new ArrayList<>();
                    labels.add(labelDAO.getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
                    labels.add(labelDAO.getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
                    apiDAO.updateDedicatedGateway(dedicatedGateway, labels);
                    throw new APIManagementException("Error while updating lifecycle state in Private Jet Mode", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
                }
            }
        }
        String localTime = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_LAST_UPTIME);
        LocalDateTime time = LocalDateTime.parse(localTime);
        updateAPIStatusForWorkflowComplete(getWorkflowReference(), targetState, invoker, time);
        // After publishing the state change to the Gateway, remove the gateway for following occasions.
        if (hasOwnGateway) {
            if ((currentState.equalsIgnoreCase(APIStatus.PUBLISHED.getStatus()) || currentState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus()) || currentState.equalsIgnoreCase(APIStatus.DEPRECATED.getStatus())) && (targetState.equalsIgnoreCase(APIStatus.CREATED.getStatus()) || targetState.equalsIgnoreCase(APIStatus.MAINTENANCE.getStatus()) || targetState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus())) || targetState.equalsIgnoreCase(APIStatus.RETIRED.getStatus())) {
                // remove gateway
                API api = apiDAO.getAPI(getWorkflowReference());
                apiGateway.removeContainerBasedGateway(label, api);
            }
        }
    } else if (WorkflowStatus.REJECTED == response.getWorkflowStatus()) {
        if (log.isDebugEnabled()) {
            log.debug("API state change workflow complete: Rejected");
        }
        apiDAO.updateAPIWorkflowStatus(getWorkflowReference(), APIMgtConstants.APILCWorkflowStatus.REJECTED);
    }
    updateWorkflowEntries(this);
    return response;
}
Also used : LocalDateTime(java.time.LocalDateTime) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) API(org.wso2.carbon.apimgt.core.models.API) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedGateway(org.wso2.carbon.apimgt.core.models.DedicatedGateway)

Aggregations

Label (org.wso2.carbon.apimgt.core.models.Label)65 ArrayList (java.util.ArrayList)52 Test (org.testng.annotations.Test)45 LabelDAO (org.wso2.carbon.apimgt.core.dao.LabelDAO)32 API (org.wso2.carbon.apimgt.core.models.API)29 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)28 SQLException (java.sql.SQLException)21 PreparedStatement (java.sql.PreparedStatement)20 HashMap (java.util.HashMap)16 Connection (java.sql.Connection)15 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)14 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)13 Test (org.junit.Test)12 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)11 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)11 Map (java.util.Map)10 BeforeTest (org.testng.annotations.BeforeTest)9 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)8 Response (javax.ws.rs.core.Response)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8