Over a million developers have joined DZone.

Thrift API Gateway — Part 2: Spring Domination

In the first part of this series, we investigated how to prepare thrift packets for exchanging security token by user information. In this part, we'll take a deeper dive into Spring.

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

In the first part of this series, we investigated how to prepare thrift packets for exchanging security token by user information. Library was written and its time to move forward.

One Annotation to Rule Them All

Annotation-driven development is the Spring-way. Spring can be configured by many annotations that incapsulate tons of logic from your eyes. The first step consists of annotation creation that loads configuration with beans and properties.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(ThriftGatewayConfiguration.class)
public @interface EnableThriftGateway {  
}

ThriftGatewayConfiguration consists of some beans for our needs. It will be created sometime later.

Intro to Zuul

Netflix Zuul is the edge service that routes and processes any HTTP requests from the frontend or a mobile device and streams theirs to the backend. It has the system of chaining filters. Each filter adds new functionality. Even writing a response is a filter. There are three filter types:

  • pre-filters
  • route
  • post-filters

Each type has an order. Pre-filters are executing first. Next, route filters and post-filters are executing last. Each filter has its own order, too.

Lets create it.

public class AuthenticationZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequestWrapper request = (HttpServletRequestWrapper) ctx.getRequest();

        //actions are here

        return null;
    }
}

Connect it to Spring container as a bean.

@Configuration
public class ThriftGatewayConfiguration {  
    @Bean
    public AuthenticationZuulFilter authenticationZuulFilter() {
        return new AuthenticationZuulFilter();
    }
}

Magic Configuration

Okay, let's do some magic. Remember that configuration that we described in first part of the article? Implement it as write like below:

@Configuration
public class ThriftGatewayConfiguration {  
    @Bean
    @ConditionalOnMissingBean(AuthTokenExchanger.class)
    AuthTokenExchanger authTokenExchanger() {
        throw new UnsupportedOperationException("You should implement AuthTokenExchanger bean");
    }

    @Bean
    @ConditionalOnMissingBean(TProtocolFactory.class)
    TProtocolFactory thriftProtocolFactory() {
        return new TBinaryProtocol.Factory();
    }

    @Bean
    public AuthenticationZuulFilter authenticationZuulFilter() {
        return new AuthenticationZuulFilter();
    }
}

Annotation ConditionalOnMissingBean prevents default bean creation if a bean with a conditional class is defined in you project. AuthTokenExchanger is needed for an exchange external token to internal that we considered in the previous article. By default, for security reasons we can't implement any logic and raise exception. So, in the project the developer must implement his/her own logic and it is its responsibility. Protocol translation is not supported yet, so only one protocol is needed to be registered as a thriftProtocolFactory bean. AuthenticationZuulFilter have been registered earler.

Filter Internals

It's time to dive deeper to AuthenticationZuulFilter realization. First, request context should be got:

RequestContext ctx = RequestContext.getCurrentContext();  
HttpServletRequestWrapper request = (HttpServletRequestWrapper) ctx.getRequest();  

Next step is creating MessageTranslator:

MessageTransalator messageTransalator = new MessageTransalator(protocolFactory, authTokenExchanger);  

Positive scenario contains process request data, write it to the requestEntity property of context and set new content length instead of origin:

byte[] processed = messageTransalator.process(request.getContentData());  
ctx.set("requestEntity", new ByteArrayInputStream(processed));  
ctx.setOriginContentLength(processed.length);  

If authentification or other thrift specific exception is raised, we need to process this exception with MessageTranslator and return it to the client:

ctx.setSendZuulResponse(false);  
ctx.setResponseDataStream(new ByteArrayInputStream(new byte[]{}));

try {  
ctx.getResponse().getOutputStream().write(messageTransalator.processError(e));
} catch (Exception e1) {
log.error("unexpected error", e1);
    ctx.setResponseStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}

There are some tricks with context properties necessary for preventing further service call processing. First, ctx.setSendZuulResponse(false) prevents GZIPping response. Thrift clients may fail from this type of package. And second, ctx.setResponseDataStream(new ByteArrayInputStream(new byte[]{})) is needed to pass should filter in the Zuul response filter.

If any not-thrift exception is raised then we need to do the same things without writing response because there is nothing to return.

Examples

You can find examples in this repository on GitHub. In our example, very simple logic is implemented:

@Bean
AuthTokenExchanger authTokenExchanger() {  
    return new AuthTokenExchanger<Token, TName>() {
        @Override
        public Token createEmptyAuthToken() {
            return new Token();
        }

        @Override
        public TName process(Token authToken) throws TException {
            if (authToken.getValue().equals("heisours")) {
                return new TName("John", "Smith");
            }

            throw new UnauthorizedException(ErrorCode.WRONG_LOGIN_OR_PASSWORD);
        }
    };
}

And, we may test it in a very native Java way (thanks thrift):

@Test
public void testSimpleCall() throws Exception {  
    assertEquals("Hello John Smith", client.greet(new Token("heisours")));
}

@Test(expected = UnauthorizedException.class)
public void testUnauthorizedCall() throws Exception {  
    client.greet(new Token("heisnot"));
}

Links

You can discover and fork projects on GitHub: https://github.com/aatarasoff/spring-thrift-api-gateway

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
java ,spring ,thrift ,api ,zuul

Published at DZone with permission of Aleksandr Tarasov. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}