23 Haziran 2020 Salı

SpringBatch SimpleJobLauncher Sınıfı - Job Nesnesini Belirtilen JobParameters İle Çalıştırır

Giriş
run() metodu aracılığıyla belirtilen Job nesnesini belirtilen JobParameters ile çalıştırır.

Tanımlama
Örnek
Şöyle yaparız.
<bean id="jobLauncher"
     class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
    <property name="jobRepository" ref="jobRepository" />
    <property name="taskExecutor">
        <bean class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
    </property>
</bean>
Örnek
Şöyle yaparız.
@Bean
public JobLauncher simpleJobLauncher() throws Exception {
  SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
  ...
  return jobLauncher;
}
Kullanım
Örnek
Elimizde bir tane Job bean olsun. Job nesnesi normalde bean olmak zorunda değil.
@Bean
public Step step1() {
  return stepBuilderFactory.get("step1")
    .<Customer, Customer> chunk(1000)
    .reader(customerItemReader())
    .writer(customerItemWriter())
    .build();
}


@Bean
public Job job() {
  return jobBuilderFactory.get("job")
    .start(step1())
    .build();
}  
Şöyle yaparız
@EnableBatchProcessing
public class SpringBatchApplication implements CommandLineRunner {

  @Autowired
  private JobLauncher jobLauncher;

  @Autowired
  private Job job;

  public static void main(String[] args) {
    SpringApplication.run(SpringBatchApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    JobParameters jobParameters = new JobParametersBuilder()
      .addString("UUID", UUID.randomUUID().toString())
      .toJobParameters();

    JobExecution execution = jobLauncher.run(job, jobParameters);
    System.out.println("STATUS :: "+execution.getStatus());
   }
}
constructor
Şöyle yaparız.
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
afterPropertiesSet metodu
Şöyle yaparız.
jobLauncher.afterPropertiesSet();
run metodu
Metodun imzası şöyle. JobExecution nesnesi döner.
public JobExecution run(Job job, JobParameters jobParameters)
  throws JobExecutionAlreadyRunningException, JobRestartException,
         JobInstanceAlreadyCompleteException, JobParametersInvalidException
Örnek
Şöyle yaparız
Job job =  ...;
JobParameters jobParameters = ...;
try {
  JobExecution jobExecution = jobLauncher.run(job, jobParameters);
} catch (JobExecutionAlreadyRunningException | JobRestartException
   | JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
  ...
}
Örnek
Elimizde şöyle bir kod olsun
JobParametersBuilder paramsBuilder = new JobParametersBuilder();
paramsBuilder.addString("delimiter", "yourCustomDelimiter");
Şöyle yaparız.
jobLauncher.run(job, paramsBuilder.toJobParameters());
Örnek
Controller içinde şöyle yaparız.
@Autowired
JobLauncher jobLauncher;

@RequestMapping(value="/trigger-job", method = RequestMethod.GET)
public Long workHard() throws Exception {
  JobParameters jobParameters = new JobParametersBuilder().
    addLong("time", System.currentTimeMillis())
    .toJobParameters();
  JobExecution jobExecution = jobLauncher.run(myJob, jobParameters);
  ...
}
setJobRepository metodu
Örnek
Şöyle yaparız.
@Configuration
public class BatchConfig {

  @Autowired
  JobRepository jobRepository;


  @Bean
  public JobLauncher simpleJobLauncher() throws Exception {
    SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
    jobLauncher.setJobRepository(jobRepository);
    ...
    return jobLauncher;
  }
}
setTaskExecutor metodu
Örnek
Şöyle yaparız.
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
Örnek
Şöyle yaparız.
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
  ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
  taskExecutor.setCorePoolSize(15);
  taskExecutor.setMaxPoolSize(20);
  taskExecutor.setQueueCapacity(30);
  return taskExecutor;
}

@Bean
public JobLauncher jobLauncher(ThreadPoolTaskExecutor taskExecutor,
  JobRepository jobRepository) {
  SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
  jobLauncher.setTaskExecutor(taskExecutor);
  jobLauncher.setJobRepository(jobRepository);
  return jobLauncher;
}


SpringBatch FlatFileItemReaderBuilder Sınıfı - Dosya Okur

Giriş
Şu satırı dahil ederiz
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
Bu sınıf ile bir FlatFileItemReader yani ItemReader yaratılır.

setLineMapper metodu - DefaultLineMapper
DefaultLineMapper verilebilir.

Örnek - FieldSetMapper'dan Kalıtım
Kendi Customer sınıfımızı CSV dosyasından okumak için şöyle yaparız.
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;

