use of org.wso2.carbon.apimgt.api.model.DocumentationContent in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisApiIdDocumentsDocumentIdContentGet.
/**
* Retrieves the content of a particular document
*
* @param apiId UUID of API
* @param documentId UUID of the document
* @param ifNoneMatch If-None-Match header value
* @param ifModifiedSince If-Modified-Since header value
* @param request msf4j request object
* @return Content of the document
* @throws NotFoundException When the particular resource does not exist in the system
*/
@Override
public Response apisApiIdDocumentsDocumentIdContentGet(String apiId, String documentId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
String username = RestApiUtil.getLoggedInUsername(request);
try {
APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
String existingFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, ifNoneMatch, ifModifiedSince, request);
if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
return Response.notModified().build();
}
DocumentContent documentationContent = apiPublisher.getDocumentationContent(documentId);
DocumentInfo documentInfo = documentationContent.getDocumentInfo();
if (DocumentInfo.SourceType.FILE.equals(documentInfo.getSourceType())) {
String filename = documentInfo.getFileName();
return Response.ok(documentationContent.getFileContent()).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
} else if (DocumentInfo.SourceType.INLINE.equals(documentInfo.getSourceType())) {
String content = documentationContent.getInlineContent();
return Response.ok(content).header(RestApiConstants.HEADER_CONTENT_TYPE, MediaType.TEXT_PLAIN).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
} else if (DocumentInfo.SourceType.URL.equals(documentInfo.getSourceType())) {
String sourceUrl = documentInfo.getSourceURL();
return Response.seeOther(new URI(sourceUrl)).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
}
} catch (APIManagementException e) {
String errorMessage = "Error while retrieving document " + documentId + " of the API " + apiId;
HashMap<String, String> paramList = new HashMap<String, String>();
paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
log.error(errorMessage, e);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving source URI location of " + documentId;
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.DocumentationContent 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.api.model.DocumentationContent 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.api.model.DocumentationContent in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addDocumentationContentForFile.
/**
* Add documentation content of files.
*
* @param inputStream Input Stream
* @param mediaType Media type of the document
* @param filename File name
* @param apiProvider API Provider
* @param apiId API/API Product UUID
* @param documentId Document ID
* @param organization organization of the API
* @throws APIManagementException If an error occurs while adding the documentation file
*/
public static void addDocumentationContentForFile(InputStream inputStream, String mediaType, String filename, APIProvider apiProvider, String apiId, String documentId, String organization) throws APIManagementException {
DocumentationContent content = new DocumentationContent();
ResourceFile resourceFile = new ResourceFile(inputStream, mediaType);
resourceFile.setName(filename);
content.setResourceFile(resourceFile);
content.setSourceType(DocumentationContent.ContentSourceType.FILE);
apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
use of org.wso2.carbon.apimgt.api.model.DocumentationContent in project carbon-apimgt by wso2.
the class ApiProductsApiServiceImpl method getAPIProductDocumentContent.
@Override
public Response getAPIProductDocumentContent(String apiProductId, String documentId, String accept, String ifNoneMatch, MessageContext messageContext) {
Documentation documentation;
try {
String username = RestApiCommonUtil.getLoggedInUsername();
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// this will fail if user does not have access to the API Product or the API Product does not exist
APIProductIdentifier productIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
// documentation = apiProvider.getProductDocumentation(documentId, tenantDomain);
DocumentationContent docContent = apiProvider.getDocumentationContent(apiProductId, documentId, organization);
if (docContent == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
return null;
}
// gets the content depending on the type of the document
if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.FILE)) {
String contentType = docContent.getResourceFile().getContentType();
contentType = contentType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : contentType;
String name = docContent.getResourceFile().getName();
return Response.ok(docContent.getResourceFile().getContent()).header(RestApiConstants.HEADER_CONTENT_TYPE, contentType).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"").build();
} else if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.INLINE) || docContent.getSourceType().equals(DocumentationContent.ContentSourceType.MARKDOWN)) {
String content = docContent.getTextContent();
return Response.ok(content).header(RestApiConstants.HEADER_CONTENT_TYPE, DOCUMENTATION_INLINE_CONTENT_TYPE).build();
} else if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.URL)) {
String sourceUrl = docContent.getTextContent();
return Response.seeOther(new URI(sourceUrl)).build();
}
} catch (APIManagementException e) {
// Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, apiProductId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving document : " + documentId + " of API Product " + apiProductId, e, log);
} else {
String errorMessage = "Error while retrieving document " + documentId + " of the API Product" + apiProductId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving source URI location of " + documentId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
Aggregations