Search in sources :

Example 71 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class APIUtil method getDocumentation.

/**
 * Create the Documentation from artifact
 *
 * @param artifact Documentation artifact
 * @return Documentation
 * @throws APIManagementException if failed to create Documentation from artifact
 */
public static Documentation getDocumentation(GenericArtifact artifact) throws APIManagementException {
    Documentation documentation;
    try {
        DocumentationType type;
        String docType = artifact.getAttribute(APIConstants.DOC_TYPE);
        if (docType.equalsIgnoreCase(DocumentationType.HOWTO.getType())) {
            type = DocumentationType.HOWTO;
        } else if (docType.equalsIgnoreCase(DocumentationType.PUBLIC_FORUM.getType())) {
            type = DocumentationType.PUBLIC_FORUM;
        } else if (docType.equalsIgnoreCase(DocumentationType.SUPPORT_FORUM.getType())) {
            type = DocumentationType.SUPPORT_FORUM;
        } else if (docType.equalsIgnoreCase(DocumentationType.API_MESSAGE_FORMAT.getType())) {
            type = DocumentationType.API_MESSAGE_FORMAT;
        } else if (docType.equalsIgnoreCase(DocumentationType.SAMPLES.getType())) {
            type = DocumentationType.SAMPLES;
        } else {
            type = DocumentationType.OTHER;
        }
        documentation = new Documentation(type, artifact.getAttribute(APIConstants.DOC_NAME));
        documentation.setId(artifact.getId());
        documentation.setSummary(artifact.getAttribute(APIConstants.DOC_SUMMARY));
        String visibilityAttr = artifact.getAttribute(APIConstants.DOC_VISIBILITY);
        Documentation.DocumentVisibility documentVisibility = Documentation.DocumentVisibility.API_LEVEL;
        if (visibilityAttr != null) {
            if (visibilityAttr.equals(Documentation.DocumentVisibility.API_LEVEL.name())) {
                documentVisibility = Documentation.DocumentVisibility.API_LEVEL;
            } else if (visibilityAttr.equals(Documentation.DocumentVisibility.PRIVATE.name())) {
                documentVisibility = Documentation.DocumentVisibility.PRIVATE;
            } else if (visibilityAttr.equals(Documentation.DocumentVisibility.OWNER_ONLY.name())) {
                documentVisibility = Documentation.DocumentVisibility.OWNER_ONLY;
            }
        }
        documentation.setVisibility(documentVisibility);
        Documentation.DocumentSourceType docSourceType = Documentation.DocumentSourceType.INLINE;
        String artifactAttribute = artifact.getAttribute(APIConstants.DOC_SOURCE_TYPE);
        if (Documentation.DocumentSourceType.URL.name().equals(artifactAttribute)) {
            docSourceType = Documentation.DocumentSourceType.URL;
            documentation.setSourceUrl(artifact.getAttribute(APIConstants.DOC_SOURCE_URL));
        } else if (Documentation.DocumentSourceType.FILE.name().equals(artifactAttribute)) {
            docSourceType = Documentation.DocumentSourceType.FILE;
            documentation.setFilePath(prependWebContextRoot(artifact.getAttribute(APIConstants.DOC_FILE_PATH)));
        } else if (Documentation.DocumentSourceType.MARKDOWN.name().equals(artifactAttribute)) {
            docSourceType = Documentation.DocumentSourceType.MARKDOWN;
        }
        documentation.setSourceType(docSourceType);
        if (documentation.getType() == DocumentationType.OTHER) {
            documentation.setOtherTypeName(artifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME));
        }
    } catch (GovernanceException e) {
        throw new APIManagementException("Failed to get documentation from artifact", e);
    }
    return documentation;
}
Also used : DocumentationType(org.wso2.carbon.apimgt.api.model.DocumentationType) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException)

Example 72 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class APIConsumerImpl method searchPaginatedContent.

