use of org.wso2.carbon.identity.jaxrs.designator.PATCH in project carbon-apimgt by wso2.
the class PersistenceHelper method getSampleAPIArtifactForTenant.
public static GenericArtifact getSampleAPIArtifactForTenant() throws GovernanceException {
GenericArtifact artifact = new GenericArtifactImpl(new QName("", "PizzaShackAPI", ""), "application/vnd.wso2-api+xml");
artifact.setAttribute("overview_endpointSecured", "false");
artifact.setAttribute("overview_transports", "http,https");
artifact.setAttribute("URITemplate_authType3", "Application & Application User");
artifact.setAttribute("overview_wadl", null);
artifact.setAttribute("URITemplate_authType4", "Application & Application User");
artifact.setAttribute("overview_authorizationHeader", "Authorization");
artifact.setAttribute("URITemplate_authType1", "Application & Application User");
artifact.setAttribute("overview_visibleTenants", null);
artifact.setAttribute("URITemplate_authType2", "Application & Application User");
artifact.setAttribute("overview_wsdl", null);
artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory");
artifact.setAttribute("URITemplate_authType0", "Application & Application User");
artifact.setAttribute("overview_keyManagers", "[\"all\"]");
artifact.setAttribute("overview_environments", "Default");
artifact.setAttribute("overview_context", "/t/wso2.com/pizzashack/1.0.0");
artifact.setAttribute("overview_visibility", "restricted");
artifact.setAttribute("overview_isLatest", "true");
artifact.setAttribute("overview_outSequence", "log_out_message");
artifact.setAttribute("overview_provider", "admin-AT-wso2.com");
artifact.setAttribute("apiCategories_categoryName", "testcategory");
artifact.setAttribute("overview_thumbnail", "/t/wso2.com/t/wso2.com/registry/resource/_system/governance/apimgt/applicationdata/provider/admin-AT-wso2.com/PizzaShackAPI/1.0.0/icon");
artifact.setAttribute("overview_contextTemplate", "/t/wso2.com/pizzashack/{version}");
artifact.setAttribute("overview_description", "This is a simple API for Pizza Shack online pizza delivery store.");
artifact.setAttribute("overview_technicalOwner", "John Doe");
artifact.setAttribute("overview_type", "HTTP");
artifact.setAttribute("overview_technicalOwnerEmail", "architecture@pizzashack.com");
artifact.setAttribute("URITemplate_httpVerb4", "DELETE");
artifact.setAttribute("overview_inSequence", "log_in_message");
artifact.setAttribute("URITemplate_httpVerb2", "GET");
artifact.setAttribute("URITemplate_httpVerb3", "PUT");
artifact.setAttribute("URITemplate_httpVerb0", "POST");
artifact.setAttribute("URITemplate_httpVerb1", "GET");
artifact.setAttribute("labels_labelName", "gwlable");
artifact.setAttribute("overview_businessOwner", "Jane Roe");
artifact.setAttribute("overview_version", "1.0.0");
artifact.setAttribute("overview_endpointConfig", "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}," + "\"endpoint_security\":{\"production\":{\"password\":\"admin\",\"tokenUrl\":null,\"clientId\":null," + "\"clientSecret\":null,\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":\"BASIC\"," + "\"grantType\":null,\"enabled\":true,\"uniqueIdentifier\":null,\"username\":\"admin\"}," + "\"sandbox\":{\"password\":null,\"tokenUrl\":null,\"clientId\":null,\"clientSecret\":null," + "\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":null,\"grantType\":null,\"enabled\":false," + "\"uniqueIdentifier\":null,\"username\":null}},\"production_endpoints\":" + "{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}}");
artifact.setAttribute("overview_tier", "Bronze||Silver||Gold||Unlimited");
artifact.setAttribute("overview_sandboxTps", "1000");
artifact.setAttribute("overview_apiOwner", "admin@wso2.com");
artifact.setAttribute("overview_businessOwnerEmail", "marketing@pizzashack.com");
artifact.setAttribute("isMonetizationEnabled", "false");
artifact.setAttribute("overview_implementation", "ENDPOINT");
artifact.setAttribute("overview_deployments", "null");
artifact.setAttribute("overview_redirectURL", null);
artifact.setAttribute("monetizationProperties", "{}");
artifact.setAttribute("overview_name", "PizzaShackAPI");
artifact.setAttribute("overview_subscriptionAvailability", "current_tenant");
artifact.setAttribute("overview_productionTps", "1000");
artifact.setAttribute("overview_cacheTimeout", "300");
artifact.setAttribute("overview_visibleRoles", "admin,internal/subscriber");
artifact.setAttribute("overview_testKey", null);
artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":true,\"accessControlAllowOrigins\":[\"*\"]," + "\"accessControlAllowCredentials\":false,\"accessControlAllowHeaders\":[\"authorization\"," + "\"Access-Control-Allow-Origin\",\"Content-Type\",\"SOAPAction\",\"apikey\",\"testKey\"]," + "\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
artifact.setAttribute("overview_advertiseOnly", "false");
artifact.setAttribute("overview_versionType", "context");
artifact.setAttribute("overview_status", "PUBLISHED");
artifact.setAttribute("overview_endpointPpassword", null);
artifact.setAttribute("overview_tenants", null);
artifact.setAttribute("overview_endpointAuthDigest", "false");
artifact.setAttribute("overview_faultSequence", "json_fault");
artifact.setAttribute("overview_responseCaching", "Enabled");
artifact.setAttribute("URITemplate_urlPattern4", "/order/{orderId}");
artifact.setAttribute("overview_isDefaultVersion", "true");
artifact.setAttribute("URITemplate_urlPattern2", "/order/{orderId}");
artifact.setAttribute("URITemplate_urlPattern3", "/order/{orderId}");
artifact.setAttribute("URITemplate_urlPattern0", "/order");
artifact.setAttribute("URITemplate_urlPattern1", "/menu");
artifact.setAttribute("overview_enableStore", "true");
artifact.setAttribute("overview_enableSchemaValidation", "true");
artifact.setAttribute("overview_endpointUsername", null);
artifact.setAttribute("overview_status", "PUBLISHED");
artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
return artifact;
}
use of org.wso2.carbon.identity.jaxrs.designator.PATCH in project carbon-apimgt by wso2.
the class PersistenceHelper method getSampleAPIProductArtifact.
public static GenericArtifact getSampleAPIProductArtifact() throws GovernanceException {
GenericArtifact artifact = new GenericArtifactImpl(new QName("", "APIProductTest", ""), "application/vnd.wso2-api+xml");
artifact.setAttribute("overview_transports", "http,https");
artifact.setAttribute("monetizationProperties", "{}");
artifact.setAttribute("overview_authorizationHeader", "Authorization");
artifact.setAttribute("overview_visibleTenants", null);
artifact.setAttribute("overview_name", "APIProductTest");
artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory,basic_auth,api_key");
artifact.setAttribute("overview_environments", "Default");
artifact.setAttribute("overview_subscriptionAvailability", "all_tenants");
artifact.setAttribute("overview_context", "/prodcontext");
artifact.setAttribute("overview_visibility", "restricted");
artifact.setAttribute("overview_cacheTimeout", "300");
artifact.setAttribute("overview_provider", "admin");
artifact.setAttribute("overview_visibleRoles", "admin");
artifact.setAttribute("apiCategories_categoryName", "testcategory");
artifact.setAttribute("overview_contextTemplate", "/prodcontext/{version}");
artifact.setAttribute("overview_thumbnail", null);
artifact.setAttribute("overview_description", "sample product");
artifact.setAttribute("overview_technicalOwner", null);
artifact.setAttribute("overview_type", "APIProduct");
artifact.setAttribute("overview_technicalOwnerEmail", null);
artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":false," + "\"accessControlAllowOrigins\":[\"*\"],\"accessControlAllowCredentials\":false," + "\"accessControlAllowHeaders\":[\"authorization\",\"Access-Control-Allow-Origin\",\"Content-Type\"," + "\"SOAPAction\",\"apikey\",\"testKey\"],\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\"," + "\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
artifact.setAttribute("overview_versionType", "context");
artifact.setAttribute("overview_status", "PUBLISHED");
artifact.setAttribute("overview_businessOwner", "productOwner");
artifact.setAttribute("overview_version", "1.0.0");
artifact.setAttribute("overview_tenants", null);
artifact.setAttribute("overview_responseCaching", "Disabled");
artifact.setAttribute("overview_tier", "Bronze||Gold");
artifact.setAttribute("overview_businessOwnerEmail", "owner@test.com");
artifact.setAttribute("isMonetizationEnabled", "false");
artifact.setAttribute("overview_enableStore", "true");
artifact.setAttribute("overview_enableSchemaValidation", "false");
artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
return artifact;
}
use of org.wso2.carbon.identity.jaxrs.designator.PATCH in project carbon-apimgt by wso2.
the class APIProviderImpl method updateApiArtifact.
private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
// Validate Transports
validateAndSetTransports(api);
validateAndSetAPISecurity(api);
boolean transactionCommitted = false;
String apiUUID = null;
try {
registry.beginTransaction();
String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
Resource apiResource = registry.get(artifact.getPath());
String oldAccessControlRoles = api.getAccessControlRoles();
if (apiResource != null) {
oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
}
GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
if (oldTags != null) {
for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
registry.removeTag(artifactPath, tag.getTagName());
}
}
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
// If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
// will skip registry update. Only if this API created with WSDL end point type we need to update
// wsdls for each update.
// check for wsdl endpoint
org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
String wsdlURL;
if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
String path = APIUtil.createWSDL(registry, api);
if (path != null) {
// reset the wsdl path to permlink
updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
}
}
}
}
artifactManager.updateGenericArtifact(updateApiArtifact);
// write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
// to gain performance
String apiStatus = api.getStatus().toUpperCase();
saveAPIStatus(artifactPath, apiStatus);
String[] visibleRoles = new String[0];
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
// propagate api status change and access control roles change to document artifact
String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
}
if (updatePermissions) {
APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
String visibleRolesList = api.getVisibleRoles();
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
}
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
registry.commitTransaction();
transactionCommitted = true;
apiUUID = updateApiArtifact.getId();
if (updatePermissions) {
APIManagerConfiguration config = getAPIManagerConfiguration();
boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
String docRootPath = APIUtil.getAPIDocPath(api.getId());
if (isSetDocLevelPermissions) {
// Retain the docs
List<Documentation> docs = getAllDocumentation(api.getId());
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
} else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
}
}
}
} else {
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
}
} else {
// In order to support content search feature - we need to update resource permissions of document resources
// if their visibility is set to API level.
List<Documentation> docs = getAllDocumentation(api.getId());
if (docs != null) {
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
}
}
}
}
} catch (Exception e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error from this level will mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
handleException("Error while performing registry transaction operation", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
handleException("Error occurred while rolling back the transaction.", ex);
}
}
return apiUUID;
}
use of org.wso2.carbon.identity.jaxrs.designator.PATCH in project carbon-apimgt by wso2.
the class APIKeyValidator method getVerbInfoDTOFromAPIData.
/**
* @param messageContext The message context
* @param context API context of API
* @param apiVersion Version of API
* @param requestPath Incoming request path
* @param httpMethod http method of request
* @return verbInfoDTO which contains throttling tier for given resource and verb+resource key
*/
public VerbInfoDTO getVerbInfoDTOFromAPIData(MessageContext messageContext, String context, String apiVersion, String requestPath, String httpMethod) throws APISecurityException {
String cacheKey = context + ':' + apiVersion;
APIInfoDTO apiInfoDTO = null;
if (isGatewayAPIResourceValidationEnabled) {
apiInfoDTO = (APIInfoDTO) getResourceCache().get(cacheKey);
}
if (apiInfoDTO == null) {
apiInfoDTO = doGetAPIInfo(messageContext, context, apiVersion);
if (isGatewayAPIResourceValidationEnabled) {
getResourceCache().put(cacheKey, apiInfoDTO);
}
}
// Match the case where the direct api context is matched
if ("/".equals(requestPath)) {
String requestCacheKey = context + '/' + apiVersion + requestPath + ':' + httpMethod;
// Get decision from cache.
VerbInfoDTO matchingVerb = null;
if (isGatewayAPIResourceValidationEnabled) {
matchingVerb = (VerbInfoDTO) getResourceCache().get(requestCacheKey);
}
// On a cache hit
if (matchingVerb != null) {
matchingVerb.setRequestKey(requestCacheKey);
return matchingVerb;
} else {
if (apiInfoDTO.getResources() != null) {
for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
String urlPattern = resourceInfoDTO.getUrlPattern();
// If the request patch is '/', it can only be matched with a resource whose url-context is '/*'
if ("/*".equals(urlPattern)) {
for (VerbInfoDTO verbDTO : resourceInfoDTO.getHttpVerbs()) {
if (verbDTO.getHttpVerb().equals(httpMethod)) {
// Store verb in cache
if (isGatewayAPIResourceValidationEnabled) {
getResourceCache().put(requestCacheKey, verbDTO);
}
verbDTO.setRequestKey(requestCacheKey);
return verbDTO;
}
}
}
}
}
}
}
// Remove the ending '/' from request
requestPath = RESTUtils.trimTrailingSlashes(requestPath);
while (requestPath.length() > 1) {
String requestCacheKey = context + '/' + apiVersion + requestPath + ':' + httpMethod;
// Get decision from cache.
VerbInfoDTO matchingVerb = null;
if (isGatewayAPIResourceValidationEnabled) {
matchingVerb = (VerbInfoDTO) getResourceCache().get(requestCacheKey);
}
// On a cache hit
if (matchingVerb != null) {
matchingVerb.setRequestKey(requestCacheKey);
return matchingVerb;
} else // On a cache miss
{
for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
String urlPattern = resourceInfoDTO.getUrlPattern();
if (urlPattern.endsWith("/*")) {
// Remove the ending '/*'
urlPattern = urlPattern.substring(0, urlPattern.length() - 2);
}
// If the urlPattern ends with a '/', remove that as well.
urlPattern = RESTUtils.trimTrailingSlashes(urlPattern);
if (requestPath.endsWith(urlPattern)) {
for (VerbInfoDTO verbDTO : resourceInfoDTO.getHttpVerbs()) {
if (verbDTO.getHttpVerb().equals(httpMethod)) {
// Store verb in cache
if (isGatewayAPIResourceValidationEnabled) {
getResourceCache().put(requestCacheKey, verbDTO);
}
verbDTO.setRequestKey(requestCacheKey);
return verbDTO;
}
}
}
}
}
// Remove the section after the last occurrence of the '/' character
int index = requestPath.lastIndexOf('/');
requestPath = requestPath.substring(0, index <= 0 ? 0 : index);
}
// nothing found. return the highest level of security
return null;
}
use of org.wso2.carbon.identity.jaxrs.designator.PATCH in project carbon-apimgt by wso2.
the class SolaceAdminApis method applicationPatchAddSubscription.
/**
* Add subscriptions to application in Solace and update the application
*
* @param organization name of the Organization
* @param application Application to be checked in solace
* @param apiProducts API products to add as subscriptions
* @return CloseableHttpResponse of the PATCH call
*/
public CloseableHttpResponse applicationPatchAddSubscription(String organization, Application application, ArrayList<String> apiProducts) {
URL serviceEndpointURL = new URL(baseUrl);
HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
HttpPatch httpPatch = new HttpPatch(baseUrl + "/" + organization + "/developers/" + developerUserName + "/apps/" + application.getUUID());
httpPatch.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedCredentials());
httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
// retrieve existing API products in the app
try {
apiProducts = retrieveApiProductsInAnApplication(applicationGet(organization, application.getUUID(), "default"), apiProducts);
} catch (IOException e) {
log.error(e.getMessage());
}
org.json.JSONObject requestBody = buildRequestBodyForApplicationPatchSubscriptions(apiProducts);
StringEntity params = null;
try {
params = new StringEntity(requestBody.toString());
httpPatch.setEntity(params);
return APIUtil.executeHTTPRequest(httpPatch, httpClient);
} catch (IOException | APIManagementException e) {
log.error(e.getMessage());
}
return null;
}
Aggregations