12 Aralık 2017 Salı

SpringData Jdbc Jdbc BeanPropertyRowMapper Sınıfı

Giriş
Açıklaması şöyle. Yani RowMapper arayüzünü kullanmak daha iyi
To have tight integration between Java and ResultSet of JDBC, Spring JDBC has a RowMapper interface. A developer can either create a custom class or use BeanPropertyRowMapper, which reduces the boilerplate; however, the entity should have a public getter and setter; it might get an encapsulation issue besides it provides convenience rather than high performance. For best performance, consider using a custom RowMapper implementation.
Örnek
Elimizde bir model sınıfı olsun.
public class FooModel {

  private Long id;
  private String name;

  public InvModel() {
    super();
  }

}
Şöyle yaparız.
RowMapper<InvModel> MAPPER = BeanPropertyRowMapper.newInstance(FooModel.class);

5 Aralık 2017 Salı

SpringSecurity OAuth2 TokenEndpoint Sınıfı

Giriş
Açıklaması şöyle
Clients must be authenticated using a Spring Security Authentication to access this endpoint, and the client id is extracted from the authentication token. The best way to arrange this (as per the OAuth2 spec) is to use HTTP basic authentication for this endpoint with standard Spring Security support.

28 Kasım 2017 Salı

HttpSessionRequestCache Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
constructor
Şöyle yaparız.
HttpSessionRequestCache httpSessionRequestCache = new HttpSessionRequestCache();
setCreateSessionAllowed metodu
Şöyle yaparız.
httpSessionRequestCache.setCreateSessionAllowed(false);
Diğer
Kullanmak için şöyle yaparız.
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
  public HttpSessionRequestCache getHttpSessionRequestCache() {
    HttpSessionRequestCache httpSessionRequestCache = new HttpSessionRequestCache();
    httpSessionRequestCache.setCreateSessionAllowed(false);
    return httpSessionRequestCache;
  }

  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http.requestCache().requestCache(getHttpSessionRequestCache());
}

27 Kasım 2017 Pazartesi

InheritableThreadLocal Sınıfı

Giriş
Açıklaması şöyle
This class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values.
Örnek
Şöyle yaparız.
@Service
class A{

  private InheritableThreadLocal<Student> student;

}

10 Kasım 2017 Cuma

SpringScheduling TaskScheduler Arayüzü - Dynamic Task Scheduling İçin Kullanılır

Giriş
Şu satırı dahil ederiz.
import org.springframework.scheduling.TaskScheduler;
Bu arayüzü gerçekleştiren sınıflar şöyle
ConcurrentTaskScheduler, 
DefaultManagedTaskScheduler, 
TimerManagerTaskScheduler

Bu sınıf scheduleXXX() şeklinde metodlar sağlar. Temel amacı bir işin gelecekte çağrılması için teslim edilmesini sağlamak. İşi çalıştıran sınıflar genellikle bir ThreadPool kullandıkları için aynı zamanda TaskExecutor arayüzünü de gerçekleştirirler.

Tanımlama
Örnek
Şöyle yaparız.
<task:scheduler id="scheduler" pool-size="10" />
<task:executor id="executor" keep-alive="3600" pool-size="100-200"
               queue-capacity="500" rejection-policy="CALLER_RUNS" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
schedule metodu - Runnable + Date
Örnek
Şöyle yaparız
taskScheduler.schedule(
  () -> ...,
  new Date(System.currentTimeMillis() + 3000)
);
schedule metodu - Runnable + Trigger
Trigger arayüzü işin bir sonraki çalışma zamanını hesaplar.
Bu metod ScheduledFuture nesnesi döner.
Örnek
Şöyle yaparız.
scheduler.schedule(runnable, new CronTrigger("0 15 9-17 * * MON-FRI"));
Örnek
Şöyle yaparız
@Service
public class TaskSchedulingService {

  @Autowired
  private TaskScheduler taskScheduler;

  Map<String, ScheduledFuture<?>> jobsMap = new HashMap<>();

  public void scheduleATask(String jobId, Runnable runnable String cronExpression) {
    ScheduledFuture<?> scheduledTask = taskScheduler.schedule(runnable, 
      new CronTrigger(cronExpression,
TimeZone.getTimeZone(TimeZone.getDefault().getID())));

    jobsMap.put(jobId, scheduledTask);
  }

  public void removeScheduledTask(String jobId) {
    ScheduledFuture<?> scheduledTask = jobsMap.get(jobId);
    if(scheduledTask != null) {
      scheduledTask.cancel(true);
      jobsMap.put(jobId, null);
    }
  }
}
scheduleWithFixedDelay metodu
Örnek
Şöyle yaparız
taskScheduler.scheduleWithFixedDelay(() -> ..., 1000);

7 Kasım 2017 Salı

SpringSecurity CustomAuthenticationProvider Örneği

Giriş
Açıklaması şöyle. Yani Spring Security ile kendi AuthenticationProvider nesnemi kullanabilirim.
You can implement the authentication provider and build your custom authentication. public class customAuth implements AuthenticationProvider then override the authenticate method
Kendi AuthenticationProvider nesnemi takmak için şöyle yaparız
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(myFooAuthenticationProvider);
    auth.authenticationProvider(myBarAuthenticationProvider);
  }
}
Tanımlama
Şöyle yaparız
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
  ...
}
authenticate metodu
- Eğer kullanıcının şifresi yanlış, blocklanmış vs gibi şeyleri tespit edersek AuthenticationException fırlatırız. Örneğin BadCredentialsException
- Eğer authentication işlemini pas geçmek istiyorsak null döneriz
- Eğer kullanıcıyı doğrularsak UsernamePasswordAuthenticationToken nesnesi döneriz.

Örnek
Şöyle yaparız. Kodda parametre olarak geçilen authentication nesnesine yeni değer atanıyor gibi gösterilse bile önemli değil. Sadece yeni nesne dönmek yeterli.
@Override
public Authentication authenticate(Authentication authentication) throws 
  AuthenticationException {

  String name = authentication.getName();
  String password = authentication.getCredentials().toString();
  

  List<SimpleGrantedAuthority> auths = ...;
  authentication = new UsernamePasswordAuthenticationToken(name, password, auths);
  return authentication;
}
Örnek
Şöyle yaparız.
@Component
public class DbAuthProvider implements AuthenticationProvider {
  private final UserDetailsService userDetailsService;
  private final PasswordEncoder passwordEncoder;
   ...

  @Override
  public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
    if (!StringUtils.endsWithIgnoreCase(authentication.getPrincipal().toString(),
"@dbauth.com")) {
      // this user is not supported by DB authentication
      return null;
    }
    UserDetails user = userDetailsService
.loadUserByUsername(authentication.getPrincipal().toString());
    String rawPw = authentication.getCredentials() == null ? null :
authentication.getCredentials().toString();
    if (passwordEncoder.matches(rawPw, user.getPassword())) {
      
       return new UsernamePasswordAuthenticationToken(user.getUsername(),
rawPw,Collections.emptyList());
    } else {
      throw new BadCredentialsException("Bad password");
    }
  }
  @Override
  public boolean supports(Class<?> aClass) {
    return aClass.isAssignableFrom(  }
}