use of org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException in project carbon-apimgt by wso2.
the class ThrottlingApiServiceImpl method throttlingDenyPoliciesPost.
/**
* Add a Block Condition
*
* @param body DTO of new block condition to be created
* @param contentType Content-Type header
* @return Created block condition along with the location of it with Location header
*/
@Override
public Response throttlingDenyPoliciesPost(String contentType, BlockingConditionDTO body, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// Add the block condition. It will throw BlockConditionAlreadyExistsException if the condition already
// exists in the system
String uuid = null;
if (ConditionTypeEnum.API.equals(body.getConditionType()) || ConditionTypeEnum.APPLICATION.equals(body.getConditionType()) || ConditionTypeEnum.USER.equals(body.getConditionType())) {
uuid = apiProvider.addBlockCondition(body.getConditionType().toString(), (String) body.getConditionValue(), body.isConditionStatus());
} else if (ConditionTypeEnum.IP.equals(body.getConditionType()) || ConditionTypeEnum.IPRANGE.equals(body.getConditionType())) {
if (body.getConditionValue() instanceof Map) {
JSONObject jsonObject = new JSONObject();
jsonObject.putAll((Map) body.getConditionValue());
if (ConditionTypeEnum.IP.equals(body.getConditionType())) {
RestApiAdminUtils.validateIPAddress(jsonObject.get("fixedIp").toString());
}
if (ConditionTypeEnum.IPRANGE.equals(body.getConditionType())) {
RestApiAdminUtils.validateIPAddress(jsonObject.get("startingIp").toString());
RestApiAdminUtils.validateIPAddress(jsonObject.get("endingIp").toString());
}
uuid = apiProvider.addBlockCondition(body.getConditionType().toString(), jsonObject.toJSONString(), body.isConditionStatus());
}
}
// retrieve the new blocking condition and send back as the response
BlockConditionsDTO newBlockingCondition = apiProvider.getBlockConditionByUUID(uuid);
BlockingConditionDTO dto = BlockingConditionMappingUtil.fromBlockingConditionToDTO(newBlockingCondition);
return Response.created(new URI(RestApiConstants.RESOURCE_PATH_THROTTLING_BLOCK_CONDITIONS + "/" + uuid)).entity(dto).build();
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceAlreadyExists(e)) {
RestApiUtil.handleResourceAlreadyExistsError("A black list item with type: " + body.getConditionType() + ", value: " + body.getConditionValue() + " already exists", e, log);
} else {
String errorMessage = "Error while adding Blocking Condition. Condition type: " + body.getConditionType() + ", " + "value: " + body.getConditionValue() + ". " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (URISyntaxException | ParseException e) {
String errorMessage = "Error while retrieving Blocking Condition resource location: Condition type: " + body.getConditionType() + ", " + "value: " + body.getConditionValue() + ". " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException in project carbon-apimgt by wso2.
the class BlacklistApiServiceImpl method blacklistPost.
/**
* Add a blacklist condition.
*
* @param body DTO object including the blacklist condition data
* @param request msf4j request object
* @return Response object
* @throws NotFoundException if an error occurred when particular resource does not exits in the system.
*/
@Override
public Response blacklistPost(BlockingConditionDTO body, Request request) throws NotFoundException {
if (log.isDebugEnabled()) {
log.debug("Received BlockCondition POST request with body: " + body);
}
try {
APIMgtAdminService apiMgtAdminService = RestApiUtil.getAPIMgtAdminService();
// Add the block condition. It will throw BlockConditionAlreadyExistsException if the condition already
// exists in the system
BlockConditions blockConditions = BlockingConditionMappingUtil.fromBlockingConditionDTOToBlockCondition(body);
String uuid = apiMgtAdminService.addBlockCondition(blockConditions);
// retrieve the new blocking condition and send back as the response
BlockConditions newBlockingCondition = apiMgtAdminService.getBlockConditionByUUID(uuid);
BlockingConditionDTO dto = BlockingConditionMappingUtil.fromBlockingConditionToDTO(newBlockingCondition);
return Response.status(Response.Status.CREATED).entity(dto).build();
} catch (APIManagementException e) {
String errorMessage = "Error occurred while adding blocking condition with UUID " + body.getConditionId();
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
}
use of org.wso2.carbon.apimgt.api.BlockConditionAlreadyExistsException in project carbon-apimgt by wso2.
the class ApiMgtDAO method addBlockConditions.
/**
* Add a block condition
*
* @return uuid of the block condition if successfully added
* @throws APIManagementException
*/
public BlockConditionsDTO addBlockConditions(BlockConditionsDTO blockConditionsDTO) throws APIManagementException {
Connection connection = null;
PreparedStatement insertPreparedStatement = null;
boolean status = false;
boolean valid = false;
ResultSet rs = null;
String uuid = blockConditionsDTO.getUUID();
String conditionType = blockConditionsDTO.getConditionType();
String conditionValue = blockConditionsDTO.getConditionValue();
String tenantDomain = blockConditionsDTO.getTenantDomain();
String conditionStatus = String.valueOf(blockConditionsDTO.isEnabled());
try {
String query = SQLConstants.ThrottleSQLConstants.ADD_BLOCK_CONDITIONS_SQL;
if (APIConstants.BLOCKING_CONDITIONS_API.equals(conditionType)) {
String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(conditionValue);
if (extractedTenantDomain == null) {
extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
if (tenantDomain.equals(extractedTenantDomain) && isValidContext(conditionValue)) {
valid = true;
} else {
throw new APIManagementException("Couldn't Save Block Condition Due to Invalid API Context " + conditionValue);
}
} else if (APIConstants.BLOCKING_CONDITIONS_APPLICATION.equals(conditionType)) {
String[] appArray = conditionValue.split(":");
if (appArray.length > 1) {
String appOwner = appArray[0];
String appName = appArray[1];
if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) && isValidApplication(appOwner, appName)) {
valid = true;
} else {
throw new APIManagementException("Couldn't Save Block Condition Due to Invalid Application " + "name " + appName + " from Application " + "Owner " + appOwner);
}
}
} else if (APIConstants.BLOCKING_CONDITIONS_USER.equals(conditionType)) {
if (MultitenantUtils.getTenantDomain(conditionValue).equals(tenantDomain)) {
valid = true;
} else {
throw new APIManagementException("Invalid User in Tenant Domain " + tenantDomain);
}
} else if (APIConstants.BLOCKING_CONDITIONS_IP.equals(conditionType) || APIConstants.BLOCK_CONDITION_IP_RANGE.equals(conditionType)) {
valid = true;
} else if (APIConstants.BLOCKING_CONDITIONS_SUBSCRIPTION.equals(conditionType)) {
/* ATM this condition type will be used internally to handle subscription blockings for JWT type access
tokens.
*/
String[] conditionsArray = conditionValue.split(":");
if (conditionsArray.length > 0) {
String apiContext = conditionsArray[0];
String applicationIdentifier = conditionsArray[2];
String[] app = applicationIdentifier.split("-", 2);
String appOwner = app[0];
String appName = app[1];
// Check whether the given api context exists in tenant
String extractedTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(apiContext);
if (extractedTenantDomain == null) {
extractedTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
if (tenantDomain.equals(extractedTenantDomain) && isValidContext(apiContext)) {
valid = true;
} else {
throw new APIManagementException("Couldn't Save Subscription Block Condition Due to Invalid API Context " + apiContext);
}
// Check whether the given application is valid
if ((MultitenantUtils.getTenantDomain(appOwner).equals(tenantDomain)) && isValidApplication(appOwner, appName)) {
valid = true;
} else {
throw new APIManagementException("Couldn't Save Subscription Block Condition Due to Invalid Application " + "name " + appName + " from Application " + "Owner " + appOwner);
}
} else {
throw new APIManagementException("Invalid subscription block condition with insufficient data : " + conditionValue);
}
}
if (valid) {
connection = APIMgtDBUtil.getConnection();
connection.setAutoCommit(false);
if (!isBlockConditionExist(conditionType, conditionValue, tenantDomain, connection)) {
String dbProductName = connection.getMetaData().getDatabaseProductName();
insertPreparedStatement = connection.prepareStatement(query, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "CONDITION_ID") });
insertPreparedStatement.setString(1, conditionType);
insertPreparedStatement.setString(2, conditionValue);
insertPreparedStatement.setString(3, conditionStatus);
insertPreparedStatement.setString(4, tenantDomain);
insertPreparedStatement.setString(5, uuid);
insertPreparedStatement.execute();
ResultSet generatedKeys = insertPreparedStatement.getGeneratedKeys();
if (generatedKeys != null && generatedKeys.next()) {
blockConditionsDTO.setConditionId(generatedKeys.getInt(1));
}
connection.commit();
status = true;
} else {
throw new BlockConditionAlreadyExistsException("Condition with type: " + conditionType + ", value: " + conditionValue + " already exists");
}
}
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
handleException("Failed to rollback adding Block condition : " + conditionType + " and " + conditionValue, ex);
}
}
handleException("Failed to add Block condition : " + conditionType + " and " + conditionValue, e);
} finally {
APIMgtDBUtil.closeAllConnections(insertPreparedStatement, connection, null);
}
if (status) {
return blockConditionsDTO;
} else {
return null;
}
}
Aggregations