DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Thrift API Gateway — Part 2: Spring Domination

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.

Aleksandr Tarasov user avatar by
Aleksandr Tarasov
·
Jan. 28, 16 · Tutorial
Like (4)
Save
Tweet
Share
8.14K Views

Join the DZone community and get the full member experience.

Join For Free

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

API Spring Framework Thrift (protocol) zuul Filter (software)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top Authentication Trends to Watch Out for in 2023
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • How to Cut the Release Inspection Time From 4 Days to 4 Hours
  • Using QuestDB to Collect Infrastructure Metrics

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: