use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.DocumentDTO in project carbon-apimgt by wso2.
the class ImportUtils method addDocumentation.
/**
* This method adds the documents to the imported API or API Product.
*
* @param pathToArchive Location of the extracted folder of the API or API Product
* @param apiTypeWrapper Imported API or API Product
* @param organization Identifier of an Organization
*/
private static void addDocumentation(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider, String organization) {
String jsonContent = null;
Identifier identifier = apiTypeWrapper.getId();
String docDirectoryPath = pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY;
File documentsFolder = new File(docDirectoryPath);
File[] fileArray = documentsFolder.listFiles();
String provider = (apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApiProduct().getId().getProviderName() : apiTypeWrapper.getApi().getId().getProviderName();
String tenantDomain = MultitenantUtils.getTenantDomain(provider);
try {
// Remove all documents associated with the API before update
List<Documentation> documents = apiProvider.getAllDocumentation(identifier);
if (documents != null) {
for (Documentation documentation : documents) {
apiProvider.removeDocumentation(identifier, documentation.getId(), tenantDomain);
}
}
if (documentsFolder.isDirectory() && fileArray != null) {
// This loop locates the documents inside each repo
for (File documentFile : fileArray) {
String folderName = documentFile.getName();
String individualDocumentFilePath = docDirectoryPath + File.separator + folderName;
String pathToYamlFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.YAML_EXTENSION;
String pathToJsonFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.JSON_EXTENSION;
// Load document file if exists
if (CommonUtil.checkFileExistence(pathToYamlFile)) {
if (log.isDebugEnabled()) {
log.debug("Found documents definition file " + pathToYamlFile);
}
String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile));
jsonContent = CommonUtil.yamlToJson(yamlContent);
} else if (CommonUtil.checkFileExistence(pathToJsonFile)) {
// load as a json fallback
if (log.isDebugEnabled()) {
log.debug("Found documents definition file " + pathToJsonFile);
}
jsonContent = FileUtils.readFileToString(new File(pathToJsonFile));
}
JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
DocumentDTO documentDTO = new Gson().fromJson(configElement.getAsJsonObject(), DocumentDTO.class);
// Add the documentation DTO
Documentation documentation = apiTypeWrapper.isAPIProduct() ? PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApiProduct().getUuid(), organization) : PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApi().getUuid(), organization);
// Adding doc content
String docSourceType = documentation.getSourceType().toString();
boolean docContentExists = Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(docSourceType) || Documentation.DocumentSourceType.MARKDOWN.toString().equalsIgnoreCase(docSourceType);
String apiOrApiProductId = (!apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApi().getUuid() : apiTypeWrapper.getApiProduct().getUuid();
if (docContentExists) {
try (FileInputStream inputStream = new FileInputStream(individualDocumentFilePath + File.separator + folderName)) {
String inlineContent = IOUtils.toString(inputStream, ImportExportConstants.CHARSET);
PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiOrApiProductId, documentation.getId(), tenantDomain, inlineContent);
}
} else if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(docSourceType)) {
String filePath = documentation.getFilePath();
try (FileInputStream inputStream = new FileInputStream(individualDocumentFilePath + File.separator + filePath)) {
String docExtension = FilenameUtils.getExtension(pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY + File.separator + filePath);
PublisherCommonUtils.addDocumentationContentForFile(inputStream, docExtension, documentation.getFilePath(), apiProvider, apiOrApiProductId, documentation.getId(), tenantDomain);
} catch (FileNotFoundException e) {
// this error is logged and ignored because documents are optional in an API
log.error("Failed to locate the document files of the API/API Product: " + apiTypeWrapper.getId().getName(), e);
continue;
}
}
}
}
} catch (FileNotFoundException e) {
// this error is logged and ignored because documents are optional in an API
log.error("Failed to locate the document files of the API/API Product: " + identifier.getName(), e);
} catch (APIManagementException | IOException e) {
// this error is logged and ignored because documents are optional in an API
log.error("Failed to add Documentations to API/API Product: " + identifier.getName(), e);
}
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.DocumentDTO in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addDocumentationToAPI.
/**
* Add document DTO.
*
* @param documentDto Document DTO
* @param apiId API UUID
* @return Added documentation
* @param organization Identifier of an Organization
* @throws APIManagementException If an error occurs when retrieving API Identifier,
* when checking whether the documentation exists and when adding the documentation
*/
public static Documentation addDocumentationToAPI(DocumentDTO documentDto, String apiId, String organization) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
Documentation documentation = DocumentationMappingUtil.fromDTOtoDocumentation(documentDto);
String documentName = documentDto.getName();
if (documentDto.getType() == null) {
throw new APIManagementException("Documentation type cannot be empty", ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
if (documentDto.getType() == DocumentDTO.TypeEnum.OTHER && StringUtils.isBlank(documentDto.getOtherTypeName())) {
// check otherTypeName for not null if doc type is OTHER
throw new APIManagementException("otherTypeName cannot be empty if type is OTHER.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
String sourceUrl = documentDto.getSourceUrl();
if (documentDto.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
throw new APIManagementException("Invalid document sourceUrl Format", ExceptionCodes.PARAMETER_NOT_PROVIDED);
}
if (apiProvider.isDocumentationExist(apiId, documentName, organization)) {
throw new APIManagementException("Requested document '" + documentName + "' already exists", ExceptionCodes.DOCUMENT_ALREADY_EXISTS);
}
documentation = apiProvider.addDocumentation(apiId, documentation, organization);
return documentation;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.DocumentDTO in project carbon-apimgt by wso2.
the class ApiProductsApiServiceImpl method updateAPIProductDocument.
@Override
public Response updateAPIProductDocument(String apiProductId, String documentId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
String sourceUrl = body.getSourceUrl();
Documentation oldDocument = apiProvider.getDocumentation(apiProductId, documentId, organization);
// validation checks for existence of the document
if (oldDocument == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
return null;
}
if (body.getType() == null) {
throw new BadRequestException();
}
if (body.getType() == DocumentDTO.TypeEnum.OTHER && org.apache.commons.lang3.StringUtils.isBlank(body.getOtherTypeName())) {
// check otherTypeName for not null if doc type is OTHER
RestApiUtil.handleBadRequest("otherTypeName cannot be empty if type is OTHER.", log);
return null;
}
if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
return null;
}
// overriding some properties
body.setName(oldDocument.getName());
Documentation newDocumentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
// this will fail if user does not have access to the API or the API does not exist
APIProductIdentifier apiIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
newDocumentation.setFilePath(oldDocument.getFilePath());
newDocumentation.setId(oldDocument.getId());
apiProvider.updateDocumentation(apiProductId, newDocumentation, organization);
// retrieve the updated documentation
newDocumentation = apiProvider.getDocumentation(apiProductId, documentId, organization);
return Response.ok().entity(DocumentationMappingUtil.fromDocumentationToDTO(newDocumentation)).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_API_PRODUCT, apiProductId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while updating document : " + documentId + " of API Product " + apiProductId, e, log);
} else {
String errorMessage = "Error while updating the document " + documentId + " for API Product : " + apiProductId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.DocumentDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method addAPIDocumentContent.
/**
* Add content to a document. Content can be inline or File
*
* @param apiId API identifier
* @param documentId document identifier
* @param inputStream file input stream
* @param fileDetail file details as Attachment
* @param inlineContent inline content for the document
* @param ifMatch If-match header value
* @return updated document as DTO
*/
@Override
public Response addAPIDocumentContent(String apiId, String documentId, String ifMatch, InputStream inputStream, Attachment fileDetail, String inlineContent, MessageContext messageContext) {
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
if (inputStream != null && inlineContent != null) {
RestApiUtil.handleBadRequest("Only one of 'file' and 'inlineContent' should be specified", log);
}
// retrieves the document and send 404 if not found
Documentation documentation = apiProvider.getDocumentation(apiId, documentId, organization);
if (documentation == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_DOCUMENTATION, documentId, log);
return null;
}
// add content depending on the availability of either input stream or inline content
if (inputStream != null) {
if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.FILE)) {
RestApiUtil.handleBadRequest("Source type of document " + documentId + " is not FILE", log);
}
String filename = fileDetail.getContentDisposition().getFilename();
if (APIUtil.isSupportedFileType(filename)) {
RestApiPublisherUtils.attachFileToDocument(apiId, documentation, inputStream, fileDetail, organization);
} else {
RestApiUtil.handleBadRequest("Unsupported extension type of document file: " + filename, log);
}
} else if (inlineContent != null) {
if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.INLINE) && !documentation.getSourceType().equals(Documentation.DocumentSourceType.MARKDOWN)) {
RestApiUtil.handleBadRequest("Source type of document " + documentId + " is not INLINE " + "or MARKDOWN", log);
}
PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiId, documentId, organization, inlineContent);
} else {
RestApiUtil.handleBadRequest("Either 'file' or 'inlineContent' should be specified", log);
}
// retrieving the updated doc and the URI
Documentation updatedDoc = apiProvider.getDocumentation(apiId, documentId, organization);
DocumentDTO documentDTO = DocumentationMappingUtil.fromDocumentationToDTO(updatedDoc);
String uriString = RestApiConstants.RESOURCE_PATH_DOCUMENT_CONTENT.replace(RestApiConstants.APIID_PARAM, apiId).replace(RestApiConstants.DOCUMENTID_PARAM, documentId);
URI uri = new URI(uriString);
return Response.created(uri).entity(documentDTO).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_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while adding content to the document: " + documentId + " of API " + apiId, e, log);
} else {
RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, e, log);
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving document content location : " + documentId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} finally {
IOUtils.closeQuietly(inputStream);
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.DocumentDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method updateAPIDocument.
/**
* Updates an existing document of an API
*
* @param apiId API identifier
* @param documentId document identifier
* @param body updated document DTO
* @param ifMatch If-match header value
* @return updated document DTO as response
*/
@Override
public Response updateAPIDocument(String apiId, String documentId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
String sourceUrl = body.getSourceUrl();
Documentation oldDocument = apiProvider.getDocumentation(apiId, documentId, organization);
// validation checks for existence of the document
if (body.getType() == null) {
throw new BadRequestException();
}
if (oldDocument == null) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_DOCUMENTATION, documentId, log);
return null;
}
if (body.getType() == DocumentDTO.TypeEnum.OTHER && org.apache.commons.lang3.StringUtils.isBlank(body.getOtherTypeName())) {
// check otherTypeName for not null if doc type is OTHER
RestApiUtil.handleBadRequest("otherTypeName cannot be empty if type is OTHER.", log);
return null;
}
if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
return null;
}
// overriding some properties
body.setName(oldDocument.getName());
Documentation newDocumentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
newDocumentation.setFilePath(oldDocument.getFilePath());
newDocumentation.setId(documentId);
newDocumentation = apiProvider.updateDocumentation(apiId, newDocumentation, organization);
return Response.ok().entity(DocumentationMappingUtil.fromDocumentationToDTO(newDocumentation)).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_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while updating document : " + documentId + " of API " + apiId, e, log);
} else {
String errorMessage = "Error while updating the document " + documentId + " for API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
Aggregations