@Bean
public FlatFileItemReader<Customer> customerItemReader(){

  FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
  reader.setLinesToSkip(1);
  reader.setResource(new ClassPathResource("/data/customer.csv"));

  DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
  tokenizer.setNames(new String[] {"id", "firstName", "lastName", "birthdate"});

  DefaultLineMapper<Customer> customerLineMapper = new DefaultLineMapper<>();
  customerLineMapper.setLineTokenizer(tokenizer);
  customerLineMapper.setFieldSetMapper(new CustomerFieldSetMapper());
  customerLineMapper.afterPropertiesSet();

  reader.setLineMapper(customerLineMapper);
  return reader;
}
Kendi Customer sınıfımızı doldurmak için şöyle yaparız
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

public class CustomerFieldSetMapper implements FieldSetMapper<Customer> {

  @Override
  public Customer mapFieldSet(FieldSet fieldSet) throws BindException {
    return Customer.builder()
      .id(fieldSet.readLong("id"))
      .firstName(fieldSet.readRawString("firstName"))
      .lastName(fieldSet.readRawString("lastName"))
      .birthdate(fieldSet.readRawString("birthdate"))
      .build();
  }
}
fieldSetMapper metodu
setLineMapper() ile verilen nesne yerine kullanılabilir

Örnek - Lambda
Şöyle yaparız
// the FileReader takes the path to the file as parameters
@StepScope
@Bean
public FlatFileItemReader<Title> titleCsvReaderString inputFile){
  return new FlatFileItemReaderBuilder<Title>()
    .name("titles.csv reader")
    .resource(new FileSystemResource(inputFile))
    .delimited()
    .delimiter(",")
    .names(new String[]{"id",
                        "title",
                        "type",
                        "description",
                        "release_year",
                        "age_certification",
                        "runtime",
                        "genres",
                        "production_countries",
                        "seasons",
                        "imdb_id",
                        "imdb_score",
                        "imdb_votes",
                        "tmdb_popularity",
                        "tmdb_score"
      })
  .linesToSkip(1)
  .fieldSetMapper(fieldSet -> new Title(fieldSet.readString("id"),...))
  .beanMapperStrict(false)
  .build();
}
linesToSkip metodu
CSV gibi dosyalarda bazen ilk bir kaç satırı atlamak gerekebilir
Örnek
Şöyle yaparız
@Bean(name = "readerNewsReportCSVFile")
public ItemReader<NewsReport> readerNewsReportCSVFile(){
  return new FlatFileItemReaderBuilder<NewsReport>()
    .name("readerNewsReportCSVFile")
    .resource(new FileSystemResource("dataset/FakeNewsNet.csv"))
    .linesToSkip(1)
    .delimited()
    .names("title","news_url","source_domain","tweet_num","real")
    .targetType(NewsReport.class)
    .build();
}
names metodu
Okunacak alan isimlerini belirtir

resource metodu
Okunacak dosyayı belirtir
Örnek
Şöyle yaparız
@Bean
public FlatFileItemReader<String> textItemReader() {
  return new FlatFileItemReaderBuilder<String>()
    .name("textItemReader")
    .resource(phishingDatabaseLinksClassPathResource)
    .lineMapper(new PassThroughLineMapper())
    .build();
Örnek
Şöyle yaparız.
@Bean
public FlatFileItemReader<Voltage> reader() {
  return new FlatFileItemReaderBuilder<Voltage>()
    .name("voltItemReader")
    .resource(new ClassPathResource("Volts.csv"))
    .delimited()
    .names(new String[]{"volt", "time"})
    .lineMapper(lineMapper())
    .fieldSetMapper(new BeanWrapperFieldSetMapper<Voltage>() {{
      setTargetType(Voltage.class);
    }})
    .build();
}

17 Haziran 2020 Çarşamba

SpringBoot Test @DataJpaTest Anotasyonu

Giriş
Şu satırı dahil ederiz
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
Not : Bu anotasyon yerine gerçek veri tabanında test için @AutoConfigureTestDatabase tercih edilebilir.

Kullanım Amacı
1. Repository sınıflarının test edilmesi
2. Service sınıflarının test edilmesi

@DataJpaTest Anotasyonu Ne Yapar?
@WebMvcTest Anotasyonu gibi sadece bazı bean'leri yükler. Açıklaması şöyle. Dolayısıyla @SpringBootTest anotasyonunu kullanmaya gerek kalmaz.
The @DataJpaTest annotation will only provide the autoconfiguration required to test Spring Data JPA using an in-memory database such as H2.

This annotation is used instead of @SpringBootTest.
Bu anotasyonla bellekte bir veri tabanı oluşturulur. Açıklaması şöyle
By default, tests annotated with @DataJpaTest will use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource).
Eğer embedded bir veri tabanı bulamazsa şöyle bir exception fırlatır
java.lang.IllegalStateException : Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one the classpath or tune the replace attribute of @AutoConfigurationTestDatabase
Veri tabanının Oluşturulması
Test Suite çalışınca bir kere bellekte yeni bir veri tabanı oluşturulur. Bunun çıktısı olarak Spring logusu görülebilir. Daha sonra her  test sadece en başta yaratılmış olan bellekteki veri tabanına CRUD işlemi yapar. 

