Search in sources :

Example 1 with IPluginRegistry

use of io.apiman.gateway.engine.IPluginRegistry in project apiman by apiman.

the class DefaultEngineFactoryTest method testCreateEngine.

/**
 * Test method for {@link io.apiman.gateway.engine.impl.AbstractEngineFactory#createEngine()}.
 * @throws ExecutionException
 * @throws InterruptedException
 */
@Test
public void testCreateEngine() throws InterruptedException, ExecutionException {
    DefaultEngineFactory factory = new DefaultEngineFactory() {

        @Override
        protected IComponentRegistry createComponentRegistry(IPluginRegistry pluginRegistry) {
            return new DefaultComponentRegistry() {

                @Override
                protected void registerBufferFactoryComponent() {
                    addComponent(IBufferFactoryComponent.class, new ByteBufferFactoryComponent());
                }
            };
        }

        @Override
        protected IConnectorFactory createConnectorFactory(IPluginRegistry pluginRegistry) {
            return new IConnectorFactory() {

                @Override
                public IApiConnector createConnector(ApiRequest request, Api api, RequiredAuthType requiredAuthType, boolean hasDataPolicy, IConnectorConfig connectorConfig) {
                    Assert.assertEquals("test", api.getEndpointType());
                    Assert.assertEquals("test:endpoint", api.getEndpoint());
                    IApiConnector connector = new IApiConnector() {

                        /**
                         * @see io.apiman.gateway.engine.IApiConnector#connect(io.apiman.gateway.engine.beans.ApiRequest, io.apiman.gateway.engine.async.IAsyncResultHandler)
                         */
                        @Override
                        public IApiConnection connect(ApiRequest request, IAsyncResultHandler<IApiConnectionResponse> handler) throws ConnectorException {
                            final ApiResponse response = new ApiResponse();
                            response.setCode(200);
                            // $NON-NLS-1$
                            response.setMessage("OK");
                            mockApiConnectionResponse = new MockApiConnectionResponse() {

                                @Override
                                public void write(IApimanBuffer chunk) {
                                    handleBody(chunk);
                                }

                                @Override
                                protected void handleHead(ApiResponse head) {
                                    return;
                                }

                                @Override
                                public ApiResponse getHead() {
                                    return response;
                                }

                                @Override
                                public void end() {
                                    handleEnd();
                                }

                                @Override
                                public void transmit() {
                                    transmitHandler.handle((Void) null);
                                }

                                @Override
                                public void abort(Throwable t) {
                                }
                            };
                            IAsyncResult<IApiConnectionResponse> mockResponseResultHandler = mock(IAsyncResult.class);
                            given(mockResponseResultHandler.isSuccess()).willReturn(true);
                            given(mockResponseResultHandler.isError()).willReturn(false);
                            given(mockResponseResultHandler.getResult()).willReturn(mockApiConnectionResponse);
                            mockApiConnection = mock(MockApiConnection.class);
                            given(mockApiConnection.getHead()).willReturn(request);
                            // Handle head
                            handler.handle(mockResponseResultHandler);
                            return mockApiConnection;
                        }
                    };
                    return connector;
                }

                @Override
                public IConnectorConfig createConnectorConfig(ApiRequest request, Api api) {
                    return new TestConnectorConfigImpl();
                }
            };
        }

        @Override
        protected IDelegateFactory createLoggerFactory(IPluginRegistry pluginRegistry) {
            return null;
        }

        @Override
        protected IApiRequestPathParser createRequestPathParser(IPluginRegistry pluginRegistry) {
            return new DefaultRequestPathParser(null);
        }

        @Override
        protected void complete() {
        }
    };
    IEngine engine = factory.createEngine();
    Assert.assertNotNull(engine);
    // create a api
    Api api = new Api();
    api.setEndpointType("test");
    api.setEndpoint("test:endpoint");
    api.setOrganizationId("TestOrg");
    api.setApiId("TestApi");
    api.setVersion("1.0");
    // create a client
    Client app = new Client();
    app.setClientId("TestApp");
    app.setOrganizationId("TestOrg");
    app.setVersion("1.0");
    app.setApiKey("client-12345");
    Contract contract = new Contract();
    contract.setPlan("Gold");
    contract.setApiId("TestApi");
    contract.setApiOrgId("TestOrg");
    contract.setApiVersion("1.0");
    contract.setPolicies(policyList);
    app.addContract(contract);
    // simple api/app config
    engine.getRegistry().publishApi(api, new IAsyncResultHandler<Void>() {

        @Override
        public void handle(IAsyncResult<Void> result) {
        }
    });
    engine.getRegistry().registerClient(app, new IAsyncResultHandler<Void>() {

        @Override
        public void handle(IAsyncResult<Void> result) {
        }
    });
    ApiRequest request = new ApiRequest();
    request.setApiKey("client-12345");
    request.setApiId("TestApi");
    request.setApiOrgId("TestOrg");
    request.setApiVersion("1.0");
    request.setDestination("/");
    request.setUrl("http://localhost:9999/");
    request.setType("TEST");
    IApiRequestExecutor prExecutor = engine.executor(request, new IAsyncResultHandler<IEngineResult>() {

        // At this point, we are either saying *fail* or *response connection is ready*
        @Override
        public void handle(IAsyncResult<IEngineResult> result) {
            IEngineResult er = result.getResult();
            // No exception occurred
            Assert.assertTrue(result.isSuccess());
            // The chain evaluation succeeded
            Assert.assertNotNull(er);
            Assert.assertTrue(!er.isFailure());
            Assert.assertNotNull(er.getApiResponse());
            // $NON-NLS-1$
            Assert.assertEquals("OK", er.getApiResponse().getMessage());
            er.bodyHandler(mockBodyHandler);
            er.endHandler(mockEndHandler);
        }
    });
    prExecutor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {

        @Override
        public void handle(ISignalWriteStream streamWriter) {
            streamWriter.write(mockBufferInbound);
            streamWriter.end();
        }
    });
    transmitHandler = new IAsyncHandler<Void>() {

        @Override
        public void handle(Void result) {
            // NB: This is cheating slightly for testing purposes, we don't have real async here.
            // Only now start writing stuff, so user has had opportunity to set handlers
            mockApiConnectionResponse.write(mockBufferOutbound);
            mockApiConnectionResponse.end();
        }
    };
    prExecutor.execute();
    // Request handler should receive the mock inbound buffer once only
    verify(mockApiConnection, times(1)).write(mockBufferInbound);
    // Ultimately user should receive the contrived response and end in order.
    InOrder order = inOrder(mockBodyHandler, mockEndHandler);
    order.verify(mockBodyHandler).handle(mockBufferOutbound);
    order.verify(mockEndHandler).handle((Void) null);
}
Also used : IApimanBuffer(io.apiman.gateway.engine.io.IApimanBuffer) IEngineResult(io.apiman.gateway.engine.IEngineResult) IEngine(io.apiman.gateway.engine.IEngine) IAsyncResultHandler(io.apiman.gateway.engine.async.IAsyncResultHandler) ApiRequest(io.apiman.gateway.engine.beans.ApiRequest) IApiConnectionResponse(io.apiman.gateway.engine.IApiConnectionResponse) ApiResponse(io.apiman.gateway.engine.beans.ApiResponse) RequiredAuthType(io.apiman.gateway.engine.auth.RequiredAuthType) IConnectorFactory(io.apiman.gateway.engine.IConnectorFactory) Client(io.apiman.gateway.engine.beans.Client) IApiRequestExecutor(io.apiman.gateway.engine.IApiRequestExecutor) IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) InOrder(org.mockito.InOrder) IConnectorConfig(io.apiman.gateway.engine.IConnectorConfig) ISignalWriteStream(io.apiman.gateway.engine.io.ISignalWriteStream) IApiConnector(io.apiman.gateway.engine.IApiConnector) Api(io.apiman.gateway.engine.beans.Api) Contract(io.apiman.gateway.engine.beans.Contract) Test(org.junit.Test)

