Search in sources :

Example 6 with Contract

use of io.apiman.gateway.engine.beans.Contract 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 7 with Contract

use of io.apiman.gateway.engine.beans.Contract in project apiman by apiman.

the class SecureRegistryWrapper method registerClient.

/**
 * @see io.apiman.gateway.engine.IRegistry#registerClient(io.apiman.gateway.engine.beans.Client, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */
@Override
public void registerClient(Client client, IAsyncResultHandler<Void> handler) {
    Set<Contract> contracts = client.getContracts();
    if (contracts != null) {
        for (Contract contract : contracts) {
            List<Policy> policies = contract.getPolicies();
            encryptPolicies(client.getOrganizationId(), client.getClientId(), client.getVersion(), EntityType.ClientApp, policies);
        }
    }
    delegate.registerClient(client, handler);
    if (contracts != null) {
        for (Contract contract : contracts) {
            List<Policy> policies = contract.getPolicies();
            decryptPolicies(client.getOrganizationId(), client.getClientId(), client.getVersion(), EntityType.ClientApp, policies);
        }
    }
}
Also used : Policy(io.apiman.gateway.engine.beans.Policy) Contract(io.apiman.gateway.engine.beans.Contract) ApiContract(io.apiman.gateway.engine.beans.ApiContract)

Example 8 with Contract

use of io.apiman.gateway.engine.beans.Contract in project apiman by apiman.

the class SharedGlobalDataRegistry method getContract.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void getContract(String apiOrganizationId, String apiId, String apiVersion, String apiKey, IAsyncResultHandler<ApiContract> handler) {
    String apiIndex = getApiIndex(apiOrganizationId, apiId, apiVersion);
    Future apiFuture = Future.future();
    Future clientFuture = Future.future();
    objectMap.get(apiIndex, apiFuture.completer());
    objectMap.get(apiKey, clientFuture.completer());
    CompositeFuture.all(apiFuture, clientFuture).setHandler(compositeResult -> {
        if (compositeResult.succeeded()) {
            Api api = (Api) apiFuture.result();
            Client client = (Client) clientFuture.result();
            if (api == null) {
                Exception error = new ClientNotFoundException(Messages.i18n.format("InMemoryRegistry.NoClientForAPIKey", apiKey));
                handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            } else if (client == null) {
                Exception error = new ApiRetiredException(Messages.i18n.format("InMemoryRegistry.ApiWasRetired", apiId, apiOrganizationId));
                handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            } else {
                Optional<Contract> matchedOpt = client.getContracts().stream().filter(contract -> contract.matches(apiOrganizationId, apiId, apiVersion)).findFirst();
                if (matchedOpt.isPresent()) {
                    Contract contract = matchedOpt.get();
                    ApiContract apiContract = new ApiContract(api, client, contract.getPlan(), contract.getPolicies());
                    handler.handle(AsyncResultImpl.create(apiContract));
                } else {
                    Exception error = new NoContractFoundException(// $NON-NLS-1$
                    Messages.i18n.format(// $NON-NLS-1$
                    "InMemoryRegistry.NoContractFound", client.getClientId(), api.getApiId()));
                    handler.handle(AsyncResultImpl.create(error, ApiContract.class));
                }
            }
        } else {
            handler.handle(AsyncResultImpl.create(compositeResult.cause()));
        }
    });
}
Also used : NoContractFoundException(io.apiman.gateway.engine.beans.exceptions.NoContractFoundException) ApiRetiredException(io.apiman.gateway.engine.beans.exceptions.ApiRetiredException) ClientNotFoundException(io.apiman.gateway.engine.beans.exceptions.ClientNotFoundException) Optional(java.util.Optional) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future) Api(io.apiman.gateway.engine.beans.Api) Client(io.apiman.gateway.engine.beans.Client) Contract(io.apiman.gateway.engine.beans.Contract) ApiContract(io.apiman.gateway.engine.beans.ApiContract) ApiRetiredException(io.apiman.gateway.engine.beans.exceptions.ApiRetiredException) ClientNotFoundException(io.apiman.gateway.engine.beans.exceptions.ClientNotFoundException) NoContractFoundException(io.apiman.gateway.engine.beans.exceptions.NoContractFoundException) ApiNotFoundException(io.apiman.gateway.engine.beans.exceptions.ApiNotFoundException) ApiContract(io.apiman.gateway.engine.beans.ApiContract)