Transaction
Açıklaması şöyle
By default, @DataJpaTest tests are transactional and roll back at the end of each test.
Örnek
Rollback işlemi olmasın diye @Commit kullanılabilir. Şöyle yaparız
import org.springframework.test.annotation.Commit;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DataJpaTest(showSql = true)
class FooRepositoryTest {

  @Autowired
  private FooRepository repository;

  @Test
  @Order(1)
  @Commit
  void autoGenerateId() {

    FooEntity entity = new FooEntity();
    entity.setInstant(Instant.ofEpochMilli(0));
    repository.save(entity);
    assertEquals(entity.getId(), 1);

  }

  @Test
  @Order(2)
  void findById() {

    List<FooEntity> all = repository.findAll();
    assertFalse(all.isEmpty());
    FooEntity entity = all.get(0);
    assertEquals(entity.getInstant(), Instant.ofEpochMilli(0));
  }
}
Repository Sınıflarının Test Edilmesi

1. TestEntityManager Inject Edilmesini Sağlar
Açıklaması şöyle.
Using this annotation we can have a TestEntityManager injected on the test, and use it to change the database to a state in which it's possible to unit test our repository methods.
Test kodu içinde TestEntityManager @AutoWire edilebilir.

2. Repository Sınıflarının Inject Edilmesini Sağlar
Örnek
Şöyle yaparız
@DataJpaTest
class PersonRepositoryDataJpaTest {

  @Autowired
  private PersonRepository personRepository;

  @Test
  void shouldReturnAllLastNames() {
    personRepository.saveAndFlush(new Person().setFirstName("John").setLastName("Brown"));
    personRepository.saveAndFlush(new Person().setFirstName("Kyle").setLastName("Green"));
    personRepository.saveAndFlush(new Person().setFirstName("Paul").setLastName("Brown"));

    assertEquals(Set.of("Brown", "Green"), personRepository.findAllLastNames());
  }
}
Örnek
Şöyle yaparız. Burada respository kullanılarak kaydedilen nesneye ID atandığı test ediliyor.
@DataJpaTest
class WebAuthnUserRepositoryTest {

  @Autowired
  WebAuthnUserRepository userRepository;

  @Test
  public void test() {
    WebAuthnUser user = new WebAuthnUser();
    user.setUsername("junit");
    userRepository.save(user);

    assertNotNull(user.getId());
  }
}
Örnek
Tam çalışan bir örnek şöyle
@DataJpaTest
@ExtendWith(SpringExtension.class)
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class OrderRepositoryUnitTest {

  @Autowired
  OrderRepository orderRepository;

  @BeforeEach
  public void setUp() {
    orderRepository.save(new Order(100L, "jane", 200.0, 2));
    orderRepository.save(new Order(200L, "ben", 100.0, 5));
  }

  @AfterEach
  public void destroy() {
    orderRepository.deleteAll();
  }

  @Test
  public void testGetAllOrders() {
    List<Order> orderList = orderRepository.findAll();
    Assertions.assertThat(orderList.size()).isEqualTo(2);
    Assertions.assertThat(orderList.get(0).getId()).isNotNegative();
    Assertions.assertThat(orderList.get(0).getId()).isGreaterThan(0);
    Assertions.assertThat(orderList.get(0).getBuyer()).isEqualTo("jane");
  }

  @Test
  public void testGetInvalidOrder() {
    Exception exception = assertThrows(NoSuchElementException.class, () -> {
        orderRepository.findById(120L).get();
    });
    Assertions.assertThat(exception).isNotNull();
    Assertions.assertThat(exception.getClass()).isEqualTo(NoSuchElementException.class);
    Assertions.assertThat(exception.getMessage()).isEqualTo("No value present");
  }

  @Test
  public void testGetCreateOrder() {
    Order saved = new Order(300L, "tim", 50.0, 4);
    Order returned = orderRepository.save(saved);
    Assertions.assertThat(returned).isNotNull();
    Assertions.assertThat(returned.getBuyer()).isNotEmpty();
    Assertions.assertThat(returned.getId()).isGreaterThan(1);
    Assertions.assertThat(returned.getId()).isNotNegative();
    Assertions.assertThat(saved.getBuyer()).isEqualTo(returned.getBuyer());
  }

  @Test
  public void testDeleteOrder() {
    Order saved = new Order(400L, "ron", 60.0, 3);
    orderRepository.save(saved);
    orderRepository.delete(saved);
    Exception exception = assertThrows(NoSuchElementException.class, () -> {
      orderRepository.findById(400L).get();
    });
    Assertions.assertThat(exception).isNotNull();
    Assertions.assertThat(exception.getClass()).isEqualTo(NoSuchElementException.class);
    Assertions.assertThat(exception.getMessage()).isEqualTo("No value present");
  }
}
Örnek
Şöyle yaparız. @ContextConfiguration bir test anotasyonu. Bu anotasyon ile test içinde yüklenecek @Configuration olarak işaretli sınıfları belirtiriz.
@RunWith( SpringRunner.class )
@DataJpaTest
@ContextConfiguration(classes=PersistenceConfig.class)
public class PersonRepositoryTest {

