use of org.wso2.carbon.apimgt.persistence.dto.ResourceFile in project carbon-apimgt by wso2.
the class APIProviderImplTest method testAddFileToDocumentation.
/**
* This method tests adding file to documentation method.
* @throws Exception
*
* @throws GovernanceException Governance Exception.
*/
@Test
public void testAddFileToDocumentation() throws Exception {
String apiUUID = "xxxxxxxx";
String docUUID = "yyyyyyyy";
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
Tier tier = new Tier("Gold");
Map<String, Tier> tiers = new TreeMap<>();
tiers.put("Gold", tier);
URITemplate uriTemplate1 = new URITemplate();
uriTemplate1.setHTTPVerb("POST");
uriTemplate1.setAuthType("Application");
uriTemplate1.setUriTemplate("/add");
uriTemplate1.setThrottlingTier("Gold");
uriTemplates.add(uriTemplate1);
final API api = new API(identifier);
api.setStatus(APIConstants.CREATED);
api.setVisibility("public");
api.setAccessControl("all");
api.setTransports("http,https");
api.setContext("/test");
api.setEnvironments(environments);
api.setUriTemplates(uriTemplates);
api.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
apiProvider.addAPI(api);
String fileName = "test.txt";
String contentType = "application/force-download";
Documentation doc = new Documentation(DocumentationType.HOWTO, fileName);
doc.setSourceType(DocumentSourceType.FILE);
PowerMockito.when(APIUtil.getDocumentationFilePath(api.getId(), fileName)).thenReturn("filePath");
InputStream inputStream = Mockito.mock(InputStream.class);
// apiProvider.addFileToDocumentation(api.getId(), doc, fileName, inputStream, contentType);
DocumentationContent content = new DocumentationContent();
ResourceFile resourceFile = new ResourceFile(inputStream, contentType);
content.setResourceFile(resourceFile);
apiProvider.addDocumentationContent(apiUUID, docUUID, "carbon.super", content);
}
use of org.wso2.carbon.apimgt.persistence.dto.ResourceFile in project carbon-apimgt by wso2.
the class APIProviderImpl method copySequencesToNewVersion.
private void copySequencesToNewVersion(API api, String newVersion, String pathFlow) throws Exception {
String seqFilePath = APIUtil.getSequencePath(api.getId(), pathFlow);
if (registry.resourceExists(seqFilePath)) {
APIIdentifier newApiId = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(), newVersion);
String seqNewFilePath = APIUtil.getSequencePath(newApiId, pathFlow);
org.wso2.carbon.registry.api.Collection seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(seqFilePath);
if (seqCollection != null) {
String[] seqChildPaths = seqCollection.getChildren();
for (String seqChildPath : seqChildPaths) {
Resource sequence = registry.get(seqChildPath);
ResourceFile seqFile = new ResourceFile(sequence.getContentStream(), sequence.getMediaType());
OMElement seqElement = APIUtil.buildOMElement(sequence.getContentStream());
String seqFileName = seqElement.getAttributeValue(new QName("name"));
addResourceFile(api.getId(), seqNewFilePath + seqFileName, seqFile);
}
}
}
}
use of org.wso2.carbon.apimgt.persistence.dto.ResourceFile in project carbon-apimgt by wso2.
the class APIProviderImpl method createNewAPIVersion.
public API createNewAPIVersion(String existingApiId, String newVersion, Boolean isDefaultVersion, String organization) throws APIManagementException {
API existingAPI = getAPIbyUUID(existingApiId, organization);
if (existingAPI == null) {
throw new APIMgtResourceNotFoundException("API not found for id " + existingApiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, existingApiId));
}
if (newVersion.equals(existingAPI.getId().getVersion())) {
throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName());
}
existingAPI.setOrganization(organization);
APIIdentifier existingAPIId = existingAPI.getId();
String existingAPICreatedTime = existingAPI.getCreatedTime();
String existingAPIStatus = existingAPI.getStatus();
boolean isExsitingAPIdefaultVersion = existingAPI.isDefaultVersion();
String existingContext = existingAPI.getContext();
String existingVersionTimestamp = existingAPI.getVersionTimestamp();
APIIdentifier newApiId = new APIIdentifier(existingAPI.getId().getProviderName(), existingAPI.getId().getApiName(), newVersion);
existingAPI.setUuid(null);
existingAPI.setId(newApiId);
existingAPI.setStatus(APIConstants.CREATED);
existingAPI.setDefaultVersion(isDefaultVersion);
existingAPI.setVersionTimestamp("");
// We need to change the context by setting the new version
// This is a change that is coming with the context version strategy
String existingAPIContextTemplate = existingAPI.getContextTemplate();
existingAPI.setContext(existingAPIContextTemplate.replace("{version}", newVersion));
Map<String, List<OperationPolicy>> operationPoliciesMap = extractAndDropOperationPoliciesFromURITemplate(existingAPI.getUriTemplates());
API newAPI = addAPI(existingAPI);
String newAPIId = newAPI.getUuid();
if (!operationPoliciesMap.isEmpty()) {
// clone common or API specific operation policy.
Map<String, String> clonedOperationPolicyMap = cloneOperationPoliciesToAPI(existingApiId, newAPI, operationPoliciesMap);
// attach policy to uri template.
attachOperationPoliciesToAPI(newAPI, clonedOperationPolicyMap, operationPoliciesMap);
}
// copy docs
List<Documentation> existingDocs = getAllDocumentation(existingApiId, organization);
if (existingDocs != null) {
for (Documentation documentation : existingDocs) {
Documentation newDoc = addDocumentation(newAPIId, documentation, organization);
DocumentationContent content = getDocumentationContent(existingApiId, documentation.getId(), // TODO see whether we can optimize this
organization);
if (content != null) {
addDocumentationContent(newAPIId, newDoc.getId(), organization, content);
}
}
}
// copy icon
ResourceFile icon = getIcon(existingApiId, organization);
if (icon != null) {
setThumbnailToAPI(newAPIId, icon, organization);
}
// copy sequences
List<Mediation> mediationPolicies = getAllApiSpecificMediationPolicies(existingApiId, organization);
if (mediationPolicies != null) {
for (Mediation mediation : mediationPolicies) {
Mediation policy = getApiSpecificMediationPolicyByPolicyId(existingApiId, mediation.getUuid(), organization);
addApiSpecificMediationPolicy(newAPIId, policy, organization);
}
}
// copy wsdl
if (!APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType()) && existingAPI.getWsdlUrl() != null) {
ResourceFile wsdl = getWSDL(existingApiId, organization);
if (wsdl != null) {
addWSDLResource(newAPIId, wsdl, null, organization);
}
}
// copy graphql definition
String graphQLSchema = getGraphqlSchemaDefinition(existingApiId, organization);
if (graphQLSchema != null) {
saveGraphqlSchemaDefinition(newAPIId, graphQLSchema, organization);
}
// update old api
// revert back to old values before update.
existingAPI.setUuid(existingApiId);
existingAPI.setStatus(existingAPIStatus);
existingAPI.setId(existingAPIId);
existingAPI.setContext(existingContext);
existingAPI.setCreatedTime(existingAPICreatedTime);
// update existing api with the original timestamp
existingAPI.setVersionTimestamp(existingVersionTimestamp);
if (isDefaultVersion) {
existingAPI.setDefaultVersion(false);
} else {
existingAPI.setDefaultVersion(isExsitingAPIdefaultVersion);
}
try {
apiPersistenceInstance.updateAPI(new Organization(organization), APIMapper.INSTANCE.toPublisherApi(existingAPI));
} catch (APIPersistenceException e) {
throw new APIManagementException("Error while updating API details", e);
}
return getAPIbyUUID(newAPIId, organization);
}
use of org.wso2.carbon.apimgt.persistence.dto.ResourceFile in project carbon-apimgt by wso2.
the class APIUtil method saveWSDLResource.
/**
* Save the provided wsdl archive file to the registry for the api
*
* @param registry Governance Registry space to save the WSDL
* @param api API instance
* @return
* @throws RegistryException
* @throws APIManagementException
*/
public static String saveWSDLResource(Registry registry, API api) throws RegistryException, APIManagementException {
ResourceFile wsdlResource = api.getWsdlResource();
String wsdlResourcePath;
boolean isZip = false;
APIIdentifier apiId = api.getId();
String apiPath = APIUtil.getAPIPath(apiId);
int prependIndex = apiPath.indexOf(apiId.getVersion()) + apiId.getVersion().length();
String apiSourcePath = apiPath.substring(0, prependIndex);
String wsdlResourcePathArchive = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_WSDL_ARCHIVE_LOCATION + api.getId().getProviderName() + APIConstants.WSDL_PROVIDER_SEPERATOR + api.getId().getApiName() + api.getId().getVersion() + APIConstants.ZIP_FILE_EXTENSION;
String wsdlResourcePathFile = apiSourcePath + RegistryConstants.PATH_SEPARATOR + createWsdlFileName(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion());
if (wsdlResource.getContentType().equals(APIConstants.APPLICATION_ZIP)) {
wsdlResourcePath = wsdlResourcePathArchive;
isZip = true;
} else {
wsdlResourcePath = wsdlResourcePathFile;
}
String absoluteWSDLResourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + wsdlResourcePath;
try {
Resource wsdlResourceToUpdate = registry.newResource();
wsdlResourceToUpdate.setContentStream(api.getWsdlResource().getContent());
wsdlResourceToUpdate.setMediaType(api.getWsdlResource().getContentType());
registry.put(wsdlResourcePath, wsdlResourceToUpdate);
String[] visibleRoles = null;
if (api.getVisibleRoles() != null) {
visibleRoles = api.getVisibleRoles().split(",");
}
setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, wsdlResourcePath);
if (isZip) {
// Delete any WSDL file if exists
if (registry.resourceExists(wsdlResourcePathFile)) {
registry.delete(wsdlResourcePathFile);
}
} else {
// Delete any WSDL archives if exists
if (registry.resourceExists(wsdlResourcePathArchive)) {
registry.delete(wsdlResourcePathArchive);
}
}
api.setWsdlUrl(getRegistryResourceHTTPPermlink(absoluteWSDLResourcePath));
} catch (RegistryException e) {
String msg = "Failed to add WSDL Archive " + api.getWsdlUrl() + " to the registry";
log.error(msg, e);
throw new RegistryException(msg, e);
} catch (APIManagementException e) {
String msg = "Failed to process the WSDL Archive: " + api.getWsdlUrl();
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return wsdlResourcePath;
}
use of org.wso2.carbon.apimgt.persistence.dto.ResourceFile in project carbon-apimgt by wso2.
the class APIConsumerImpl method getWSDL.
@Override
public ResourceFile getWSDL(API api, String environmentName, String environmentType, String organization) throws APIManagementException {
WSDLValidationResponse validationResponse;
ResourceFile resourceFile = getWSDL(api.getUuid(), organization);
if (resourceFile.getContentType().contains(APIConstants.APPLICATION_ZIP)) {
validationResponse = APIMWSDLReader.extractAndValidateWSDLArchive(resourceFile.getContent());
} else {
validationResponse = APIMWSDLReader.validateWSDLFile(resourceFile.getContent());
}
if (validationResponse.isValid()) {
WSDLProcessor wsdlProcessor = validationResponse.getWsdlProcessor();
wsdlProcessor.updateEndpoints(api, environmentName, environmentType);
InputStream wsdlDataStream = wsdlProcessor.getWSDL();
return new ResourceFile(wsdlDataStream, resourceFile.getContentType());
} else {
throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.CORRUPTED_STORED_WSDL, api.getId().toString()));
}
}
Aggregations