Example 9 with Contract

use of io.apiman.gateway.engine.beans.Contract in project apiman by apiman.

the class CachingJdbcRegistry method getContract.

/**
 * @see io.apiman.gateway.engine.jdbc.JdbcRegistry#getContract(java.lang.String, java.lang.String, java.lang.String, java.lang.String, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */
@Override
public void getContract(String apiOrganizationId, String apiId, String apiVersion, String apiKey, IAsyncResultHandler<ApiContract> handler) {
    Client client = null;
    Api api = null;
    try {
        synchronized (mutex) {
            client = getClient(apiKey);
            api = getApi(apiOrganizationId, apiId, apiVersion);
        }
        if (client == null) {
            // $NON-NLS-1$
            Exception error = new NoContractFoundException(Messages.i18n.format("JdbcRegistry.NoClientForAPIKey", apiKey));
            handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            return;
        }
        if (api == null) {
            throw new ApiRetiredException(// $NON-NLS-1$
            Messages.i18n.format(// $NON-NLS-1$
            "JdbcRegistry.ApiWasRetired", apiId, apiOrganizationId));
        }
        Contract matchedContract = null;
        for (Contract contract : client.getContracts()) {
            if (contract.matches(apiOrganizationId, apiId, apiVersion)) {
                matchedContract = contract;
                break;
            }
        }
        if (matchedContract == null) {
            throw new NoContractFoundException(// $NON-NLS-1$
            Messages.i18n.format(// $NON-NLS-1$
            "JdbcRegistry.NoContractFound", client.getClientId(), api.getApiId()));
        }
        ApiContract contract = new ApiContract(api, client, matchedContract.getPlan(), matchedContract.getPolicies());
        handler.handle(AsyncResultImpl.create(contract));
    } catch (Exception e) {
        handler.handle(AsyncResultImpl.create(e, ApiContract.class));
    }
}
Also used : NoContractFoundException(io.apiman.gateway.engine.beans.exceptions.NoContractFoundException) ApiRetiredException(io.apiman.gateway.engine.beans.exceptions.ApiRetiredException) Api(io.apiman.gateway.engine.beans.Api) Client(io.apiman.gateway.engine.beans.Client) Contract(io.apiman.gateway.engine.beans.Contract) ApiContract(io.apiman.gateway.engine.beans.ApiContract) NoContractFoundException(io.apiman.gateway.engine.beans.exceptions.NoContractFoundException) SQLException(java.sql.SQLException) ApiRetiredException(io.apiman.gateway.engine.beans.exceptions.ApiRetiredException) ApiContract(io.apiman.gateway.engine.beans.ApiContract)

Example 10 with Contract

use of io.apiman.gateway.engine.beans.Contract in project apiman by apiman.

the class JdbcRegistry method getContract.

/**
 * @see io.apiman.gateway.engine.IRegistry#getContract(java.lang.String, java.lang.String, java.lang.String, java.lang.String, io.apiman.gateway.engine.async.IAsyncResultHandler)
 */
