Skip to content

Commit

Permalink
Add changes for APIs export REST API
Browse files Browse the repository at this point in the history
  • Loading branch information
HeshanSudarshana committed Aug 19, 2024
1 parent 6e1eb10 commit 7d26f5a
Show file tree
Hide file tree
Showing 7 changed files with 496 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4047,6 +4047,85 @@ paths:
> exportAPI.zip'
operationId: exportAPI

/apis/export/apis:
get:
tags:
- Import Export
summary: Export APIs for a given environment
description: |
This operation can be used to export the details of given APIs to a zip file.
parameters:
- name: apiId
in: query
description: UUID of the API
required: false
schema:
type: string
- name: name
in: query
description: |
API Name
required: false
schema:
type: string
- name: version
in: query
description: |
Version of the API
required: false
schema:
type: string
- name: gatewayLabel
in: query
description: |
Gateway environment name to export the APIs
required: false
schema:
type: string
- name: gatewayType
in: query
description: |
Gateway type for the exported APIs
schema:
type: string
enum:
- Synapse
- Envoy
default: Envoy
responses:
200:
description: |
OK.
Export Successful.
headers:
Content-Type:
description: |
The content type of the body.
schema:
type: string
content:
application/zip:
schema:
type: string
format: binary
404:
$ref: '#/components/responses/NotFound'
500:
$ref: '#/components/responses/InternalServerError'
security:
- OAuth2Security:
- apim:api_view
- apim:api_publish
- apim:api_create
- apim:api_import_export
- apim:api_manage
x-code-samples:
- lang: Curl
source: 'curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8"
"https://127.0.0.1:9443/api/am/publisher/v4/apis/export/apis?apiId=96077508-fd01-4fae-bc64-5de0e2baf43c&name=PizzaShackAPI&version=1.0&provider=admin&format=YAML&gatewayEnvironment=Default"
> exportAPIs.zip'
operationId: exportAPIs

/apis/import:
post:
tags:
Expand Down Expand Up @@ -13172,6 +13251,23 @@ components:
description: |
Revision of the imported API
example: 1
#-----------------------------------------------------
# The Synapse Artifacts List resource
#-----------------------------------------------------
SynapseArtifactList:
title: SynapseArtifactList
properties:
count:
type: integer
description: |
Number of Synapse Artifacts returned.
example: 1
list:
type: array
items:
type: string
pagination:
$ref: '#/definitions/Pagination'
responses:
BadRequest:
description: Bad Request. Invalid request or validation error.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO;
import javax.validation.constraints.*;


import io.swagger.annotations.*;
import java.util.Objects;

import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope;
import com.fasterxml.jackson.annotation.JsonCreator;

import javax.validation.Valid;



public class SynapseArtifactListDTO {

private Integer count = null;
private List<String> list = new ArrayList<String>();
private PaginationDTO pagination = null;

/**
* Number of Synapse Artifacts returned.
**/
public SynapseArtifactListDTO count(Integer count) {
this.count = count;
return this;
}


@ApiModelProperty(example = "1", value = "Number of Synapse Artifacts returned. ")
@JsonProperty("count")
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}

/**
**/
public SynapseArtifactListDTO list(List<String> list) {
this.list = list;
return this;
}


@ApiModelProperty(value = "")
@JsonProperty("list")
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}

/**
**/
public SynapseArtifactListDTO pagination(PaginationDTO pagination) {
this.pagination = pagination;
return this;
}


@ApiModelProperty(value = "")
@Valid
@JsonProperty("pagination")
public PaginationDTO getPagination() {
return pagination;
}
public void setPagination(PaginationDTO pagination) {
this.pagination = pagination;
}


@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SynapseArtifactListDTO synapseArtifactList = (SynapseArtifactListDTO) o;
return Objects.equals(count, synapseArtifactList.count) &&
Objects.equals(list, synapseArtifactList.list) &&
Objects.equals(pagination, synapseArtifactList.pagination);
}

@Override
public int hashCode() {
return Objects.hash(count, list, pagination);
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SynapseArtifactListDTO {\n");

sb.append(" count: ").append(toIndentedString(count)).append("\n");
sb.append(" list: ").append(toIndentedString(list)).append("\n");
sb.append(" pagination: ").append(toIndentedString(pagination)).append("\n");
sb.append("}");
return sb.toString();
}

/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,27 @@ public Response exportAPI( @ApiParam(value = "UUID of the API") @QueryParam("ap
return delegate.exportAPI(apiId, name, version, revisionNumber, providerName, format, preserveStatus, latestRevision, securityContext);
}

@GET
@Path("/export/apis")

@Produces({ "application/zip", "application/json" })
@ApiOperation(value = "Export APIs for a given environment", notes = "This operation can be used to export the details of given APIs to a zip file. ", response = File.class, authorizations = {
@Authorization(value = "OAuth2Security", scopes = {
@AuthorizationScope(scope = "apim:api_view", description = "View API"),
@AuthorizationScope(scope = "apim:api_publish", description = "Publish API"),
@AuthorizationScope(scope = "apim:api_create", description = "Create API"),
@AuthorizationScope(scope = "apim:api_import_export", description = "Import and export APIs related operations"),
@AuthorizationScope(scope = "apim:api_manage", description = "Manage all API related operations")
})
}, tags={ "Import Export", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. Export Successful. ", response = File.class),
@ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class),
@ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) })
public Response exportAPIs( @ApiParam(value = "UUID of the API") @QueryParam("apiId") String apiId, @ApiParam(value = "API Name ") @QueryParam("name") String name, @ApiParam(value = "Version of the API ") @QueryParam("version") String version, @ApiParam(value = "Gateway environment name to export the APIs ") @QueryParam("gatewayLabel") String gatewayLabel, @ApiParam(value = "Gateway type for the exported APIs ", allowableValues="Synapse, Envoy", defaultValue="Envoy") @DefaultValue("Envoy") @QueryParam("gatewayType") String gatewayType) throws APIManagementException{
return delegate.exportAPIs(apiId, name, version, gatewayLabel, gatewayType, securityContext);
}

