Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Conditional Method chaining in Java 8

I have a spring security config method. I want a particular method to be chained antMatchers("/**/**").permitAll() only if a condition matches. something like this {dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} . Ofcourse it's not a valid syntax , what is the MOST CONSISE way of doing it . Looking for a menimum coding .

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors().disable()
            .authorizeRequests()
            {dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} //dev only. NEVER enable on prod 
                .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/api/signin")
                .successHandler(authSuccessHandler())
                .failureHandler(authFailureHandler())
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
like image 790
sapy Avatar asked Jan 11 '19 18:01

sapy


1 Answers

The only way is to assign the intermediate object to a variable.

WhateverAuthorizeRequestsReturns partial = http
    .csrf().disable()
    .cors().disable()
    .authorizeRequests();

if (dev) // note: you don't need 'dev == true' like you had
{
    partial.someOptionalThing();
    // if the type is immutable then you need to reassign e.g.:
    // partial = partial.someOptionalThing()
}

partial.something()
    .somethingElse()
    .andTheRest();
like image 89
Michael Avatar answered Oct 13 '22 03:10

Michael