@Override
public void getContract(String apiOrganizationId, String apiId, String apiVersion, String apiKey, IAsyncResultHandler<ApiContract> handler) {
    try {
        Client client = getClientInternal(apiKey);
        Api api = getApiInternal(apiOrganizationId, apiId, apiVersion);
        if (client == null) {
            // $NON-NLS-1$
            Exception error = new ClientNotFoundException(Messages.i18n.format("JdbcRegistry.NoClientForAPIKey", apiKey));
            handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            return;
        }
        if (api == null) {
            Exception error = new ApiRetiredException(// $NON-NLS-1$
            Messages.i18n.format(// $NON-NLS-1$
            "JdbcRegistry.ApiWasRetired", apiId, apiOrganizationId));
            handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            return;
        }
        Contract matchedContract = null;
        for (Contract contract : client.getContracts()) {
            if (contract.matches(apiOrganizationId, apiId, apiVersion)) {
                matchedContract = contract;
                break;
            }
        }
        if (matchedContract == null) {
            Exception error = new NoContractFoundException(// $NON-NLS-1$
            Messages.i18n.format(// $NON-NLS-1$
            "JdbcRegistry.NoContractFound", client.getClientId(), api.getApiId()));
            handler.handle(AsyncResultImpl.create(error, ApiContract.class));
            return;
        }
        ApiContract contract = new ApiContract(api, client, matchedContract.getPlan(), matchedContract.getPolicies());
        handler.handle(AsyncResultImpl.create(contract));
    } catch (Exception e) {
        handler.handle(AsyncResultImpl.create(e, ApiContract.class));
    }
}
Also used : NoContractFoundException(io.apiman.gateway.engine.beans.exceptions.NoContractFoundException) ApiRetiredException(io.apiman.gateway.engine.beans.exceptions.ApiRetiredException) ClientNotFoundException(io.apiman.gateway.engine.beans.exceptions.ClientNotFoundException) Api(io.apiman.gateway.engine.beans.Api) Client(io.apiman.gateway.engine.beans.Client) Contract(io.apiman.gateway.engine.beans.Contract) ApiContract(io.apiman.gateway.engine.beans.ApiContract) ApiRetiredException(io.apiman.gateway.engine.beans.exceptions.ApiRetiredException) SQLException(java.sql.SQLException) PublishingException(io.apiman.gateway.engine.beans.exceptions.PublishingException) RegistrationException(io.apiman.gateway.engine.beans.exceptions.RegistrationException) ClientNotFoundException(io.apiman.gateway.engine.beans.exceptions.ClientNotFoundException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) NoContractFoundException(io.apiman.gateway.engine.beans.exceptions.NoContractFoundException) ApiNotFoundException(io.apiman.gateway.engine.beans.exceptions.ApiNotFoundException) ApiContract(io.apiman.gateway.engine.beans.ApiContract)

Aggregations

Contract (io.apiman.gateway.engine.beans.Contract)15 Client (io.apiman.gateway.engine.beans.Client)13 Api (io.apiman.gateway.engine.beans.Api)11 ApiContract (io.apiman.gateway.engine.beans.ApiContract)9 ApiRetiredException (io.apiman.gateway.engine.beans.exceptions.ApiRetiredException)8 NoContractFoundException (io.apiman.gateway.engine.beans.exceptions.NoContractFoundException)8 ClientNotFoundException (io.apiman.gateway.engine.beans.exceptions.ClientNotFoundException)7 PublishingException (io.apiman.gateway.engine.beans.exceptions.PublishingException)7 ApiNotFoundException (io.apiman.gateway.engine.beans.exceptions.ApiNotFoundException)6 ApiGatewayBean (io.apiman.manager.api.beans.apis.ApiGatewayBean)5 ApiVersionBean (io.apiman.manager.api.beans.apis.ApiVersionBean)5 ClientVersionBean (io.apiman.manager.api.beans.clients.ClientVersionBean)5 StorageException (io.apiman.manager.api.core.exceptions.StorageException)5 IGatewayLink (io.apiman.manager.api.gateway.IGatewayLink)5 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)5 Policy (io.apiman.gateway.engine.beans.Policy)4 RegistrationException (io.apiman.gateway.engine.beans.exceptions.RegistrationException)4 ContractBean (io.apiman.manager.api.beans.contracts.ContractBean)4 GatewayBean (io.apiman.manager.api.beans.gateways.GatewayBean)4