Example 2 with IPluginRegistry

use of io.apiman.gateway.engine.IPluginRegistry in project apiman by apiman.

the class AbstractEngineFactory method createEngine.

/**
 * Call this to create a new engine. This method uses the engine
 * config singleton to create the engine.
 */
@Override
public final IEngine createEngine() {
    IPluginRegistry pluginRegistry = createPluginRegistry();
    IDataEncrypter encrypter = createDataEncrypter(pluginRegistry);
    CurrentDataEncrypter.instance = encrypter;
    IRegistry registry = createRegistry(pluginRegistry, encrypter);
    IComponentRegistry componentRegistry = createComponentRegistry(pluginRegistry);
    IConnectorFactory cfactory = createConnectorFactory(pluginRegistry);
    IPolicyFactory pfactory = createPolicyFactory(pluginRegistry);
    IMetrics metrics = createMetrics(pluginRegistry);
    IApiRequestPathParser pathParser = createRequestPathParser(pluginRegistry);
    List<IGatewayInitializer> initializers = createInitializers(pluginRegistry);
    for (IGatewayInitializer initializer : initializers) {
        initializer.initialize();
    }
    complete();
    return new EngineImpl(registry, pluginRegistry, componentRegistry, cfactory, pfactory, metrics, pathParser);
}
Also used : IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) IPolicyFactory(io.apiman.gateway.engine.policy.IPolicyFactory) IApiRequestPathParser(io.apiman.gateway.engine.IApiRequestPathParser) IComponentRegistry(io.apiman.gateway.engine.IComponentRegistry) IConnectorFactory(io.apiman.gateway.engine.IConnectorFactory) IGatewayInitializer(io.apiman.gateway.engine.IGatewayInitializer) IDataEncrypter(io.apiman.common.util.crypt.IDataEncrypter) IRegistry(io.apiman.gateway.engine.IRegistry) IMetrics(io.apiman.gateway.engine.IMetrics)