@POST
@Path("/{apiId}/generate-key")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ public interface ApisApiService {
public Response deployAPIRevision(String apiId, String revisionId, List<APIRevisionDeploymentDTO> apIRevisionDeploymentDTO, MessageContext messageContext) throws APIManagementException;
public Response editCommentOfAPI(String commentId, String apiId, PatchRequestBodyDTO patchRequestBodyDTO, MessageContext messageContext) throws APIManagementException;
public Response exportAPI(String apiId, String name, String version, String revisionNumber, String providerName, String format, Boolean preserveStatus, Boolean latestRevision, MessageContext messageContext) throws APIManagementException;
public Response exportAPIs(String apiId, String name, String version, String gatewayLabel, String gatewayType, MessageContext messageContext) throws APIManagementException;
public Response generateInternalAPIKey(String apiId, MessageContext messageContext) throws APIManagementException;
public Response generateMockScripts(String apiId, String ifNoneMatch, MessageContext messageContext) throws APIManagementException;
public Response getAPI(String apiId, String xWSO2Tenant, String ifNoneMatch, MessageContext messageContext) throws APIManagementException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@
import org.wso2.carbon.apimgt.impl.certificatemgt.ResponseCode;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.definitions.*;
import org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto;
import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO;
import org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.RuntimeArtifactGeneratorUtil;
import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException;
import org.wso2.carbon.apimgt.impl.importexport.ExportFormat;
import org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI;
Expand All @@ -79,11 +81,14 @@
import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil;
import org.wso2.carbon.core.util.CryptoException;
import org.wso2.carbon.core.util.CryptoUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.util.*;

import static org.wso2.carbon.apimgt.api.ExceptionCodes.API_VERSION_ALREADY_EXISTS;
Expand Down Expand Up @@ -3397,6 +3402,61 @@ public Response createNewAPIVersion(String newVersion, String apiId, Boolean def
}
}

/**
* Exports APIs from API Manager for a given gateway environment.
*
* @param apiId UUID of an API
* @param name Name of the API that needs to be exported
* @param version Version of the API that needs to be exported
* @param gatewayLabel Gateway environment of the APIs
* @param gatewayType Gateway type
* @return ZIP file containing exported APIs
* @throws APIManagementException when error occurred while exporting the APIs
*/
@Override
public Response exportAPIs(String apiId, String name, String version, String gatewayLabel, String gatewayType,
MessageContext messageContext) throws APIManagementException {
RuntimeArtifactDto runtimeArtifactDto;
String organization = RestApiUtil.getValidatedOrganization(messageContext);
if (StringUtils.isNotEmpty(organization) && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
.equalsIgnoreCase(organization)) {
runtimeArtifactDto = RuntimeArtifactGeneratorUtil.generateAllRuntimeArtifact(apiId, gatewayLabel,
gatewayType);
} else {
runtimeArtifactDto = RuntimeArtifactGeneratorUtil.generateRuntimeArtifact(apiId,
gatewayLabel, gatewayType, organization);
}
if (runtimeArtifactDto != null) {
if (runtimeArtifactDto.isFile()) {
File artifact = (File) runtimeArtifactDto.getArtifact();
StreamingOutput streamingOutput = (outputStream) -> {
try {
Files.copy(artifact.toPath(), outputStream);
} finally {
Files.delete(artifact.toPath());
}
};
return Response.ok(streamingOutput).header(RestApiConstants.HEADER_CONTENT_DISPOSITION,
"attachment; filename=apis.zip").header(RestApiConstants.HEADER_CONTENT_TYPE,
APIConstants.APPLICATION_ZIP).build();
} else {
SynapseArtifactListDTO synapseArtifactListDTO = new SynapseArtifactListDTO();
if (runtimeArtifactDto.getArtifact() instanceof List) {
synapseArtifactListDTO.setList((List<String>) runtimeArtifactDto.getArtifact());
synapseArtifactListDTO.setCount(((List<String>) runtimeArtifactDto.getArtifact()).size());
}
return Response.ok().entity(synapseArtifactListDTO)
.header(RestApiConstants.HEADER_CONTENT_TYPE, RestApiConstants.APPLICATION_JSON).build();
}
} else {
return Response
.status(Response.Status.NOT_FOUND)
.entity(RestApiUtil.getErrorDTO(ExceptionCodes.NO_API_ARTIFACT_FOUND))
.build();
}
}


@Override
public Response generateInternalAPIKey(String apiId, MessageContext messageContext) throws APIManagementException {

Expand Down
Loading

0 comments on commit 7d26f5a

Please sign in to comment.