public void deploy(AwsKeyPair keyPair, String region, final String restApiName, final String stage, Proxy proxy) { final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); ClientConfiguration cc = Util.createConfiguration(proxy); AmazonApiGateway ag = AmazonApiGatewayClientBuilder.standard().withCredentials(credentials) // .withClientConfiguration(cc) // .withRegion(region) // .build(); GetRestApisResult apis = ag.getRestApis(new GetRestApisRequest().withLimit(10000)); Optional<RestApi> api = apis.getItems().stream().filter(item -> item.getName().equals(restApiName)).findFirst(); RestApi a = api.orElseThrow(() -> new RuntimeException("no rest api found with name='" + restApiName + "'")); String restApiId = a.getId(); log.info("creating deployment of " + restApiId + " to stage " + stage); CreateDeploymentResult r = ag .createDeployment(new CreateDeploymentRequest().withRestApiId(restApiId).withStageName(stage)); Map<String, Map<String, MethodSnapshot>> summary = r.getApiSummary(); log.info("created deployment"); log.info("summary=" + summary); }
protected List<Resource> buildResourceList(RestApi api) { List<Resource> resourceList = new ArrayList<>(); Resources resources = api.getResources(); resourceList.addAll(resources.getItem()); LOG.debug("Building list of resources. Stack trace: ", new Throwable()); final RateLimiter rl = RateLimiter.create(2); while (resources._isLinkAvailable("next")) { rl.acquire(); resources = resources.getNext(); resourceList.addAll(resources.getItem()); } return resourceList; }
protected Resource createResource(RestApi api, String parentResourceId, String part, List<Resource> resources) { final Optional<Resource> existingResource = getResource(parentResourceId, part, resources); // create resource if doesn't exist if (!existingResource.isPresent()) { LOG.info("Creating resource '" + part + "' on " + parentResourceId); CreateResourceInput input = new CreateResourceInput(); input.setPathPart(part); Resource resource = api.getResourceById(parentResourceId); Resource created = resource.createResource(input); resources.add(created); return created; } else { return existingResource.get(); } }
@Override public String createApi(Raml raml, String name, JSONObject config) { this.config = config; // TODO: What to use as description? final RestApi api = createApi(getApiName(raml, name), null); LOG.info("Created API "+api.getId()); try { final Resource rootResource = getRootResource(api).get(); deleteDefaultModels(api); createModels(api, raml.getSchemas(), false); createResources(api, createResourcePath(api, rootResource, raml.getBasePath()), new HashMap<String, UriParameter>(), raml.getResources(), false); } catch (Throwable t) { LOG.error("Error creating API, rolling back", t); rollback(api); throw t; } return api.getId(); }
private void createModels(RestApi api, List<Map<String, String>> schemas, boolean update) { for (Map<String, String> entries : schemas) { for (Map.Entry<String, String> entry : entries.entrySet()) { final String schemaName = entry.getKey(); final String schemaValue = entry.getValue(); models.add(schemaName); if (update && getModel(api, schemaName).isPresent()) { updateModel(api, schemaName, schemaValue); } else { createModel(api, schemaName, schemaValue); } } } }
@Nullable private String createModel(RestApi api, String mime, MimeType mimeType) { final String schema = mimeType.getSchema(); if (schema != null) { if (schema.matches("\\w+")) { return schema; } final String modelName = generateModelName(); models.add(modelName); createModel(api, modelName, null, schema, mime); return modelName; } return null; }
@Override public String createApi(Raml raml, String name, JSONObject config) { this.config = config; // TODO: What to use as description? final RestApi api = createApi(getApiName(raml, name), null); LOG.info("Created API "+api.getId()); try { final Resource rootResource = getRootResource(api).get(); deleteDefaultModels(api); createModels(api, raml.getSchemas(), false); createResources(api, createResourcePath(api, rootResource, raml.getBasePath()), raml.getResources(), false); } catch (Throwable t) { LOG.error("Error creating API, rolling back", t); rollback(api); throw t; } return api.getId(); }
private static Map<String, io.swagger.models.Model> getDefinitions(RestApi restApi) throws IOException, JsonParseException, JsonMappingException { Map<String, io.swagger.models.Model> result = new HashMap<String, io.swagger.models.Model>(); for (Models models = restApi.getModels(); models != null; models = safeGetNext(models)) { for (Model modelItem : models.getItem()) { String content = modelItem.getSchema(); io.swagger.models.Model model = Json.mapper().readValue(content, io.swagger.models.Model.class); if (model instanceof ModelImpl) { ((ModelImpl) model).setName(modelItem.getName()); } model.setDescription(modelItem.getDescription()); result.put(modelItem.getName(), model); } } return result; }
public void run() { String AWSAccessKey="AKIAJM7YMMLXKUH5EWRQ"; String AWSSecretKey="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"; BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AWSAccessKey, AWSSecretKey); AmazonApiGatewayClient apiClient = new AmazonApiGatewayClient(awsCredentials); apiClient.setRegion(Region.getRegion(Regions.US_WEST_2)); GetRestApisRequest graReq = new GetRestApisRequest(); GetRestApisResult graRes = apiClient.getRestApis(graReq); RestApi theApi = null; for ( RestApi api : graRes.getItems() ) { System.out.println("Found existing REST API: " + api.getName()); if ( "TestAPI".equals(api.getName())) { theApi = api; GetExportRequest geReq = new GetExportRequest() .withRestApiId(api.getId()) .withExportType("swagger") .withStageName("TEST"); GetExportResult geRes = apiClient.getExport(geReq); String f = new String(geRes.getBody().array()); int x = 1; String from = ""; PatchOperation po = new PatchOperation() .withFrom(from) .withOp(Op.Replace) .withPath(""); } } }
private void deleteApi() { final GetRestApisRequest graprq = new GetRestApisRequest(); final GetRestApisResult graprs = this.awsApiClient.getRestApis(graprq); graprs.getItems() .stream() .filter(ra -> ra.getName().equals(ApiName)) .map(RestApi::getId) .map(id -> new DeleteRestApiRequest().withRestApiId(id)) .forEach(this.awsApiClient::deleteRestApi); }
protected RestApi createApi(String name, String description) { LOG.info("Creating API with name " + name); CreateRestApiInput input = new CreateRestApiInput(); input.setName(name); input.setDescription(description); return apiGateway.createRestApi(input); }
protected Optional<Resource> getRootResource(RestApi api) { for (Resource r : buildResourceList(api)) { if ("/".equals(r.getPath())) { return Optional.of(r); } } return Optional.empty(); }
protected void deleteDefaultModels(RestApi api) { buildModelList(api).stream().forEach(model -> { LOG.info("Removing default model " + model.getName()); try { model.deleteModel(); } catch (Throwable ignored) { } // todo: temporary catch until API fix }); }
protected List<Model> buildModelList(RestApi api) { List<Model> modelList = new ArrayList<>(); Models models = api.getModels(); modelList.addAll(models.getItem()); while (models._isLinkAvailable("next")) { models = models.getNext(); modelList.addAll(models.getItem()); } return modelList; }
protected void createModel(RestApi api, String modelName, String description, String schema, String modelContentType) { this.processedModels.add(modelName); CreateModelInput input = new CreateModelInput(); input.setName(modelName); input.setDescription(description); input.setContentType(modelContentType); input.setSchema(schema); api.createModel(input); }
protected void cleanupModels(RestApi api, Set<String> models) { List<Model> existingModels = buildModelList(api); Stream<Model> modelsToDelete = existingModels.stream().filter(model -> !models.contains(model.getName())); modelsToDelete.forEach(model -> { LOG.info("Removing deleted model " + model.getName()); model.deleteModel(); }); }
protected Optional<Resource> getResource(RestApi api, String fullPath) { for (Resource r : buildResourceList(api)) { if (r.getPath().equals(fullPath)) { return Optional.of(r); } } return Optional.empty(); }
protected Optional<Model> getModel(RestApi api, String modelName) { try { return Optional.of(api.getModelByName(modelName)); } catch (Exception ignored) { return Optional.empty(); } }
@Override public void updateApi(String apiId, Raml raml, JSONObject config) { this.config = config; RestApi api = getApi(apiId); Optional<Resource> rootResource = getRootResource(api); createModels(api, raml.getSchemas(), true); createResources(api, createResourcePath(api, rootResource.get(), raml.getBasePath()), new HashMap<String, UriParameter>(), raml.getResources(), true); cleanupResources(api, this.paths); cleanupModels(api, this.models); }
private void createModel(RestApi api, String schemaName, String schemaValue) { // HACK: Attempt to detect JSON/XML bodies. final Integer openTagIndex = schemaValue.indexOf('<'); final Integer openJsonIndex = schemaValue.indexOf('{'); // Is this possible or is the parser validating schemas? if (openTagIndex == openJsonIndex) { return; } final boolean isJson = openJsonIndex > -1 && (openTagIndex == -1 || openJsonIndex < openTagIndex); // TODO: What to put as description? createModel(api, schemaName, null, schemaValue, isJson ? "application/json" : "text/xml"); }
private void createResources(RestApi api, Resource rootResource, Map<String, UriParameter> ancestorRequestParameters, Map<String, org.raml.model.Resource> resources, boolean update) { for (Map.Entry<String, org.raml.model.Resource> entry : resources.entrySet()) { final org.raml.model.Resource resource = entry.getValue(); final Resource parentResource = createResourcePath(api, rootResource, entry.getKey()); Map<String, UriParameter> requestParameters = new HashMap<String, UriParameter>(resource.getUriParameters()); requestParameters.putAll(ancestorRequestParameters); createMethods(api, parentResource, requestParameters, resource.getActions(), update); createResources(api, parentResource, requestParameters, resource.getResources(), update); } }
private void cleanupResources(RestApi api, Set<String> paths) { buildResourceList(api) .stream() .filter(resource -> !resource.getPath().equals("/") && !paths.contains(resource.getPath())) .forEach(resource -> { LOG.info("Removing deleted resource " + resource.getPath()); deleteResource(resource); }); }
private void createMethods(RestApi api, Resource resource, Map<String, UriParameter> requestParameters, Map<ActionType, Action> actions, boolean update) { for (Map.Entry<ActionType, Action> entry : actions.entrySet()) { createMethod(api, resource, entry.getKey(), entry.getValue(), requestParameters, update); } if (update) { cleanupMethods(resource, actions); } }
private void createMethodResponses(RestApi api, Method method, Map<String, Response> responses, boolean update) { for (Map.Entry<String, Response> entry : responses.entrySet()) { createMethodResponse(api, method, entry.getKey(), entry.getValue(), update); } if (update) { cleanupMethodResponses(method, responses); } }
private void updateMethod(RestApi api, Method method, String type, String name, boolean required) { String expression = getExpression("method", "request", type, name); Map<String, Boolean> requestParameters = method.getRequestParameters(); Boolean requestParameter = requestParameters == null ? null : requestParameters.get(expression); if (requestParameter != null && requestParameter.equals(required)) { return; } LOG.info(format("Creating method parameter for api %s and method %s with name %s", api.getId(), method.getHttpMethod(), expression)); method.updateMethod(createPatchDocument(createAddOperation("/requestParameters/" + expression, getStringValue(required)))); }
@Override public void updateApi(String apiId, Raml raml, JSONObject config) { this.config = config; RestApi api = getApi(apiId); Optional<Resource> rootResource = getRootResource(api); createModels(api, raml.getSchemas(), true); createResources(api, createResourcePath(api, rootResource.get(), raml.getBasePath()), raml.getResources(), true); cleanupResources(api, this.paths); cleanupModels(api, this.models); }