Example 3 with IPluginRegistry

use of io.apiman.gateway.engine.IPluginRegistry in project apiman by apiman.

the class VertxPluginRegistryTest method getFakePluginFromCustomRegistry.

/**
 * Test with custom configuration (pluginRepositories and pluginsDir) to download a fake plugin from a fake Maven repo
 *
 * @param context
 * @throws java.io.IOException
 */
@Test
public void getFakePluginFromCustomRegistry(TestContext context) throws java.io.IOException {
    Async waitForPlugin = context.async();
    // Preparing JSON config Object
    List<String> pluginRepositories = Arrays.asList(mavenServerUri.toString());
    String pluginsDir = "/tmp/plugins-test2";
    JsonObject jsonObject = new JsonObject(getJsonConfig(pluginRepositories, pluginsDir));
    // Delete temp folder
    File TempDir = new File(pluginsDir);
    if (TempDir.exists())
        FileUtils.deleteDirectory(TempDir);
    // Referenced values to test
    Map<String, String> expected = new LinkedHashMap<String, String>() {

        {
            put("pluginRepositories", String.join(",", pluginRepositories));
            put("pluginsDir", pluginsDir);
        }
    };
    // Loading VertX configuration
    VertxEngineConfig config = new VertxEngineConfig(jsonObject);
    Map<String, String> pluginRegistryConfig = config.getPluginRegistryConfig();
    // Assert that JSON config object contains the rights parameters
    Assert.assertThat(pluginRegistryConfig, is(expected));
    // Create a fake engine for test plugins loading
    TestVerticle v = new TestVerticle(config);
    // Get pluginRegistry from engine
    IPluginRegistry pluginRegistry = v.createPluginRegistry();
    // Define simple header policy plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);
    // Download the plugin
    pluginRegistry.loadPlugin(coordinates, result -> {
        if (result.isSuccess()) {
            // Get downloaded plugin
            Plugin plugin = result.getResult();
            // Assert that's the right plugin
            context.assertEquals(plugin.getCoordinates(), coordinates);
            // Assert plugin is in the right dir
            Path pluginPath = Paths.get(pluginsDir + "/io.apiman.test/testPlugin/1.0.0.Final/testPlugin.war");
            context.assertTrue(Files.exists(pluginPath));
            waitForPlugin.complete();
        } else {
            context.fail(result.getError());
        }
    });
    waitForPlugin.awaitSuccess();
}
Also used : IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) Path(java.nio.file.Path) JsonObject(io.vertx.core.json.JsonObject) Async(io.vertx.ext.unit.Async) VertxEngineConfig(io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) File(java.io.File) Plugin(io.apiman.common.plugin.Plugin) Test(org.junit.Test)