@Override
public Map<String, Object> searchPaginatedContent(String searchQuery, String organization, int start, int end) throws APIManagementException {
    ArrayList<Object> compoundResult = new ArrayList<Object>();
    Map<Documentation, API> docMap = new HashMap<Documentation, API>();
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    int totalLength = 0;
    String userame = (userNameWithoutChange != null) ? userNameWithoutChange : username;
    Organization org = new Organization(organization);
    Map<String, Object> properties = APIUtil.getUserProperties(userame);
    String[] roles = APIUtil.getFilteredUserRoles(userame);
    ;
    UserContext ctx = new UserContext(userame, org, properties, roles);
    try {
        DevPortalContentSearchResult sResults = apiPersistenceInstance.searchContentForDevPortal(org, searchQuery, start, end, ctx);
        if (sResults != null) {
            List<SearchContent> resultList = sResults.getResults();
            for (SearchContent item : resultList) {
                if (item instanceof DocumentSearchContent) {
                    // doc item
                    DocumentSearchContent docItem = (DocumentSearchContent) item;
                    Documentation doc = new Documentation(DocumentationType.valueOf(docItem.getDocType().toString()), docItem.getName());
                    doc.setSourceType(DocumentSourceType.valueOf(docItem.getSourceType().toString()));
                    doc.setVisibility(DocumentVisibility.valueOf(docItem.getVisibility().toString()));
                    doc.setId(docItem.getId());
                    API api = new API(new APIIdentifier(docItem.getApiProvider(), docItem.getApiName(), docItem.getApiVersion()));
                    api.setUuid(docItem.getApiUUID());
                    docMap.put(doc, api);
                } else {
                    DevPortalSearchContent publiserAPI = (DevPortalSearchContent) item;
                    API api = new API(new APIIdentifier(publiserAPI.getProvider(), publiserAPI.getName(), publiserAPI.getVersion()));
                    api.setUuid(publiserAPI.getId());
                    api.setContext(publiserAPI.getContext());
                    api.setContextTemplate(publiserAPI.getContext());
                    api.setStatus(publiserAPI.getStatus());
                    // need to retrieve from db
                    api.setRating(0);
                    apiSet.add(api);
                }
            }
            compoundResult.addAll(apiSet);
            compoundResult.addAll(docMap.entrySet());
            compoundResult.sort(new ContentSearchResultNameComparator());
            result.put("length", sResults.getTotalCount());
        } else {
            result.put("length", compoundResult.size());
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching content ", e);
    }
    result.put("apis", compoundResult);
    return result;
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) ArrayList(java.util.ArrayList) DevPortalContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.DevPortalContentSearchResult) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) SearchContent(org.wso2.carbon.apimgt.persistence.dto.SearchContent) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator)

Example 73 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class APIConsumerImpl method filterMultipleVersionedAPIs.

private Map<String, Object> filterMultipleVersionedAPIs(Map<String, Object> searchResults) {
    Object apiObj = searchResults.get("apis");
    ArrayList<Object> apiSet;
    ArrayList<APIProduct> apiProductSet = new ArrayList<>();
    if (apiObj instanceof Set) {
        apiSet = new ArrayList<>(((Set) apiObj));
    } else {
        apiSet = (ArrayList<Object>) apiObj;
    }
    // Store the length of the APIs list with the versioned APIs
    int apiSetLengthWithVersionedApis = apiSet.size();
    int totalLength = Integer.parseInt(searchResults.get("length").toString());
    // filter store results if displayMultipleVersions is set to false
    Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
    if (!displayMultipleVersions) {
        SortedSet<API> resultApis = new TreeSet<API>(new APINameComparator());
        for (Object result : apiSet) {
            if (result instanceof API) {
                resultApis.add((API) result);
            } else if (result instanceof Map.Entry) {
                Map.Entry<Documentation, API> entry = (Map.Entry<Documentation, API>) result;
                resultApis.add(entry.getValue());
            } else if (result instanceof APIProduct) {
                apiProductSet.add((APIProduct) result);
            }
        }
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        String key;
        // Run the result api list through API version comparator and filter out multiple versions
        for (API api : resultApis) {
            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
            API existingAPI = latestPublishedAPIs.get(key);
            if (existingAPI != null) {
                // this one has a higher version number
                if (versionComparator.compare(api, existingAPI) > 0) {
                    latestPublishedAPIs.put(key, api);
                }
            } else {
                // We haven't seen this API before
                latestPublishedAPIs.put(key, api);
            }
        }
        // filter apiSet
        ArrayList<Object> tempApiSet = new ArrayList<Object>();
        for (Object result : apiSet) {
            API api = null;
            String mapKey;
            API latestAPI;
            if (result instanceof API) {
                api = (API) result;
                mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                if (latestPublishedAPIs.containsKey(mapKey)) {
                    latestAPI = latestPublishedAPIs.get(mapKey);
                    if (latestAPI.getId().equals(api.getId())) {
                        tempApiSet.add(api);
                    }
                }
            } else if (result instanceof Map.Entry) {
                Map.Entry<Documentation, API> docEntry = (Map.Entry<Documentation, API>) result;
                api = docEntry.getValue();
                mapKey = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                if (latestPublishedAPIs.containsKey(mapKey)) {
                    latestAPI = latestPublishedAPIs.get(mapKey);
                    if (latestAPI.getId().equals(api.getId())) {
                        tempApiSet.add(docEntry);
                    }
                }
            }
        }
        // Store the length of the APIs list without the versioned APIs
        int apiSetLengthWithoutVersionedApis = tempApiSet.size();
        apiSet = tempApiSet;
        ArrayList<Object> resultAPIandProductSet = new ArrayList<>();
        resultAPIandProductSet.addAll(apiSet);
        resultAPIandProductSet.addAll(apiProductSet);
        resultAPIandProductSet.sort(new ContentSearchResultNameComparator());
        if (apiObj instanceof Set) {
            searchResults.put("apis", new LinkedHashSet<>(resultAPIandProductSet));
        } else {
            searchResults.put("apis", resultAPIandProductSet);
        }
        searchResults.put("length", totalLength - (apiSetLengthWithVersionedApis - (apiSetLengthWithoutVersionedApis + apiProductSet.size())));
    }
    return searchResults;
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) LinkedHashSet(java.util.LinkedHashSet) SortedSet(java.util.SortedSet) HashSet(java.util.HashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) TreeSet(java.util.TreeSet) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 74 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class DocumentationMappingUtil method fromDocumentationListToDTO.