    // Tests ...
}
Service Sınıflarının Test Edilmesi - Kullanmayın
Açıklaması şöyle
... you can use @DataJpaTest annotation that starts JPA components and Repository beans. and use @Import annotation to load the service class itself.
Ancak bu kullanım şeklinde dikkatli olmak lazım, çünkü tüm test tek bir transaction ile çalışıyor. Açıklaması şöyle
@DataJpaTest wraps the suite with the @Transactional. So, the test suite and the service are both transactional. The default propagation level for the annotation is REQUIRED. It means that calling another transactional method does not start a new transaction. Instead, it continues to execute SQL statements in the current one.
Örnek
Şöyle yaparız. Burada hem Service sınıfının yüklenmesi sağlanıyor, hem de @AutoConfigureTestDatabase ile gerçek veri tabanı kullanılıyor
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace
.ANY
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.FilterType.ASSIGNABLE_TYPE

@DataJpaTest(
    includeFilters = [
        ComponentScan.Filter(ViewersService::class, type = ASSIGNABLE_TYPE)
    ]
)
@AutoConfigureTestDatabase(replace = ANY)
internal class ViewersServiceIntegrationTest {
  @Autowired
  private lateinit var viewersService: ViewersService

  @Autowired
  private lateinit var viewersRepository: ViewersRepository
  ... 
}
Örnek
Şöyle yaparız
@DataJpaTest(showSql = false)
@Import(TestService.class)
public class ServiceTest {
  @Autowired
  private TestService service;
  
  @Test
  void testFindAll() {
    List<String> values = service.findAll();
    assertEquals(1, values.size());
  }
}
Örnek
Test koşmaya başlayınca otomatik Transaction'ı başlatmamak için şöyle yaparız
@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class PersonCreateServiceImplTestH2 {

  @Autowired
  private PersonRepository personRepository;
  @MockBean
  private PersonValidateService personValidateService;
  @Autowired
  private PersonCreateService personCreateService;

  @BeforeEach
  void beforeEach() {
    personRepository.deleteAll();
  }

  @TestConfiguration
  static class Config {

    @Bean
    public PersonCreateService personCreateService(
        PersonRepository personRepository,
        PersonValidateService personValidateService
    ) {
      return new PersonCreateServiceImpl(personValidateService, personRepository);
    }
  }
  // test cases...
}
Dolayısıyla artık bu test servis kodu exception fırlatınca geçmeye başlar.
@Test
void shouldRollbackIfAnyUserIsNotValidated() {
  doThrow(new ValidationFailedException(""))
    .when(personValidateService)
    .checkUserCreation("John", "Brown");
  
  assertThrows(ValidationFailedException.class, () -> personCreateService.createFamily(
        List.of("Matilda", "Vasya", "John"),
        "Brown"
    ));
  assertEquals(0, personRepository.count());
}
@DataJpaTest Anotasyonu Alternatifi
Örnek
Hem tüm projeyi yüklemek, hem de H2 veri tabanı yaratmak için şöyle yaparız. @AutoConfigureTestDatabase otomatik olarak bir veri tabanı yaratır
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@AutoConfigureTestDatabase
class PersonCreateServiceImplSpringBootTest {

  @Autowired
  private PersonRepository personRepository;
  @MockBean
  private PersonValidateService personValidateService;
  @Autowired
  private PersonCreateService personCreateService;

