com.amazonaws.services.apigateway.model.Resource Java Examples

The following examples show how to use com.amazonaws.services.apigateway.model.Resource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 6 votes vote down vote up
private void cleanupMethods (Resource resource, Map<ActionType, Action> actions) {
    final HashSet<String> methods = new HashSet<>();

    for (ActionType action : actions.keySet()) {
        methods.add(action.toString());
    }

    for (Method m : resource.getResourceMethods().values()) {
        String httpMethod = m.getHttpMethod().toUpperCase();

        if (!methods.contains(httpMethod)) {
            LOG.info(format("Removing deleted method %s for resource %s", httpMethod, resource.getId()));

            m.deleteMethod();
        }
    }
}
 
Example #2
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #4
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #5
Source File: CheckForApiGatewayProtected.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private GetMethodResult getGetMethodResult(Resource resource,
        String resourceId, Map.Entry<String, Method> httpMethod,
        AmazonApiGatewayClient apiGatewayClient) {
    GetMethodRequest methodRequest = new GetMethodRequest();
    methodRequest.setResourceId(resource.getId());
    methodRequest.setRestApiId(resourceId);
    methodRequest.setHttpMethod(httpMethod.getKey());
    return apiGatewayClient.getMethod(methodRequest);
}
 
Example #6
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
private String getAuthorizationTypeFromConfig(Resource resource, String method, JSONObject config) {
    if (config == null) {
        return "NONE";
    }

    try {
        return config.getJSONObject(resource.getPath())
                .getJSONObject(method.toLowerCase())
                .getJSONObject("auth")
                .getString("type")
                .toUpperCase();
    } catch (JSONException exception) {
        return "NONE";
    }
}
 
Example #7
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
private void createIntegration(Resource resource, Method method, JSONObject config) {
    if (config == null) {
        return;
    }

    try {
        final JSONObject integ = config.getJSONObject(resource.getPath())
                .getJSONObject(method.getHttpMethod().toLowerCase())
                .getJSONObject("integration");

        IntegrationType type = IntegrationType.valueOf(integ.getString("type").toUpperCase());

        LOG.info("Creating integration with type " + type);

        PutIntegrationInput input = new PutIntegrationInput()
                .withType(type)
                .withUri(integ.getString("uri"))
                .withCredentials(integ.optString("credentials"))
                .withHttpMethod(integ.optString("httpMethod"))
                .withRequestParameters(jsonObjectToHashMapString(integ.optJSONObject("requestParameters")))
                .withRequestTemplates(jsonObjectToHashMapString(integ.optJSONObject("requestTemplates")))
                .withCacheNamespace(integ.optString("cacheNamespace"))
                .withCacheKeyParameters(jsonObjectToListString(integ.optJSONArray("cacheKeyParameters")));

        Integration integration = method.putIntegration(input);

        createIntegrationResponses(integration, integ.optJSONObject("responses"));
    } catch (JSONException e) {
        LOG.info(format("Skipping integration for method %s of %s: %s", method.getHttpMethod(), resource.getPath(), e));
    }
}
 
Example #8
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #9
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #10
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #11
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
protected void deleteResource(Resource resource) {
    if (resource._isLinkAvailable("resource:delete")) {
        try {
            resource.deleteResource();
        } catch (NotFoundException error) {}
    }
    // can't delete root resource
}
 
Example #12
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #13
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
protected Optional<Resource> getResource(String parentResourceId, String pathPart, List<Resource> resources) {
    for (Resource r : resources) {
        if (pathEquals(pathPart, r.getPathPart()) && r.getParentId().equals(parentResourceId)) {
            return Optional.of(r);
        }
    }
    return Optional.empty();
}
 
Example #14
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 5 votes vote down vote up
protected Optional<Resource> getRootResource(RestApi api) {
    for (Resource r : buildResourceList(api)) {
        if ("/".equals(r.getPath())) {
            return Optional.of(r);
        }
    }
    return Optional.empty();
}
 
Example #15
Source File: CheckForApiGatewayProtected.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private List<Resource> getResourceList(String resourceId,
        AmazonApiGatewayClient apiGatewayClient) {
    GetResourcesRequest resourcesRequest = new GetResourcesRequest();
    resourcesRequest.setRestApiId(resourceId);
    GetResourcesResult resourceResult = apiGatewayClient
            .getResources(resourcesRequest);
    return resourceResult.getItems();
}
 
Example #16
Source File: ApiGatewaySdkApiImporter.java    From aws-apigateway-importer with Apache License 2.0 4 votes vote down vote up
protected boolean methodExists(Resource resource, String httpMethod) {
    return resource.getResourceMethods().get(httpMethod.toUpperCase()) != null;
}
 