/**
 * Converts a List object of Documents into a DTO.
 *
 * @param documentations List of Documentations
 * @param limit          maximum number of APIs returns
 * @param offset         starting index
 * @return DocumentListDTO object containing Document DTOs
 */
public static DocumentListDTO fromDocumentationListToDTO(List<Documentation> documentations, int offset, int limit) {
    DocumentListDTO documentListDTO = new DocumentListDTO();
    List<DocumentDTO> documentDTOs = documentListDTO.getList();
    if (documentDTOs == null) {
        documentDTOs = new ArrayList<>();
        documentListDTO.setList(documentDTOs);
    }
    // add the required range of objects to be returned
    int start = offset < documentations.size() && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= documentations.size() - 1 ? offset + limit - 1 : documentations.size() - 1;
    for (int i = start; i <= end; i++) {
        documentDTOs.add(fromDocumentationToDTO(documentations.get(i)));
    }
    documentListDTO.setCount(documentDTOs.size());
    return documentListDTO;
}
Also used : DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO) DocumentListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentListDTO)

Example 75 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class ExportUtils method exportApiProduct.

/**
 * Exports an API Product from API Manager for a given API Product. MMeta information, API Product icon,
 * documentation, client certificates and dependent APIs are exported.
 *
 * @param apiProvider           API Provider
 * @param apiProductIdentifier  API Product Identifier
 * @param apiProductDtoToReturn API Product DTO
 * @param userName              Username
 * @param exportFormat          Format of output documents. Can be YAML or JSON
 * @param preserveStatus        Preserve API Product status on export
 * @param organization          Organization Identifier
 * @return
 * @throws APIManagementException If an error occurs while getting governance registry
 */
public static File exportApiProduct(APIProvider apiProvider, APIProductIdentifier apiProductIdentifier, APIProductDTO apiProductDtoToReturn, String userName, ExportFormat exportFormat, Boolean preserveStatus, boolean preserveDocs, boolean preserveCredentials, String organization) throws APIManagementException, APIImportExportException {
    int tenantId = 0;
    // Create temp location for storing API Product data
    File exportFolder = CommonUtil.createTempDirectory(apiProductIdentifier);
    String exportAPIBasePath = exportFolder.toString();
    String archivePath = exportAPIBasePath.concat(File.separator + apiProductIdentifier.getName() + "-" + apiProductIdentifier.getVersion());
    tenantId = APIUtil.getTenantId(userName);
    CommonUtil.createDirectory(archivePath);
    if (preserveDocs) {
        addThumbnailToArchive(archivePath, apiProductIdentifier, apiProvider);
        addDocumentationToArchive(archivePath, apiProductIdentifier, exportFormat, apiProvider, APIConstants.API_PRODUCT_IDENTIFIER_TYPE);
    }
    // Set API Product status to created if the status is not preserved
    if (!preserveStatus) {
        apiProductDtoToReturn.setState(APIProductDTO.StateEnum.CREATED);
    }
    addGatewayEnvironmentsToArchive(archivePath, apiProductDtoToReturn.getId(), exportFormat, apiProvider);
    addAPIProductMetaInformationToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider);
    addDependentAPIsToArchive(archivePath, apiProductDtoToReturn, exportFormat, apiProvider, userName, Boolean.TRUE, preserveDocs, preserveCredentials, organization);
    // Export mTLS authentication related certificates
    if (log.isDebugEnabled()) {
        log.debug("Mutual SSL enabled. Exporting client certificates.");
    }
    addClientCertificatesToArchive(archivePath, apiProductIdentifier, tenantId, apiProvider, exportFormat, organization);
    CommonUtil.archiveDirectory(exportAPIBasePath);
    FileUtils.deleteQuietly(new File(exportAPIBasePath));
    return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Aggregations

Documentation (org.wso2.carbon.apimgt.api.model.Documentation)56 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 Test (org.testng.annotations.Test)38 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)34 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)33 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)32 ArrayList (java.util.ArrayList)29 Resource (org.wso2.carbon.registry.core.Resource)27 HashMap (java.util.HashMap)26 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)26 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)24 API (org.wso2.carbon.apimgt.api.model.API)23 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)23 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)22 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)18 Registry (org.wso2.carbon.registry.core.Registry)18 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 DocumentationPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)17