  @BeforeEach
  void init() {
    personRepository.deleteAll();
  }
}

16 Haziran 2020 Salı

SpringData @Transactional Anotasyonu Propagation Değerleri

Giriş
Bu alan şu değerleri alabiliyor
REQUIRED
REQUIRES_NEW
NESTED
MANDATORY
NEVER
NOT_SUPPORTED
SUPPORTS
REQUIRED
Eğer başlatılmış transaction yoksa yeni bir tane yaratır. Eğer varsa mevcut transaction'a kullanılır.

REQUIRES_NEW
Her zaman yeni bir transaction yaratır deniliyor, ancak şu açıklamaya dikkat etmek lazım
Often people think of this propagation setting as “magically tells the database to make a nested transaction”. However this mental model is wrong — many Databases don’t even have nested transactions, so something else needs to happen.

What actually happens is that Spring will open a new connection to the database.
Örnek
Şöyle yaparız.
@Service
@Transactional
public class FooService implements Foo {

  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public void processEachCustomer(Customer customer){
    ...
  }
}
NESTED
Başlatılmış transacion yoksa yeni bir tane başlatır, eğer varsa Savepoint kullanır. Açıklaması şöyle. Her JPA sağlayıcısı bu özelliği desteklemiyor.
NESTED acts like REQUIRED, only it uses savepoints between nested invocations. In other words, inner logical transactions may roll back independently of outer logical transactions.
Açıklaması şöyle.
For NESTED propagation, Spring checks if a transaction exists, then if yes, it marks a savepoint. This means if our business logic execution throws an exception, then transaction rollbacks to this savepoint. If there's no active transaction, it works like REQUIRED.
Açıklaması şöyle
DataSourceTransactionManager supports this propagation out-of-the-box. Also, some implementations of JTATransactionManager may support this.

JpaTransactionManager supports NESTED only for JDBC connections. However, if we set nestedTransactionAllowed flag to true, it also works for JDBC access code in JPA transactions if our JDBC driver supports savepoints.
Hibernate ile şu hatayı alırız
NestedTransactionNotSupportedException: JpaDialect does not support savepoints check your JPA provider capabilities
MANDATORY
Başlatılmış bir transaction yok ise exception fırlatır.
Örnek
Şöyle yaparız.
@Transactional(propagation = Propagation.MANDATORY)
NEVER
Başlatılmış bir transaction olmaması gerekir. Açıklaması şöyle.
The Propagation.NEVER states that no physical transaction should exist. If a physical transaction is found, then NEVER will cause an exception as follows:

org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation 'never'
NOT_SUPPORTED
Metod çalışır ancak başlatılmış bir transaction varsa ona dahil olmaz. Açıklaması şöyle.
Propagation.NOT_SUPPORTED states that if a physical transaction exists, then it will be suspended before continuing. This physical transaction will be automatically resumed at the end. After this transaction is resumed, it can be rolled back (in case of a failure) or committed.
NOt_SUPPORTED performansı artırabilir. Açıklaması şöyle
If there is any active Transaction, it is suspended and the service method is executed without Transaction. After the method has been completed, the container resumes the client’s transaction.
It is recommended to use the NotSupported attribute for methods that don’t need transactions. Because transactions involve overhead, this attribute may improve performance.
SUPPORTS
Açıklaması şöyle. Başlatılmış bir transaction varsa kullanır, yoksa transaction başlatmaz.
For SUPPORTS, Spring first checks if an active transaction exists. If a transaction exists, then the existing transaction will be used. If there isn't a transaction, it is executed non-transactional:

8 Haziran 2020 Pazartesi

SpringSecurity RequestMatcherConfigurer Sınıfı - SpringSecurit'nin Hangi Adreslere Uygulanacağını Belirtir

Giriş
Bu sınıfın tam adı aslında HttpSecurity.RequestMatcherConfigurer. Açıklaması şöyle. Eğer bu sınıfı kullanmazsak root "/" yolundan itibaren security uygulanır.
The purpose of requestMatchers() is to specify which requests the spring security configuration will be applied to.
antMatchers metodu
Şöyle yaparız
http.requestMatchers()
  .antMatchers("/management/**")         // (1)
  .and()
    .authorizeRequests()                 // (2)
      .antMatchers("/management/health")
        .permitAll()
      .antMatchers("/management/info")
       .permitAll()
     .antMatchers("/management/**")
        .hasRole("ACTUATOR")
        .anyRequest().permitAll()
    .and()
      .httpBasic();                      //(3)