Example #17
Source File: CheckForApiGatewayProtectedTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Test
public void test()throws Exception{
    Method method = new Method();
    method.setApiKeyRequired(true);
    method.setHttpMethod("Get");
    Map<String, Method> resourceMethods = new HashMap();
    resourceMethods.put("1", method);
    Resource resource = new Resource();
    resource.setResourceMethods(resourceMethods);
    Collection<Resource> li = new ArrayList<>();
    li.add(resource);
    GetResourcesResult resourceResult = new GetResourcesResult();
    resourceResult.setItems(li);
    
    GetMethodResult methodResult = new GetMethodResult();
    methodResult.setAuthorizationType("AuthorizationType");
    methodResult.setApiKeyRequired(false);
    methodResult.setHttpMethod("Get");
    Collection<Resource> emptyList = new ArrayList<>();
    GetResourcesResult  emptyRulesResult = new GetResourcesResult ();
    emptyRulesResult.setItems(emptyList);
    
    
    mockStatic(PacmanUtils.class);
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString(),anyString())).thenReturn(
            true);
    
    when(PacmanUtils.splitStringToAList(anyString(),anyString())).thenReturn(CommonTestUtils.getListString());

    Map<String,Object>map=new HashMap<String, Object>();
    map.put("client", apiGatewayClient);
    CheckForApiGatewayProtected spy = Mockito.spy(new CheckForApiGatewayProtected());
    
    Mockito.doReturn(map).when((BaseRule)spy).getClientFor(anyObject(), anyString(), anyObject());
    
    when(apiGatewayClient.getResources(anyObject())).thenReturn(resourceResult);

    
    when(apiGatewayClient.getMethod(anyObject())).thenReturn(methodResult);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    when(apiGatewayClient.getResources(anyObject())).thenReturn(emptyRulesResult);
    spy.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "));
    
    when(apiGatewayClient.getResources(anyObject())).thenThrow(new RuleExecutionFailedExeption());
    assertThatThrownBy( 
            () -> checkForApiGatewayProtected.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
    
    
    when(PacmanUtils.doesAllHaveValue(anyString(),anyString(),anyString(),anyString())).thenReturn(
            false);
    assertThatThrownBy(
            () -> checkForApiGatewayProtected.execute(CommonTestUtils.getMapString("r_123 "),CommonTestUtils.getMapString("r_123 "))).isInstanceOf(InvalidInputException.class);
}
 
Example #18
Source File: ApiGatewaySwaggerFileImporterTest.java    From aws-apigateway-importer with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    BasicConfigurator.configure();

    Injector injector = Guice.createInjector(new SwaggerApiImporterTestModule());

    client = injector.getInstance(ApiGateway.class);
    importer = injector.getInstance(SwaggerApiFileImporter.class);

    RestApis mockRestApis = mock(RestApis.class);
    Integration mockIntegration = Mockito.mock(Integration.class);

    Method mockMethod = Mockito.mock(Method.class);
    when(mockMethod.getHttpMethod()).thenReturn("GET");
    when(mockMethod.putIntegration(any())).thenReturn(mockIntegration);

    mockChildResource = Mockito.mock(Resource.class);
    when(mockChildResource.getPath()).thenReturn("/child");
    when(mockChildResource.putMethod(any(), any())).thenReturn(mockMethod);

    mockResource = Mockito.mock(Resource.class);
    when(mockResource.getPath()).thenReturn("/");
    when(mockResource.createResource(any())).thenReturn(mockChildResource);
    when(mockResource.putMethod(any(), any())).thenReturn(mockMethod);

    Resources mockResources = mock(Resources.class);
    when(mockResources.getItem()).thenReturn(Arrays.asList(mockResource));

    Model mockModel = Mockito.mock(Model.class);
    when(mockModel.getName()).thenReturn("test model");

    Models mockModels = mock(Models.class);
    when(mockModels.getItem()).thenReturn(Arrays.asList(mockModel));

    mockRestApi = mock(RestApi.class);
    when(mockRestApi.getResources()).thenReturn(mockResources);
    when(mockRestApi.getModels()).thenReturn(mockModels);
    when(mockRestApi.getResourceById(any())).thenReturn(mockResource);

    when(client.getRestApis()).thenReturn(mockRestApis);
    when(client.createRestApi(any())).thenReturn(mockRestApi);

    importer.importApi(getResourcePath(API_GATEWAY));
}
 
Example #19
Source File: ApiGatewaySdkRamlApiImporter.java    From aws-apigateway-importer with Apache License 2.0 3 votes vote down vote up
private Resource createResourcePath(RestApi api, Resource resource, String fullPath) {
    final String[] parts = fullPath.split("/");

    Resource parentResource = resource;

    List<Resource> resources = buildResourceList(api);

    for (int i = 1; i < parts.length; i++) {
        parentResource = createResource(api, parentResource.getId(), parts[i], resources);

        paths.add(parentResource.getPath());
    }

    return parentResource;
}