Example 4 with IPluginRegistry

use of io.apiman.gateway.engine.IPluginRegistry in project apiman by apiman.

the class VertxPluginRegistryTest method getFakePluginUnreachableRegistry.

/**
 * Test with custom configuration (pluginRepositories and pluginsDir) to download a fake plugin from a fake Maven repo
 * Despite a unreachable repository in the pluginRepositories array.
 *
 * @param context
 * @throws java.io.IOException
 */
@Test
public void getFakePluginUnreachableRegistry(TestContext context) throws java.io.IOException {
    Async waitForPlugin = context.async();
    // Preparing JSON config Object with 2 custom repo : a real and a fake
    List<String> pluginRepositories = Arrays.asList("https://unreachable.maven.org/maven2/", mavenServerUri.toString());
    String pluginsDir = "/tmp/plugins-test3";
    JsonObject jsonObject = new JsonObject(getJsonConfig(pluginRepositories, pluginsDir));
    // Delete temp folder
    File TempDir = new File(pluginsDir);
    if (TempDir.exists())
        FileUtils.deleteDirectory(TempDir);
    // Referenced values to test
    Map<String, String> expected = new LinkedHashMap<String, String>() {

        {
            put("pluginRepositories", String.join(",", pluginRepositories));
            put("pluginsDir", pluginsDir);
        }
    };
    // Loading VertX configuration
    VertxEngineConfig config = new VertxEngineConfig(jsonObject);
    Map<String, String> pluginRegistryConfig = config.getPluginRegistryConfig();
    // Assert that JSON config object contains the rights parameters
    Assert.assertThat(pluginRegistryConfig, is(expected));
    // Create a fake engine for test plugins loading
    TestVerticle v = new TestVerticle(config);
    // Get pluginRegistry from engine
    IPluginRegistry pluginRegistry = v.createPluginRegistry();
    // Define simple header policy plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);
    // Download the plugin
    pluginRegistry.loadPlugin(coordinates, result -> {
        if (result.isSuccess()) {
            // Get downloaded plugin
            Plugin plugin = result.getResult();
            // Assert that's the right plugin
            context.assertEquals(plugin.getCoordinates(), coordinates);
            // Assert plugin is in the right dir
            Path pluginPath = Paths.get(pluginsDir + "/io.apiman.test/testPlugin/1.0.0.Final/testPlugin.war");
            context.assertTrue(Files.exists(pluginPath));
            waitForPlugin.complete();
        } else {
            context.fail(result.getError());
        }
    });
    waitForPlugin.awaitSuccess();
}
Also used : IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) Path(java.nio.file.Path) JsonObject(io.vertx.core.json.JsonObject) Async(io.vertx.ext.unit.Async) VertxEngineConfig(io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) File(java.io.File) Plugin(io.apiman.common.plugin.Plugin) Test(org.junit.Test)

Example 5 with IPluginRegistry

use of io.apiman.gateway.engine.IPluginRegistry in project apiman by apiman.

the class VertxPluginRegistryTest method getRealPluginFromCustomRegistry.

/**
 * Test with custom configuration (pluginRepositories and pluginsDir) to download a real plugin from Maven Central
 *
 * @param context
 * @throws java.io.IOException
 */
@Test
public void getRealPluginFromCustomRegistry(TestContext context) throws java.io.IOException {
    Async waitForPlugin = context.async();
    // Preparing JSON config Object
    List<String> pluginRepositories = Arrays.asList("https://repo1.maven.org/maven2/");
    String pluginsDir = "/tmp/plugins-test1";
    JsonObject jsonObject = new JsonObject(getJsonConfig(pluginRepositories, pluginsDir));
    // Delete temp folder
    File TempDir = new File(pluginsDir);
    if (TempDir.exists())
        FileUtils.deleteDirectory(TempDir);
    // Referenced values to test
    Map<String, String> expected = new LinkedHashMap<String, String>() {

        {
            put("pluginRepositories", String.join(",", pluginRepositories));
            put("pluginsDir", pluginsDir);
        }
    };
    // Loading VertX configuration
    VertxEngineConfig config = new VertxEngineConfig(jsonObject);
    Map<String, String> pluginRegistryConfig = config.getPluginRegistryConfig();
    // Assert that JSON config object contains the rights parameters
    Assert.assertThat(pluginRegistryConfig, is(expected));
    // Create a fake engine for test plugins loading
    TestVerticle v = new TestVerticle(config);
    // Get pluginRegistry from engine
    IPluginRegistry pluginRegistry = v.createPluginRegistry();
    // Define simple header policy plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(RealPluginCoordinates);
    // Download the plugin
    pluginRegistry.loadPlugin(coordinates, result -> {
        if (result.isSuccess()) {
            // Get downloaded plugin
            Plugin plugin = result.getResult();
            // Assert that's the right plugin
            context.assertEquals(plugin.getCoordinates(), coordinates);
            // Assert plugin is in the right dir
            Path pluginPath = Paths.get(pluginsDir + "/io.apiman.plugins/apiman-plugins-simple-header-policy/1.5.1.Final/apiman-plugins-simple-header-policy.war");
            context.assertTrue(Files.exists(pluginPath));
            waitForPlugin.complete();
        } else {
            context.fail(result.getError());
        }
    });
    waitForPlugin.awaitSuccess();
}
Also used : IPluginRegistry(io.apiman.gateway.engine.IPluginRegistry) Path(java.nio.file.Path) JsonObject(io.vertx.core.json.JsonObject) Async(io.vertx.ext.unit.Async) VertxEngineConfig(io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig) PluginCoordinates(io.apiman.common.plugin.PluginCoordinates) File(java.io.File) Plugin(io.apiman.common.plugin.Plugin) Test(org.junit.Test)

Aggregations

IPluginRegistry (io.apiman.gateway.engine.IPluginRegistry)6 Test (org.junit.Test)5 Plugin (io.apiman.common.plugin.Plugin)4 PluginCoordinates (io.apiman.common.plugin.PluginCoordinates)4 VertxEngineConfig (io.apiman.gateway.platforms.vertx3.common.config.VertxEngineConfig)4 JsonObject (io.vertx.core.json.JsonObject)4 Async (io.vertx.ext.unit.Async)4 File (java.io.File)4 Path (java.nio.file.Path)4 IConnectorFactory (io.apiman.gateway.engine.IConnectorFactory)2 PluginUtils (io.apiman.common.plugin.PluginUtils)1 IDataEncrypter (io.apiman.common.util.crypt.IDataEncrypter)1 IApiConnectionResponse (io.apiman.gateway.engine.IApiConnectionResponse)1 IApiConnector (io.apiman.gateway.engine.IApiConnector)1 IApiRequestExecutor (io.apiman.gateway.engine.IApiRequestExecutor)1 IApiRequestPathParser (io.apiman.gateway.engine.IApiRequestPathParser)1 IComponentRegistry (io.apiman.gateway.engine.IComponentRegistry)1 IConnectorConfig (io.apiman.gateway.engine.IConnectorConfig)1 IEngine (io.apiman.gateway.engine.IEngine)1 IEngineResult (io.apiman.gateway.engine.IEngineResult)1