repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/audit/package-info.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/audit/package-info.java
/** * Audit specific code. */ package com.baeldung.jhipster.quotes.config.audit;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/AuthorizedUserFeignClient.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/AuthorizedUserFeignClient.java
package com.baeldung.jhipster.quotes.client; import java.lang.annotation.*; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClientsConfiguration; import org.springframework.core.annotation.AliasFor; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @FeignClient public @interface AuthorizedUserFeignClient { @AliasFor(annotation = FeignClient.class, attribute = "name") String name() default ""; /** * A custom <code>@Configuration</code> for the feign client. * * Can contain override <code>@Bean</code> definition for the pieces that make up the client, for instance {@link * feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}. * * @see FeignClientsConfiguration for the defaults */ @AliasFor(annotation = FeignClient.class, attribute = "configuration") Class<?>[] configuration() default OAuth2UserClientFeignConfiguration.class; /** * An absolute URL or resolvable hostname (the protocol is optional). */ String url() default ""; /** * Whether 404s should be decoded instead of throwing FeignExceptions. */ boolean decode404() default false; /** * Fallback class for the specified Feign client interface. The fallback class must implement the interface * annotated by this annotation and be a valid Spring bean. */ Class<?> fallback() default void.class; /** * Path prefix to be used by all method-level mappings. Can be used with or without <code>@RibbonClient</code>. */ String path() default ""; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/OAuth2InterceptedFeignConfiguration.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/OAuth2InterceptedFeignConfiguration.java
package com.baeldung.jhipster.quotes.client; import java.io.IOException; import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; import feign.RequestInterceptor; import io.github.jhipster.security.uaa.LoadBalancedResourceDetails; public class OAuth2InterceptedFeignConfiguration { private final LoadBalancedResourceDetails loadBalancedResourceDetails; public OAuth2InterceptedFeignConfiguration(LoadBalancedResourceDetails loadBalancedResourceDetails) { this.loadBalancedResourceDetails = loadBalancedResourceDetails; } @Bean(name = "oauth2RequestInterceptor") public RequestInterceptor getOAuth2RequestInterceptor() throws IOException { return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), loadBalancedResourceDetails); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/AuthorizedFeignClient.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/AuthorizedFeignClient.java
package com.baeldung.jhipster.quotes.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClientsConfiguration; import org.springframework.core.annotation.AliasFor; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @FeignClient public @interface AuthorizedFeignClient { @AliasFor(annotation = FeignClient.class, attribute = "name") String name() default ""; /** * A custom <code>@Configuration</code> for the feign client. * * Can contain override <code>@Bean</code> definition for the pieces that * make up the client, for instance {@link feign.codec.Decoder}, * {@link feign.codec.Encoder}, {@link feign.Contract}. * * @see FeignClientsConfiguration for the defaults */ @AliasFor(annotation = FeignClient.class, attribute = "configuration") Class<?>[] configuration() default OAuth2InterceptedFeignConfiguration.class; /** * An absolute URL or resolvable hostname (the protocol is optional). */ String url() default ""; /** * Whether 404s should be decoded instead of throwing FeignExceptions. */ boolean decode404() default false; /** * Fallback class for the specified Feign client interface. The fallback class must * implement the interface annotated by this annotation and be a valid Spring bean. */ Class<?> fallback() default void.class; /** * Path prefix to be used by all method-level mappings. Can be used with or without * <code>@RibbonClient</code>. */ String path() default ""; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/OAuth2UserClientFeignConfiguration.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/OAuth2UserClientFeignConfiguration.java
package com.baeldung.jhipster.quotes.client; import java.io.IOException; import org.springframework.context.annotation.Bean; import feign.RequestInterceptor; public class OAuth2UserClientFeignConfiguration { @Bean(name = "userFeignClientInterceptor") public RequestInterceptor getUserFeignClientInterceptor() throws IOException { return new UserFeignClientInterceptor(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/UserFeignClientInterceptor.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/client/UserFeignClientInterceptor.java
package com.baeldung.jhipster.quotes.client; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; import feign.RequestInterceptor; import feign.RequestTemplate; public class UserFeignClientInterceptor implements RequestInterceptor{ private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String BEARER_TOKEN_TYPE = "Bearer"; @Override public void apply(RequestTemplate template) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) { OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails(); template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue())); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/package-info.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/package-info.java
/** * Spring MVC REST controllers. */ package com.baeldung.jhipster.quotes.web.rest;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/QuoteResource.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/QuoteResource.java
package com.baeldung.jhipster.quotes.web.rest; import com.codahale.metrics.annotation.Timed; import com.baeldung.jhipster.quotes.service.QuoteService; import com.baeldung.jhipster.quotes.web.rest.errors.BadRequestAlertException; import com.baeldung.jhipster.quotes.web.rest.util.HeaderUtil; import com.baeldung.jhipster.quotes.web.rest.util.PaginationUtil; import com.baeldung.jhipster.quotes.service.dto.QuoteDTO; import com.baeldung.jhipster.quotes.service.dto.QuoteCriteria; import com.baeldung.jhipster.quotes.service.QuoteQueryService; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing Quote. */ @RestController @RequestMapping("/api") public class QuoteResource { private final Logger log = LoggerFactory.getLogger(QuoteResource.class); private static final String ENTITY_NAME = "quotesQuote"; private final QuoteService quoteService; private final QuoteQueryService quoteQueryService; public QuoteResource(QuoteService quoteService, QuoteQueryService quoteQueryService) { this.quoteService = quoteService; this.quoteQueryService = quoteQueryService; } /** * POST /quotes : Create a new quote. * * @param quoteDTO the quoteDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new quoteDTO, or with status 400 (Bad Request) if the quote has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/quotes") @Timed public ResponseEntity<QuoteDTO> createQuote(@Valid @RequestBody QuoteDTO quoteDTO) throws URISyntaxException { log.debug("REST request to save Quote : {}", quoteDTO); if (quoteDTO.getId() != null) { throw new BadRequestAlertException("A new quote cannot already have an ID", ENTITY_NAME, "idexists"); } QuoteDTO result = quoteService.save(quoteDTO); return ResponseEntity.created(new URI("/api/quotes/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /quotes : Updates an existing quote. * * @param quoteDTO the quoteDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated quoteDTO, * or with status 400 (Bad Request) if the quoteDTO is not valid, * or with status 500 (Internal Server Error) if the quoteDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/quotes") @Timed public ResponseEntity<QuoteDTO> updateQuote(@Valid @RequestBody QuoteDTO quoteDTO) throws URISyntaxException { log.debug("REST request to update Quote : {}", quoteDTO); if (quoteDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } QuoteDTO result = quoteService.save(quoteDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, quoteDTO.getId().toString())) .body(result); } /** * GET /quotes : get all the quotes. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match * @return the ResponseEntity with status 200 (OK) and the list of quotes in body */ @GetMapping("/quotes") @Timed public ResponseEntity<List<QuoteDTO>> getAllQuotes(QuoteCriteria criteria, Pageable pageable) { log.debug("REST request to get Quotes by criteria: {}", criteria); Page<QuoteDTO> page = quoteQueryService.findByCriteria(criteria, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/quotes"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /quotes/count : count all the quotes. * * @param criteria the criterias which the requested entities should match * @return the ResponseEntity with status 200 (OK) and the count in body */ @GetMapping("/quotes/count") @Timed public ResponseEntity<Long> countQuotes (QuoteCriteria criteria) { log.debug("REST request to count Quotes by criteria: {}", criteria); return ResponseEntity.ok().body(quoteQueryService.countByCriteria(criteria)); } /** * GET /quotes/:id : get the "id" quote. * * @param id the id of the quoteDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the quoteDTO, or with status 404 (Not Found) */ @GetMapping("/quotes/{id}") @Timed public ResponseEntity<QuoteDTO> getQuote(@PathVariable Long id) { log.debug("REST request to get Quote : {}", id); Optional<QuoteDTO> quoteDTO = quoteService.findOne(id); return ResponseUtil.wrapOrNotFound(quoteDTO); } /** * DELETE /quotes/:id : delete the "id" quote. * * @param id the id of the quoteDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/quotes/{id}") @Timed public ResponseEntity<Void> deleteQuote(@PathVariable Long id) { log.debug("REST request to delete Quote : {}", id); quoteService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/LogsResource.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/LogsResource.java
package com.baeldung.jhipster.quotes.web.rest; import com.baeldung.jhipster.quotes.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Controller for view and managing Log Level at runtime. */ @RestController @RequestMapping("/management") public class LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/util/HeaderUtil.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/util/HeaderUtil.java
package com.baeldung.jhipster.quotes.web.rest.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; /** * Utility class for HTTP headers creation. */ public final class HeaderUtil { private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class); private static final String APPLICATION_NAME = "quotesApp"; private HeaderUtil() { } public static HttpHeaders createAlert(String message, String param) { HttpHeaders headers = new HttpHeaders(); headers.add("X-" + APPLICATION_NAME + "-alert", message); headers.add("X-" + APPLICATION_NAME + "-params", param); return headers; } public static HttpHeaders createEntityCreationAlert(String entityName, String param) { return createAlert(APPLICATION_NAME + "." + entityName + ".created", param); } public static HttpHeaders createEntityUpdateAlert(String entityName, String param) { return createAlert(APPLICATION_NAME + "." + entityName + ".updated", param); } public static HttpHeaders createEntityDeletionAlert(String entityName, String param) { return createAlert(APPLICATION_NAME + "." + entityName + ".deleted", param); } public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) { log.error("Entity processing failed, {}", defaultMessage); HttpHeaders headers = new HttpHeaders(); headers.add("X-" + APPLICATION_NAME + "-error", "error." + errorKey); headers.add("X-" + APPLICATION_NAME + "-params", entityName); return headers; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/util/PaginationUtil.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/util/PaginationUtil.java
package com.baeldung.jhipster.quotes.web.rest.util; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; /** * Utility class for handling pagination. * * <p> * Pagination uses the same principles as the <a href="https://developer.github.com/v3/#pagination">GitHub API</a>, * and follow <a href="http://tools.ietf.org/html/rfc5988">RFC 5988 (Link header)</a>. */ public final class PaginationUtil { private PaginationUtil() { } public static <T> HttpHeaders generatePaginationHttpHeaders(Page<T> page, String baseUrl) { HttpHeaders headers = new HttpHeaders(); headers.add("X-Total-Count", Long.toString(page.getTotalElements())); String link = ""; if ((page.getNumber() + 1) < page.getTotalPages()) { link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\","; } // prev link if ((page.getNumber()) > 0) { link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\","; } // last and first link int lastPage = 0; if (page.getTotalPages() > 0) { lastPage = page.getTotalPages() - 1; } link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\","; link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\""; headers.add(HttpHeaders.LINK, link); return headers; } private static String generateUri(String baseUrl, int page, int size) { return UriComponentsBuilder.fromUriString(baseUrl).queryParam("page", page).queryParam("size", size).toUriString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/InvalidPasswordException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/InvalidPasswordException.java
package com.baeldung.jhipster.quotes.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; public class InvalidPasswordException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; public InvalidPasswordException() { super(ErrorConstants.INVALID_PASSWORD_TYPE, "Incorrect password", Status.BAD_REQUEST); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/CustomParameterizedException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/CustomParameterizedException.java
package com.baeldung.jhipster.quotes.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import java.util.HashMap; import java.util.Map; import static org.zalando.problem.Status.BAD_REQUEST; /** * Custom, parameterized exception, which can be translated on the client side. * For example: * * <pre> * throw new CustomParameterizedException(&quot;myCustomError&quot;, &quot;hello&quot;, &quot;world&quot;); * </pre> * * Can be translated with: * * <pre> * "error.myCustomError" : "The server says {{param0}} to {{param1}}" * </pre> */ public class CustomParameterizedException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; private static final String PARAM = "param"; public CustomParameterizedException(String message, String... params) { this(message, toParamMap(params)); } public CustomParameterizedException(String message, Map<String, Object> paramMap) { super(ErrorConstants.PARAMETERIZED_TYPE, "Parameterized Exception", BAD_REQUEST, null, null, null, toProblemParameters(message, paramMap)); } public static Map<String, Object> toParamMap(String... params) { Map<String, Object> paramMap = new HashMap<>(); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { paramMap.put(PARAM + i, params[i]); } } return paramMap; } public static Map<String, Object> toProblemParameters(String message, Map<String, Object> paramMap) { Map<String, Object> parameters = new HashMap<>(); parameters.put("message", message); parameters.put("params", paramMap); return parameters; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/package-info.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/package-info.java
/** * Specific errors used with Zalando's "problem-spring-web" library. * * More information on https://github.com/zalando/problem-spring-web */ package com.baeldung.jhipster.quotes.web.rest.errors;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/LoginAlreadyUsedException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/LoginAlreadyUsedException.java
package com.baeldung.jhipster.quotes.web.rest.errors; public class LoginAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public LoginAlreadyUsedException() { super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/EmailNotFoundException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/EmailNotFoundException.java
package com.baeldung.jhipster.quotes.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; public class EmailNotFoundException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; public EmailNotFoundException() { super(ErrorConstants.EMAIL_NOT_FOUND_TYPE, "Email address not registered", Status.BAD_REQUEST); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/InternalServerErrorException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/InternalServerErrorException.java
package com.baeldung.jhipster.quotes.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; /** * Simple exception with a message, that returns an Internal Server Error code. */ public class InternalServerErrorException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; public InternalServerErrorException(String message) { super(ErrorConstants.DEFAULT_TYPE, message, Status.INTERNAL_SERVER_ERROR); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/ErrorConstants.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/ErrorConstants.java
package com.baeldung.jhipster.quotes.web.rest.errors; import java.net.URI; public final class ErrorConstants { public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; public static final String ERR_VALIDATION = "error.validation"; public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem"; public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); public static final URI PARAMETERIZED_TYPE = URI.create(PROBLEM_BASE_URL + "/parameterized"); public static final URI ENTITY_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/entity-not-found"); public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); public static final URI EMAIL_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/email-not-found"); private ErrorConstants() { } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/FieldErrorVM.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/FieldErrorVM.java
package com.baeldung.jhipster.quotes.web.rest.errors; import java.io.Serializable; public class FieldErrorVM implements Serializable { private static final long serialVersionUID = 1L; private final String objectName; private final String field; private final String message; public FieldErrorVM(String dto, String field, String message) { this.objectName = dto; this.field = field; this.message = message; } public String getObjectName() { return objectName; } public String getField() { return field; } public String getMessage() { return message; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/EmailAlreadyUsedException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/EmailAlreadyUsedException.java
package com.baeldung.jhipster.quotes.web.rest.errors; public class EmailAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public EmailAlreadyUsedException() { super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/BadRequestAlertException.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/BadRequestAlertException.java
package com.baeldung.jhipster.quotes.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; import org.zalando.problem.Status; import java.net.URI; import java.util.HashMap; import java.util.Map; public class BadRequestAlertException extends AbstractThrowableProblem { private static final long serialVersionUID = 1L; private final String entityName; private final String errorKey; public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) { this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey); } public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey)); this.entityName = entityName; this.errorKey = errorKey; } public String getEntityName() { return entityName; } public String getErrorKey() { return errorKey; } private static Map<String, Object> getAlertParameters(String entityName, String errorKey) { Map<String, Object> parameters = new HashMap<>(); parameters.put("message", "error." + errorKey); parameters.put("params", entityName); return parameters; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/ExceptionTranslator.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/errors/ExceptionTranslator.java
package com.baeldung.jhipster.quotes.web.rest.errors; import com.baeldung.jhipster.quotes.web.rest.util.HeaderUtil; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.NativeWebRequest; import org.zalando.problem.DefaultProblem; import org.zalando.problem.Problem; import org.zalando.problem.ProblemBuilder; import org.zalando.problem.Status; import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; import org.zalando.problem.violations.ConstraintViolationProblem; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; /** * Controller advice to translate the server side exceptions to client-friendly json structures. * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807) */ @ControllerAdvice public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait { /** * Post-process the Problem payload to add the message key for the front-end if needed */ @Override public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) { if (entity == null) { return entity; } Problem problem = entity.getBody(); if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { return entity; } ProblemBuilder builder = Problem.builder() .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) .withStatus(problem.getStatus()) .withTitle(problem.getTitle()) .with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI()); if (problem instanceof ConstraintViolationProblem) { builder .with("violations", ((ConstraintViolationProblem) problem).getViolations()) .with("message", ErrorConstants.ERR_VALIDATION); } else { builder .withCause(((DefaultProblem) problem).getCause()) .withDetail(problem.getDetail()) .withInstance(problem.getInstance()); problem.getParameters().forEach(builder::with); if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) { builder.with("message", "error.http." + problem.getStatus().getStatusCode()); } } return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); } @Override public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { BindingResult result = ex.getBindingResult(); List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream() .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode())) .collect(Collectors.toList()); Problem problem = Problem.builder() .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) .withTitle("Method argument not valid") .withStatus(defaultConstraintViolationStatus()) .with("message", ErrorConstants.ERR_VALIDATION) .with("fieldErrors", fieldErrors) .build(); return create(ex, problem, request); } @ExceptionHandler public ResponseEntity<Problem> handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) { Problem problem = Problem.builder() .withStatus(Status.NOT_FOUND) .with("message", ErrorConstants.ENTITY_NOT_FOUND_TYPE) .build(); return create(ex, problem, request); } @ExceptionHandler public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) { return create(ex, request, HeaderUtil.createFailureAlert(ex.getEntityName(), ex.getErrorKey(), ex.getMessage())); } @ExceptionHandler public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { Problem problem = Problem.builder() .withStatus(Status.CONFLICT) .with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE) .build(); return create(ex, problem, request); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/vm/package-info.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/vm/package-info.java
/** * View Models used by Spring MVC REST controllers. */ package com.baeldung.jhipster.quotes.web.rest.vm;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/vm/LoggerVM.java
jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/web/rest/vm/LoggerVM.java
package com.baeldung.jhipster.quotes.web.rest.vm; import ch.qos.logback.classic.Logger; /** * View Model object for storing a Logback logger. */ public class LoggerVM { private String name; private String level; public LoggerVM(Logger logger) { this.name = logger.getName(); this.level = logger.getEffectiveLevel().toString(); } public LoggerVM() { // Empty public constructor used by Jackson. } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Override public String toString() { return "LoggerVM{" + "name='" + name + '\'' + ", level='" + level + '\'' + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javax-sound/src/main/java/com/baeldung/SoundPlayerUsingJavaZoom.java
javax-sound/src/main/java/com/baeldung/SoundPlayerUsingJavaZoom.java
package com.baeldung; import java.io.BufferedInputStream; import javazoom.jl.player.Player; public class SoundPlayerUsingJavaZoom { public static void main(String[] args) { // javazoom Player doesn't work with wav audio format. // String audioFilePath = "AudioFileWithWavFormat.wav"; // It works with below audio formats. // String audioFilePath = "AudioFileWithMpegFormat.mpeg"; String audioFilePath = "AudioFileWithMp3Format.mp3"; SoundPlayerUsingJavaZoom player = new SoundPlayerUsingJavaZoom(); try { BufferedInputStream buffer = new BufferedInputStream(player.getClass() .getClassLoader() .getResourceAsStream(audioFilePath)); Player mp3Player = new Player(buffer); mp3Player.play(); } catch (Exception ex) { System.out.println("Error occured during playback process:" + ex.getMessage()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javax-sound/src/main/java/com/baeldung/SoundPlayerUsingJavaFx.java
javax-sound/src/main/java/com/baeldung/SoundPlayerUsingJavaFx.java
package com.baeldung; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; public class SoundPlayerUsingJavaFx { public static void main(String[] args) { // String audioFilePath = "AudioFileWithWavFormat.wav"; // String audioFilePath = "AudioFileWithMpegFormat.mpeg"; String audioFilePath = "AudioFileWithMp3Format.mp3"; SoundPlayerUsingJavaFx soundPlayerWithJavaFx = new SoundPlayerUsingJavaFx(); try { com.sun.javafx.application.PlatformImpl.startup(() -> { }); Media media = new Media(soundPlayerWithJavaFx.getClass() .getClassLoader() .getResource(audioFilePath) .toExternalForm()); MediaPlayer mp3Player = new MediaPlayer(media); mp3Player.setOnPlaying(new Runnable() { @Override public void run() { System.out.println("Playback started"); } }); mp3Player.play(); } catch (Exception ex) { System.out.println("Error occured during playback process:" + ex.getMessage()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javax-sound/src/main/java/com/baeldung/SoundPlayerUsingSourceDataLine.java
javax-sound/src/main/java/com/baeldung/SoundPlayerUsingSourceDataLine.java
package com.baeldung; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; public class SoundPlayerUsingSourceDataLine { private static final int BUFFER_SIZE = 4096; void play(String soundFilePath) { try { InputStream inputStream = getClass().getClassLoader() .getResourceAsStream(soundFilePath); AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream); AudioFormat audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info); sourceDataLine.open(audioFormat); sourceDataLine.start(); System.out.println("Playback Started."); byte[] bufferBytes = new byte[BUFFER_SIZE]; int readBytes = -1; while ((readBytes = audioStream.read(bufferBytes)) != -1) { sourceDataLine.write(bufferBytes, 0, readBytes); } sourceDataLine.drain(); sourceDataLine.close(); audioStream.close(); System.out.println("Playback has been finished."); } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) { System.out.println("Error occured during playback process:" + ex.getMessage()); } } public static void main(String[] args) { String audioFilePath = "AudioFileWithWavFormat.wav"; // Clip can not play mpeg/mp3 format audio. We'll get exception if we run with below commented mp3 and mpeg format audio. // String audioFilePath = "AudioFileWithMpegFormat.mpeg"; // String audioFilePath = "AudioFileWithMp3Format.mp3"; SoundPlayerUsingSourceDataLine player = new SoundPlayerUsingSourceDataLine(); player.play(audioFilePath); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javax-sound/src/main/java/com/baeldung/SoundPlayerUsingClip.java
javax-sound/src/main/java/com/baeldung/SoundPlayerUsingClip.java
package com.baeldung; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class SoundPlayerUsingClip implements LineListener { boolean isPlaybackCompleted; @Override public void update(LineEvent event) { if (LineEvent.Type.START == event.getType()) { System.out.println("Playback started."); } else if (LineEvent.Type.STOP == event.getType()) { isPlaybackCompleted = true; System.out.println("Playback completed."); } } /** * * Play a given audio file. * @param audioFilePath Path of the audio file. * */ void play(String audioFilePath) { try { InputStream inputStream = getClass().getClassLoader() .getResourceAsStream(audioFilePath); AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream); AudioFormat format = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip audioClip = (Clip) AudioSystem.getLine(info); audioClip.addLineListener(this); audioClip.open(audioStream); audioClip.start(); while (!isPlaybackCompleted) { try { Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } audioClip.close(); audioStream.close(); } catch (UnsupportedAudioFileException | LineUnavailableException | IOException ex) { System.out.println("Error occured during playback process:"+ ex.getMessage()); } } public static void main(String[] args) { String audioFilePath = "AudioFileWithWavFormat.wav"; // Clip can not play mpeg/mp3 format audio. We'll get exception if we run with below commented mp3 and mpeg format audio. // String audioFilePath = "AudioFileWithMpegFormat.mpeg"; // String audioFilePath = "AudioFileWithMp3Format.mp3"; SoundPlayerUsingClip player = new SoundPlayerUsingClip(); player.play(audioFilePath); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/xacml4j/NightlyWithdrawalPolicyUnitTest.java
libraries-security/src/test/java/com/baeldung/xacml4j/NightlyWithdrawalPolicyUnitTest.java
package com.baeldung.xacml4j; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.xacml4j.v20.Xacml20TestUtility; import org.xacml4j.v30.Attribute; import org.xacml4j.v30.Categories; import org.xacml4j.v30.Category; import org.xacml4j.v30.CompositeDecisionRule; import org.xacml4j.v30.Decision; import org.xacml4j.v30.Entity; import org.xacml4j.v30.RequestContext; import org.xacml4j.v30.ResponseContext; import org.xacml4j.v30.Result; import org.xacml4j.v30.XacmlPolicyTestSupport; import org.xacml4j.v30.pdp.PolicyDecisionPoint; import org.xacml4j.v30.pdp.PolicyDecisionPointBuilder; import org.xacml4j.v30.spi.combine.DecisionCombiningAlgorithmProviderBuilder; import org.xacml4j.v30.spi.function.FunctionProviderBuilder; import org.xacml4j.v30.spi.pip.PolicyInformationPointBuilder; import org.xacml4j.v30.spi.repository.InMemoryPolicyRepository; import org.xacml4j.v30.spi.repository.PolicyRepository; import org.xacml4j.v30.types.DoubleExp; import org.xacml4j.v30.types.StringExp; import org.xacml4j.v30.types.TimeExp; public class NightlyWithdrawalPolicyUnitTest extends XacmlPolicyTestSupport { private static final String POLICY_SET = "xacml4j/NightlyWithdrawalsPolicy.xml"; @Test public void testWhenNightlyWithdrawalOver500_thenFail() throws Exception { PolicyDecisionPoint pdp = buildPDP(POLICY_SET); // Action category Attribute actionAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:action:action-id") .value(StringExp.of("withdrawal")) .build(); Entity actionEntity = Entity.builder() .attribute(actionAttribute) .build(); Category actionCategory = Category.builder(Categories.ACTION) .entity(actionEntity) .build(); // Environment Category Attribute timeAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:environment:current-time") .includeInResult(false) .value(TimeExp.of("21:00:00")) .build(); Entity timeEntity = Entity.builder() .attribute(timeAttribute) .build(); Category environmentCategory = Category.builder(Categories.ENVIRONMENT) .entity(timeEntity) .build(); // ATM category Attribute amountAttribute = Attribute.builder("urn:baeldung:atm:withdrawal:amount") .value(DoubleExp.of("1200.00")) .build(); Entity atmEntity = Entity.builder() .attribute(amountAttribute) .build(); Category atmCategory = Category.builder(Categories.parse("urn:baeldung:atm:withdrawal")) .entity(atmEntity) .build(); RequestContext request = RequestContext.builder() .attributes(actionCategory, environmentCategory, atmCategory) .build(); ResponseContext response = pdp.decide(request); assertNotNull(response); assertTrue("Shoud have at least one result", response.getResults() != null && !response.getResults() .isEmpty()); Result result = response.getResults() .iterator() .next(); assertTrue("Evaluation should succeed", result.getStatus() .isSuccess()); assertEquals("Should DENY withdrawal", Decision.DENY, result.getDecision()); } @Test public void testWhenNightlyWithdrawalUnder500_thenSuccess() throws Exception { PolicyDecisionPoint pdp = buildPDP(POLICY_SET); // Action category Attribute actionAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:action:action-id") .includeInResult(false) .value(StringExp.of("withdrawal")) .build(); Entity actionEntity = Entity.builder() .attribute(actionAttribute) .build(); Category actionCategory = Category.builder(Categories.ACTION) .entity(actionEntity) .build(); // Environment Category Attribute timeAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:environment:current-time") .includeInResult(false) .value(TimeExp.of("21:00:00")) .build(); Entity timeEntity = Entity.builder() .attribute(timeAttribute) .build(); Category environmentCategory = Category.builder(Categories.ENVIRONMENT) .entity(timeEntity) .build(); // ATM category Attribute amountAttribute = Attribute.builder("urn:baeldung:atm:withdrawal:amount") .value(DoubleExp.of("499.00")) .build(); Entity atmEntity = Entity.builder() .attribute(amountAttribute) .build(); Category atmCategory = Category.builder(Categories.parse("urn:baeldung:atm:withdrawal")) .entity(atmEntity) .build(); RequestContext request = RequestContext.builder() .attributes(actionCategory, environmentCategory, atmCategory) .build(); ResponseContext response = pdp.decide(request); assertNotNull(response); assertTrue("Shoud have at least one result", response.getResults() != null && !response.getResults().isEmpty()); Result result = response.getResults().iterator().next(); assertTrue("Evaluation should succeed", result.getStatus().isSuccess()); assertEquals("Should PERMIT withdrawal", Decision.PERMIT, result.getDecision()); } @Test public void testWhenBusinessHoursWithdrawalOver500_thenSuccess() throws Exception { PolicyDecisionPoint pdp = buildPDP(POLICY_SET); // Action category Attribute actionAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:action:action-id") .includeInResult(false) .value(StringExp.of("withdrawal")) .build(); Entity actionEntity = Entity.builder() .attribute(actionAttribute) .build(); Category actionCategory = Category.builder(Categories.ACTION) .entity(actionEntity) .build(); // Environment Category Attribute timeAttribute = Attribute.builder("urn:oasis:names:tc:xacml:1.0:environment:current-time") .includeInResult(false) .value(TimeExp.of("12:00:00")) .build(); Entity timeEntity = Entity.builder() .attribute(timeAttribute) .build(); Category environmentCategory = Category.builder(Categories.ENVIRONMENT) .entity(timeEntity) .build(); // ATM category Attribute amountAttribute = Attribute.builder("urn:baeldung:atm:withdrawal:amount") .value(DoubleExp.of("2000.00")) .build(); Entity atmEntity = Entity.builder() .attribute(amountAttribute) .build(); Category atmCategory = Category.builder(Categories.parse("urn:baeldung:atm:withdrawal")) .entity(atmEntity) .build(); RequestContext request = RequestContext.builder() .attributes(actionCategory, environmentCategory, atmCategory) .build(); ResponseContext response = pdp.decide(request); assertNotNull(response); assertTrue("Shoud have at least one result", response.getResults() != null && !response.getResults() .isEmpty()); Result result = response.getResults() .iterator() .next(); assertTrue("Evaluation should succeed", result.getStatus().isSuccess()); assertEquals("Should PERMIT withdrawal", Decision.PERMIT, result.getDecision()); } private PolicyDecisionPoint buildPDP(String... policyResources) throws Exception { PolicyRepository repository = new InMemoryPolicyRepository("tes-repository", FunctionProviderBuilder.builder() .defaultFunctions() .build(), DecisionCombiningAlgorithmProviderBuilder.builder() .withDefaultAlgorithms() .create()); List<CompositeDecisionRule> policies = new ArrayList<CompositeDecisionRule>(policyResources.length); for (String policyResource : policyResources) { CompositeDecisionRule policy = repository.importPolicy(Xacml20TestUtility.getClasspathResource(policyResource)); log.info("Policy: {}", policy); policies.add(policy); } return PolicyDecisionPointBuilder.builder("testPdp") .policyRepository(repository) .pip(PolicyInformationPointBuilder.builder("testPip") .defaultResolvers() .build()) .rootPolicy(policies.get(0)) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java
libraries-security/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java
package com.baeldung.bouncycastle; import static org.junit.Assert.assertTrue; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.Security; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import org.bouncycastle.cms.CMSException; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.OperatorCreationException; import org.junit.Test; public class BouncyCastleLiveTest { String certificatePath = "src/main/resources/Baeldung.cer"; String privateKeyPath = "src/main/resources/Baeldung.p12"; char[] p12Password = "password".toCharArray(); char[] keyPassword = "password".toCharArray(); @Test public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException { Security.addProvider(new BouncyCastleProvider()); CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC"); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath)); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(privateKeyPath), p12Password); PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword); String secretMessage = "My password is 123456Seven"; System.out.println("Original Message : " + secretMessage); byte[] stringToEncrypt = secretMessage.getBytes(); byte[] encryptedData = BouncyCastleCrypto.encryptData(stringToEncrypt, certificate); byte[] rawData = BouncyCastleCrypto.decryptData(encryptedData, privateKey); String decryptedMessage = new String(rawData); assertTrue(decryptedMessage.equals(secretMessage)); byte[] signedData = BouncyCastleCrypto.signData(rawData, certificate, privateKey); Boolean check = BouncyCastleCrypto.verifSignData(signedData); assertTrue(check); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/bouncycastle/pgp/BouncyCastlePGPUnitTest.java
libraries-security/src/test/java/com/baeldung/bouncycastle/pgp/BouncyCastlePGPUnitTest.java
package com.baeldung.bouncycastle.pgp; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import org.bouncycastle.cms.CMSException; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.operator.OperatorCreationException; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class BouncyCastlePGPUnitTest { @Test @Order(1) public void givenFileWithPlainText_whenPGPEncrypWithPubKey_thenPGPEncryptedFileCreated() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException, PGPException { Path resourcesPath = Paths.get("src", "main", "resources"); String pgpresource = resourcesPath.resolve("pgp") .toAbsolutePath() .toString(); String pubKeyFileName = pgpresource + "/public_key.asc"; String encryptedFileName = pgpresource + "/EncryptedOutputFile.pgp"; String plainTextInputFileName = pgpresource + "/PlainTextInputFile.txt"; BouncyCastlePGPDemoApplication.encryptFile(encryptedFileName, plainTextInputFileName, pubKeyFileName, true); Path path = Paths.get(encryptedFileName); assertTrue(Files.exists(path)); } @Test @Order(2) public void givenPGPEncryptedFile_whenDecryptWithPrivateKey_thenFileWithPlainTextCreated() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException, PGPException { Path resourcesPath = Paths.get("src", "main", "resources"); String pgpresource = resourcesPath.resolve("pgp") .toAbsolutePath() .toString(); String encryptedFileName = pgpresource + "/EncryptedOutputFile.pgp"; String privKeyFileName = pgpresource + "/private_key.asc"; BouncyCastlePGPDemoApplication.decryptFile(encryptedFileName, privKeyFileName, "baeldung".toCharArray(), "decryptedFile", true); File file = new File("decryptedFile"); assertTrue(file.exists()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java
libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java
package com.baeldung.ssh; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import com.baeldung.ssh.jsch.JschDemo; public class JSchLiveTest { @Test public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { String username = "demo"; String password = "password"; String host = "test.rebex.net"; int port = 22; String command = "ls"; String responseString = JschDemo.listFolderStructure(username, password, host, port, command); assertNotNull(responseString); } @Test(expected = Exception.class) public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { String username = "invalidUsername"; String password = "password"; String host = "test.rebex.net"; int port = 22; String command = "ls"; String responseString = JschDemo.listFolderStructure(username, password, host, port, command); assertNull(responseString); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java
libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java
package com.baeldung.ssh; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import com.baeldung.ssh.apachesshd.SshdDemo; public class ApacheMinaSshdLiveTest { @Test public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { String username = "demo"; String password = "password"; String host = "test.rebex.net"; int port = 22; long defaultTimeoutSeconds = 10l; String command = "ls\n"; String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); assertNotNull(responseString); } @Test(expected = Exception.class) public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { String username = "invalidUsername"; String password = "password"; String host = "test.rebex.net"; int port = 22; long defaultTimeoutSeconds = 10l; String command = "ls\n"; String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); assertNull(responseString); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/pem/BouncyCastlePemUtilsUnitTest.java
libraries-security/src/test/java/com/baeldung/pem/BouncyCastlePemUtilsUnitTest.java
package com.baeldung.pem; import org.junit.jupiter.api.Test; import java.io.File; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import static org.junit.jupiter.api.Assertions.assertEquals; public class BouncyCastlePemUtilsUnitTest { @Test public void whenReadPublicKeyFromPEMFile_thenSuccess() throws Exception { File pemFile = new File(BouncyCastlePemUtilsUnitTest.class.getResource("/pem/public-key.pem").getFile()); RSAPublicKey publicKey1 = BouncyCastlePemUtils.readX509PublicKey(pemFile); RSAPublicKey publicKey2 = BouncyCastlePemUtils.readX509PublicKeySecondApproach(pemFile); assertEquals("X.509", publicKey1.getFormat()); assertEquals("RSA", publicKey1.getAlgorithm()); assertEquals("X.509", publicKey2.getFormat()); assertEquals("RSA", publicKey2.getAlgorithm()); } @Test public void whenReadPrivateKeyFromPEMFile_thenSuccess() throws Exception { File pemFile = new File(BouncyCastlePemUtilsUnitTest.class.getResource("/pem/private-key-pkcs8.pem").getFile()); RSAPrivateKey privateKey1 = BouncyCastlePemUtils.readPKCS8PrivateKey(pemFile); RSAPrivateKey privateKey2 = BouncyCastlePemUtils.readPKCS8PrivateKeySecondApproach(pemFile); assertEquals("PKCS#8", privateKey1.getFormat()); assertEquals("RSA", privateKey1.getAlgorithm()); assertEquals("PKCS#8", privateKey2.getFormat()); assertEquals("RSA", privateKey2.getAlgorithm()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/listfilesremoteserver/RemoteServerFileListingLiveTest.java
libraries-security/src/test/java/com/baeldung/listfilesremoteserver/RemoteServerFileListingLiveTest.java
package com.baeldung.listfilesremoteserver; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.SftpException; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.sftp.client.SftpClient; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.Vector; import static com.baeldung.listfilesremoteserver.RemoteServerJsch.createSession; import static com.baeldung.listfilesremoteserver.RemoteServerJsch.setUpJsch; import static com.baeldung.listfilesremoteserver.RemoteServerJsch.createSftpChannel; import static com.baeldung.listfilesremoteserver.RemoteServerJsch.listFiles; import static com.baeldung.listfilesremoteserver.RemoteServerJsch.printFiles; import static com.baeldung.listfilesremoteserver.RemoteServerJsch.disconnect; import static com.baeldung.listfilesremoteserver.RemoteServerSshj.listFileWithSshj; import static com.baeldung.listfilesremoteserver.RemoteServerApacheSshd.connectToServer; import static com.baeldung.listfilesremoteserver.RemoteServerApacheSshd.setUpSshClient; import static com.baeldung.listfilesremoteserver.RemoteServerApacheSshd.createSftpClient; import static com.baeldung.listfilesremoteserver.RemoteServerApacheSshd.listDirectory; import static com.baeldung.listfilesremoteserver.RemoteServerApacheSshd.printDirectoryEntries; public class RemoteServerFileListingLiveTest { private static final String REMOTE_DIR = "REMOTE_DIR"; @Test public void givenJsch_whenListFiles_thenSuccess() throws JSchException, SftpException { JSch jsch = setUpJsch(); Session session = createSession(jsch); ChannelSftp channelSftp = createSftpChannel(session); Vector<ChannelSftp.LsEntry> files = listFiles(channelSftp, REMOTE_DIR); printFiles(files); disconnect(channelSftp, session); } @Test public void givenApacheSshd_whenListFiles_thenSuccess() throws IOException { try (SshClient client = setUpSshClient(); ClientSession session = connectToServer(client); SftpClient sftp = createSftpClient(session)) { List<SftpClient.DirEntry> entries = listDirectory(sftp, REMOTE_DIR); printDirectoryEntries(entries); } } @Test public void givenSshj_whenListFiles_thenSuccess() throws IOException { listFileWithSshj(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java
libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java
package com.baeldung.digitalsignature; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Paths; import java.security.PrivateKey; import java.security.PublicKey; import static org.junit.Assert.assertTrue; public class DigitalSignatureUnitTest { String messagePath = "src/test/resources/digitalsignature/message.txt"; String senderKeyStore = "src/test/resources/digitalsignature/sender_keystore.jks"; String receiverKeyStore = "src/test/resources/digitalsignature/receiver_keystore.jks"; String storeType = "JKS"; String senderAlias = "senderKeyPair"; String receiverAlias = "receiverKeyPair"; char[] password = "changeit".toCharArray(); String signingAlgorithm = "SHA256withRSA"; String hashingAlgorithm = "SHA-256"; @Test public void givenMessageData_whenSignWithSignatureSigning_thenVerify() throws Exception { PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); byte[] digitalSignature = DigitalSignatureUtils.sign(messageBytes, signingAlgorithm, privateKey); PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); boolean isCorrect = DigitalSignatureUtils.verify(messageBytes, signingAlgorithm, publicKey, digitalSignature); assertTrue(isCorrect); } @Test public void givenMessageData_whenSignWithMessageDigestAndCipher_thenVerify() throws Exception { PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); byte[] encryptedMessageHash = DigitalSignatureUtils.signWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, privateKey); PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); boolean isCorrect = DigitalSignatureUtils.verifyWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, publicKey, encryptedMessageHash); assertTrue(isCorrect); } @Test public void givenMessageData_whenSignWithSignatureSigning_thenVerifyWithMessageDigestAndCipher() throws Exception { PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); byte[] digitalSignature = DigitalSignatureUtils.sign(messageBytes, signingAlgorithm, privateKey); PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); boolean isCorrect = DigitalSignatureUtils.verifyWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, publicKey, digitalSignature); assertTrue(isCorrect); } @Test public void givenMessageData_whenSignWithMessageDigestAndCipher_thenVerifyWithSignature() throws Exception { PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); byte[] encryptedMessageHash = DigitalSignatureUtils.signWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, privateKey); PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); boolean isCorrect = DigitalSignatureUtils.verify(messageBytes, signingAlgorithm, publicKey, encryptedMessageHash); assertTrue(isCorrect); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java
libraries-security/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java
package com.baeldung.bouncycastle; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSEnvelopedData; import org.bouncycastle.cms.CMSEnvelopedDataGenerator; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.KeyTransRecipientInformation; import org.bouncycastle.cms.RecipientInformation; import org.bouncycastle.cms.SignerInformation; import org.bouncycastle.cms.SignerInformationStore; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder; import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.OutputEncryptor; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.Store; public class BouncyCastleCrypto { public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) throws CertificateEncodingException, OperatorCreationException, CMSException, IOException { byte[] signedMessage = null; List<X509Certificate> certList = new ArrayList<X509Certificate>(); CMSTypedData cmsData = new CMSProcessableByteArray(data); certList.add(signingCertificate); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator(); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey); cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate)); cmsGenerator.addCertificates(certs); CMSSignedData cms = cmsGenerator.generate(cmsData, true); signedMessage = cms.getEncoded(); return signedMessage; } public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException { ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); ASN1InputStream aIn = new ASN1InputStream(bIn); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); aIn.close(); bIn.close(); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); SignerInformation signer = c.iterator().next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder)); if (!verifResult) { return false; } return true; } public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException { byte[] encryptedData = null; if (null != data && null != encryptionCertificate) { CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); CMSTypedData msg = new CMSProcessableByteArray(data); OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build(); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor); encryptedData = cmsEnvelopedData.getEncoded(); } return encryptedData; } public static byte[] decryptData(final byte[] encryptedData, final PrivateKey decryptionKey) throws CMSException { byte[] decryptedData = null; if (null != encryptedData && null != decryptionKey) { CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData); Collection<RecipientInformation> recip = envelopedData.getRecipientInfos().getRecipients(); KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next(); JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey); decryptedData = recipientInfo.getContent(recipient); } return decryptedData; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/bouncycastle/pgp/PGPExampleUtil.java
libraries-security/src/main/java/com/baeldung/bouncycastle/pgp/PGPExampleUtil.java
package com.baeldung.bouncycastle.pgp; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchProviderException; import java.util.Iterator; import org.bouncycastle.openpgp.PGPCompressedDataGenerator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; class PGPExampleUtil { static byte[] compressFile(String fileName, int algorithm) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm); PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName)); comData.close(); return bOut.toByteArray(); } /** * Search a secret key ring collection for a secret key corresponding to keyID if it * exists. * * @param pgpSec a secret key ring collection. * @param keyID keyID we want. * @param pass passphrase to decrypt secret key with. * @return the private key. * @throws PGPException * @throws NoSuchProviderException */ static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass) throws PGPException, NoSuchProviderException { PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID); if (pgpSecKey == null) { return null; } return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC") .build(pass)); } static PGPPublicKey readPublicKey(String fileName) throws IOException, PGPException { InputStream keyIn = new BufferedInputStream(new FileInputStream(fileName)); PGPPublicKey pubKey = readPublicKey(keyIn); keyIn.close(); return pubKey; } /** * A simple method that opens a key ring file and loads the first available key * suitable for encryption. * * @param input data stream containing the public key data * @return the first public key found. * @throws IOException * @throws PGPException */ static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); } static PGPSecretKey readSecretKey(String fileName) throws IOException, PGPException { InputStream keyIn = new BufferedInputStream(new FileInputStream(fileName)); PGPSecretKey secKey = readSecretKey(keyIn); keyIn.close(); return secKey; } /** * A simple method that opens a key ring file and loads the first available key * suitable for signature generation. * * @param input stream to read the secret key ring collection from. * @return a secret key. * @throws IOException on a problem with using the input stream. * @throws PGPException if there is an issue parsing the input stream. */ static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException { PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); Iterator keyRingIter = pgpSec.getKeyRings(); while (keyRingIter.hasNext()) { PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getSecretKeys(); while (keyIter.hasNext()) { PGPSecretKey key = (PGPSecretKey) keyIter.next(); if (key.isSigningKey()) { return key; } } } throw new IllegalArgumentException("Can't find signing key in key ring."); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/bouncycastle/pgp/BouncyCastlePGPDemoApplication.java
libraries-security/src/main/java/com/baeldung/bouncycastle/pgp/BouncyCastlePGPDemoApplication.java
package com.baeldung.bouncycastle.pgp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import java.util.Iterator; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.bcpg.CompressionAlgorithmTags; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPCompressedData; import org.bouncycastle.openpgp.PGPEncryptedData; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedDataList; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPOnePassSignatureList; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory; import org.bouncycastle.openpgp.operator.PGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; import org.bouncycastle.util.io.Streams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BouncyCastlePGPDemoApplication { private static final Logger logger = LoggerFactory.getLogger(BouncyCastlePGPDemoApplication.class); static { Security.addProvider(new BouncyCastleProvider()); } public static void main(String[] args) { Path resourcesPath = Paths.get("src", "main", "resources"); String pgpresource = resourcesPath.resolve("pgp") .toAbsolutePath() .toString(); String pubKeyFileName = pgpresource + "/public_key.asc"; String encryptedFileName = pgpresource + "/EncryptedOutputFile.pgp"; String plainTextInputFileName = pgpresource + "/PlainTextInputFile.txt"; String privKeyFileName = pgpresource + "/private_key.asc"; try { encryptFile(encryptedFileName, plainTextInputFileName, pubKeyFileName, true); decryptFile(encryptedFileName, privKeyFileName, "baeldung".toCharArray(), "decryptedFile", true); } catch (NoSuchProviderException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (PGPException e) { logger.error(e.getMessage()); } } public static void encryptFile(String outputFileName, String inputFileName, String pubKeyFileName, boolean armor) throws IOException, NoSuchProviderException, PGPException { OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName)); PGPPublicKey encKey = PGPExampleUtil.readPublicKey(pubKeyFileName); if (armor) { out = new ArmoredOutputStream(out); } try { byte[] bytes = PGPExampleUtil.compressFile(inputFileName, CompressionAlgorithmTags.ZIP); PGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setProvider("BC") .setSecureRandom(new SecureRandom()) .setWithIntegrityPacket(true); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptorBuilder); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC")); OutputStream cOut = encGen.open(out, bytes.length); cOut.write(bytes); cOut.close(); out.close(); } catch (PGPException e) { logger.error(e.getMessage()); } } public static void decryptFile(String encryptedInputFileName, String privatekeyFileName, char[] passPhrase, String defaultFileName, boolean withIntegrityCheck) throws IOException, NoSuchProviderException { InputStream instream = new BufferedInputStream(new FileInputStream(encryptedInputFileName)); InputStream privateKeyInStream = new BufferedInputStream(new FileInputStream(privatekeyFileName)); instream = PGPUtil.getDecoderStream(instream); try { JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(instream); PGPEncryptedDataList enc; Object o = pgpF.nextObject(); // the first object might be a PGP marker packet. if (o instanceof PGPEncryptedDataList) { enc = (PGPEncryptedDataList) o; } else { enc = (PGPEncryptedDataList) pgpF.nextObject(); } Iterator it = enc.getEncryptedDataObjects(); PGPPrivateKey sKey = null; PGPPublicKeyEncryptedData pbe = null; PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateKeyInStream), new JcaKeyFingerprintCalculator()); while (sKey == null && it.hasNext()) { pbe = (PGPPublicKeyEncryptedData) it.next(); sKey = PGPExampleUtil.findSecretKey(pgpSec, pbe.getKeyID(), passPhrase); } if (sKey == null) { throw new IllegalArgumentException("secret key for message not found."); } InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC") .build(sKey)); JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear); Object message = plainFact.nextObject(); if (message instanceof PGPCompressedData) { PGPCompressedData cData = (PGPCompressedData) message; JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream()); message = pgpFact.nextObject(); } if (message instanceof PGPLiteralData) { PGPLiteralData ld = (PGPLiteralData) message; String outFileName = ld.getFileName(); outFileName = defaultFileName; InputStream unc = ld.getInputStream(); OutputStream fOut = new FileOutputStream(outFileName); Streams.pipeAll(unc, fOut); fOut.close(); } else if (message instanceof PGPOnePassSignatureList) { throw new PGPException("encrypted message contains a signed message - not literal data."); } else { throw new PGPException("message is not a simple encrypted file - type unknown."); } if (pbe.isIntegrityProtected() && pbe.verify()) { logger.error("message integrity check passed"); } else { logger.error("message integrity check failed"); } } catch (PGPException e) { logger.error(e.getMessage()); } privateKeyInStream.close(); instream.close(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java
libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java
package com.baeldung.ssh.apachesshd; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.EnumSet; import java.util.concurrent.TimeUnit; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.channel.ClientChannel; import org.apache.sshd.client.channel.ClientChannelEvent; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.channel.Channel; public class SshdDemo { public static void main(String[] args) throws Exception { String username = "demo"; String password = "password"; String host = "test.rebex.net"; int port = 22; long defaultTimeoutSeconds = 10l; String command = "ls\n"; listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); } public static String listFolderStructure(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) throws Exception { SshClient client = SshClient.setUpDefaultClient(); client.start(); try (ClientSession session = client.connect(username, host, port) .verify(defaultTimeoutSeconds, TimeUnit.SECONDS) .getSession()) { session.addPasswordIdentity(password); session.auth() .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) { channel.setOut(responseStream); channel.setErr(errorResponseStream); try { channel.open() .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); try (OutputStream pipedIn = channel.getInvertedIn()) { pipedIn.write(command.getBytes()); pipedIn.flush(); } channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds)); String errorString = new String(errorResponseStream.toByteArray()); if(!errorString.isEmpty()) { throw new Exception(errorString); } String responseString = new String(responseStream.toByteArray()); return responseString; } finally { channel.close(false); } } } finally { client.stop(); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java
libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java
package com.baeldung.ssh.jsch; import java.io.ByteArrayOutputStream; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class JschDemo { public static void main(String args[]) throws Exception { String username = "demo"; String password = "password"; String host = "test.rebex.net"; int port = 22; String command = "ls"; listFolderStructure(username, password, host, port, command); } public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception { Session session = null; ChannelExec channel = null; String response = null; try { session = new JSch().getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); channel.setOutputStream(responseStream); channel.setErrStream(errorResponseStream); channel.connect(); while (channel.isConnected()) { Thread.sleep(100); } String errorResponse = new String(errorResponseStream.toByteArray()); response = new String(responseStream.toByteArray()); if(!errorResponse.isEmpty()) { throw new Exception(errorResponse); } } finally { if (session != null) { session.disconnect(); } if (channel != null) { channel.disconnect(); } } return response; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/pem/BouncyCastlePemUtils.java
libraries-security/src/main/java/com/baeldung/pem/BouncyCastlePemUtils.java
package com.baeldung.pem; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class BouncyCastlePemUtils { public static RSAPublicKey readX509PublicKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException { KeyFactory factory = KeyFactory.getInstance("RSA"); try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) { PemObject pemObject = pemReader.readPemObject(); byte[] content = pemObject.getContent(); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content); return (RSAPublicKey) factory.generatePublic(pubKeySpec); } } public static RSAPublicKey readX509PublicKeySecondApproach(File file) throws IOException { try (FileReader keyReader = new FileReader(file)) { PEMParser pemParser = new PEMParser(keyReader); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemParser.readObject()); return (RSAPublicKey) converter.getPublicKey(publicKeyInfo); } } public static RSAPrivateKey readPKCS8PrivateKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException { KeyFactory factory = KeyFactory.getInstance("RSA"); try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) { PemObject pemObject = pemReader.readPemObject(); byte[] content = pemObject.getContent(); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content); return (RSAPrivateKey) factory.generatePrivate(privKeySpec); } } public static RSAPrivateKey readPKCS8PrivateKeySecondApproach(File file) throws IOException { try (FileReader keyReader = new FileReader(file)) { PEMParser pemParser = new PEMParser(keyReader); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(pemParser.readObject()); return (RSAPrivateKey) converter.getPrivateKey(privateKeyInfo); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/listfilesremoteserver/RemoteServerSshj.java
libraries-security/src/main/java/com/baeldung/listfilesremoteserver/RemoteServerSshj.java
package com.baeldung.listfilesremoteserver; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.sftp.RemoteResourceInfo; import net.schmizz.sshj.sftp.SFTPClient; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; public class RemoteServerSshj { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServerSshj.class); private static final String HOST = "HOST_NAME"; private static final String USER = "USERNAME"; private static final String PRIVATE_KEY = "PRIVATE_KEY"; private static final String REMOTE_DIR = "REMOTE_DIR"; public static void listFileWithSshj() throws IOException { try (SSHClient sshClient = new SSHClient()) { sshClient.addHostKeyVerifier(new PromiscuousVerifier()); sshClient.connect(HOST); sshClient.authPublickey(USER, PRIVATE_KEY); try (SFTPClient sftpClient = sshClient.newSFTPClient()) { List<RemoteResourceInfo> files = sftpClient.ls(REMOTE_DIR); for (RemoteResourceInfo file : files) { LOGGER.info("Filename: " + file.getName()); LOGGER.info("Permissions: " + file.getAttributes() .getPermissions()); LOGGER.info("Last Modification Time: " + file.getAttributes() .getMtime()); } } } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/listfilesremoteserver/RemoteServerJsch.java
libraries-security/src/main/java/com/baeldung/listfilesremoteserver/RemoteServerJsch.java
package com.baeldung.listfilesremoteserver; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.SftpException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Vector; public class RemoteServerJsch { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServerJsch.class); private static final String HOST = "HOST_NAME"; private static final String USER = "USERNAME"; private static final String PRIVATE_KEY = "PRIVATE_KEY"; private static final int PORT = 22; public static JSch setUpJsch() throws JSchException { JSch jsch = new JSch(); jsch.addIdentity(PRIVATE_KEY); return jsch; } public static Session createSession(JSch jsch) throws JSchException { Session session = jsch.getSession(USER, HOST, PORT); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); return session; } public static ChannelSftp createSftpChannel(Session session) throws JSchException { ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); return channelSftp; } public static Vector<ChannelSftp.LsEntry> listFiles(ChannelSftp channelSftp, String remoteDir) throws SftpException { return channelSftp.ls(remoteDir); } public static void printFiles(Vector<ChannelSftp.LsEntry> files) { for (ChannelSftp.LsEntry entry : files) { LOGGER.info(entry.getLongname()); } } public static void disconnect(ChannelSftp channelSftp, Session session) { channelSftp.disconnect(); session.disconnect(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/listfilesremoteserver/RemoteServerApacheSshd.java
libraries-security/src/main/java/com/baeldung/listfilesremoteserver/RemoteServerApacheSshd.java
package com.baeldung.listfilesremoteserver; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.keyprovider.FileKeyPairProvider; import org.apache.sshd.sftp.client.SftpClient; import org.apache.sshd.sftp.client.SftpClientFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Paths; import java.security.KeyPair; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class RemoteServerApacheSshd { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServerApacheSshd.class); private static final String HOST = "HOST_NAME"; private static final String USER = "USERNAME"; private static final String PRIVATE_KEY = "PRIVATE_KEY"; private static final int PORT = 22; public static SshClient setUpSshClient() { SshClient client = SshClient.setUpDefaultClient(); client.start(); client.setServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE); return client; } public static ClientSession connectToServer(SshClient client) throws IOException { ClientSession session = client.connect(USER, HOST, PORT) .verify(10000) .getSession(); FileKeyPairProvider fileKeyPairProvider = new FileKeyPairProvider(Paths.get(PRIVATE_KEY)); Iterable<KeyPair> keyPairs = fileKeyPairProvider.loadKeys(null); for (KeyPair keyPair : keyPairs) { session.addPublicKeyIdentity(keyPair); } session.auth() .verify(10000); return session; } public static SftpClient createSftpClient(ClientSession session) throws IOException { SftpClientFactory factory = SftpClientFactory.instance(); return factory.createSftpClient(session); } public static List<SftpClient.DirEntry> listDirectory(SftpClient sftp, String remotePath) throws IOException { Iterable<SftpClient.DirEntry> entriesIterable = sftp.readDir(remotePath); return StreamSupport.stream(entriesIterable.spliterator(), false) .collect(Collectors.toList()); } public static void printDirectoryEntries(List<SftpClient.DirEntry> entries) { for (SftpClient.DirEntry entry : entries) { LOGGER.info(entry.getFilename()); LOGGER.info(entry.getLongFilename()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java
libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java
package com.baeldung.digitalsignature; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.DigestInfo; import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; import javax.crypto.Cipher; import java.io.FileInputStream; import java.io.IOException; import java.security.*; import java.security.cert.Certificate; import java.util.Arrays; public class DigitalSignatureUtils { public static PrivateKey getPrivateKey(String file, char[] password, String storeType, String alias) throws Exception { KeyStore keyStore = KeyStore.getInstance(storeType); keyStore.load(new FileInputStream(file), password); return (PrivateKey) keyStore.getKey(alias, password); } public static PublicKey getPublicKey(String file, char[] password, String storeType, String alias) throws Exception { KeyStore keyStore = KeyStore.getInstance(storeType); keyStore.load(new FileInputStream(file), password); Certificate certificate = keyStore.getCertificate(alias); return certificate.getPublicKey(); } public static byte[] sign(byte[] message, String signingAlgorithm, PrivateKey signingKey) throws SecurityException { try { Signature signature = Signature.getInstance(signingAlgorithm); signature.initSign(signingKey); signature.update(message); return signature.sign(); } catch (GeneralSecurityException exp) { throw new SecurityException("Error during signature generation", exp); } } public static boolean verify(byte[] messageBytes, String signingAlgorithm, PublicKey publicKey, byte[] signedData) { try { Signature signature = Signature.getInstance(signingAlgorithm); signature.initVerify(publicKey); signature.update(messageBytes); return signature.verify(signedData); } catch (GeneralSecurityException exp) { throw new SecurityException("Error during verifying", exp); } } public static byte[] signWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PrivateKey privateKey) { try { MessageDigest md = MessageDigest.getInstance(hashingAlgorithm); byte[] messageHash = md.digest(messageBytes); DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder(); AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm); DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, messageHash); byte[] hashToEncrypt = digestInfo.getEncoded(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(hashToEncrypt); } catch (GeneralSecurityException | IOException exp) { throw new SecurityException("Error during signature generation", exp); } } public static boolean verifyWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PublicKey publicKey, byte[] encryptedMessageHash) { try { MessageDigest md = MessageDigest.getInstance(hashingAlgorithm); byte[] newMessageHash = md.digest(messageBytes); DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder(); AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm); DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, newMessageHash); byte[] hashToEncrypt = digestInfo.getEncoded(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] decryptedMessageHash = cipher.doFinal(encryptedMessageHash); return Arrays.equals(decryptedMessageHash, hashToEncrypt); } catch (GeneralSecurityException | IOException exp) { throw new SecurityException("Error during verifying", exp); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javafx-2/src/main/java/com/baeldung/Main.java
javafx-2/src/main/java/com/baeldung/Main.java
package com.baeldung; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("app-label.fxml")); Parent root = loader.load(); primaryStage.setScene(new Scene(root)); } catch (IOException e) { System.err.println("View failed to load: " + e.getMessage()); primaryStage.setScene(new Scene(new Label("UI failed to load"))); } primaryStage.setTitle("Title goes here"); primaryStage.show(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javafx-2/src/main/java/com/baeldung/controller/MainController.java
javafx-2/src/main/java/com/baeldung/controller/MainController.java
package com.baeldung.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; public class MainController implements Initializable { private final Logger logger; private final MetricsCollector metrics; private final String appName; @FXML private Label statusLabel; @FXML private Label appNameLabel; public MainController(String name) { this.logger = Logger.getLogger(MainController.class.getName()); this.metrics = new MetricsCollector("dashboard-controller"); this.appName = name; logger.info("DashboardController created"); metrics.incrementCounter("controller.instances"); } @Override public void initialize(URL location, ResourceBundle resources) { this.appNameLabel.setText(this.appName); this.statusLabel.setText("App is ready!"); logger.info("UI initialized successfully"); } // Placeholder classes for demo static class Logger { private final String name; private Logger(String name) { this.name = name; } public static Logger getLogger(String name) { return new Logger(name); } public void info(String msg) { System.out.println("[INFO] " + msg); } } static class MetricsCollector { private final String source; public MetricsCollector(String source) { this.source = source; } public void incrementCounter(String key) { System.out.println("Metric incremented: " + key + " (source: " + source + ")"); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javafx-2/src/main/java/com/baeldung/controller/ControllerAnnotation.java
javafx-2/src/main/java/com/baeldung/controller/ControllerAnnotation.java
package com.baeldung.controller; import javafx.fxml.FXML; import javafx.scene.control.Label; public class ControllerAnnotation { private final String appName; @FXML private Label appNameLabel; public ControllerAnnotation(String name) { this.appName = name; } @FXML public void initialize() { this.appNameLabel.setText(this.appName); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/javafx-2/src/main/java/com/baeldung/controller/ProfileController.java
javafx-2/src/main/java/com/baeldung/controller/ProfileController.java
package com.baeldung.controller; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; public class ProfileController implements Initializable { private final UserService userService; private User currentUser; @FXML private Label usernameLabel; public ProfileController(UserService userService) { this.userService = userService; this.currentUser = userService.getCurrentUser(); } @Override public void initialize(URL location, ResourceBundle resources) { usernameLabel.setText("Welcome, " + this.currentUser.getName()); } // Placeholder classes for demo static class UserService { private final User user; UserService() { this.user = new User("Baeldung"); } public User getCurrentUser() { return this.user; } } static class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/test/java/com/baeldung/bootbatch/SpringBootBatchIntegrationTest.java
spring-batch/src/test/java/com/baeldung/bootbatch/SpringBootBatchIntegrationTest.java
package com.baeldung.bootbatch; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.batch.test.JobRepositoryTestUtils; import org.springframework.batch.test.context.SpringBatchTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.annotation.PropertySource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringBatchTest @DirtiesContext @SpringJUnitConfig(BatchConfiguration.class) @PropertySource("classpath:application.properties") @EnableAutoConfiguration @ExtendWith({ OutputCaptureExtension.class }) public class SpringBootBatchIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; @MockBean private JobCompletionNotificationListener jobCompletionNotificationListener; @AfterEach public void cleanUp() { jobRepositoryTestUtils.removeJobExecutions(); } @Test public void givenCoffeeList_whenJobExecuted_thenSuccess(CapturedOutput output) throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob(); JobInstance jobInstance = jobExecution.getJobInstance(); ExitStatus jobExitStatus = jobExecution.getExitStatus(); assertEquals("importUserJob", jobInstance.getJobName()); assertEquals("COMPLETED", jobExitStatus.getExitCode()); String regex = "\\[virtual-thread-executor\\d+\\] INFO com.baeldung.bootbatch.CoffeeItemProcessor"; assertThat(output.getAll()).containsPattern(regex); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java
spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchIntegrationTest.java
package com.baeldung.batchtesting; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collection; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.StepExecution; import org.springframework.batch.test.AssertFile; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.batch.test.JobRepositoryTestUtils; import org.springframework.batch.test.context.SpringBatchTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.core.io.FileSystemResource; import org.springframework.test.context.ContextConfiguration; @SpringBatchTest @EnableAutoConfiguration @ContextConfiguration(classes = { SpringBatchConfiguration.class }) public class SpringBatchIntegrationTest { private static final String TEST_OUTPUT = "src/test/resources/output/actual-output.json"; private static final String EXPECTED_OUTPUT = "src/test/resources/output/expected-output.json"; private static final String TEST_INPUT = "src/test/resources/input/test-input.csv"; @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; @AfterEach public void cleanUp() { jobRepositoryTestUtils.removeJobExecutions(); } private JobParameters defaultJobParameters() { JobParametersBuilder paramsBuilder = new JobParametersBuilder(); paramsBuilder.addString("file.input", TEST_INPUT); paramsBuilder.addString("file.output", TEST_OUTPUT); return paramsBuilder.toJobParameters(); } @Test public void givenReferenceOutput_whenJobExecuted_thenSuccess() throws Exception { // given FileSystemResource expectedResult = new FileSystemResource(EXPECTED_OUTPUT); FileSystemResource actualResult = new FileSystemResource(TEST_OUTPUT); // when JobExecution jobExecution = jobLauncherTestUtils.launchJob(defaultJobParameters()); JobInstance actualJobInstance = jobExecution.getJobInstance(); ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); // then assertEquals("transformBooksRecords", actualJobInstance.getJobName()); assertEquals("COMPLETED", actualJobExitStatus.getExitCode()); AssertFile.assertFileEquals(expectedResult, actualResult); } @Test public void givenReferenceOutput_whenStep1Executed_thenSuccess() throws Exception { // given FileSystemResource expectedResult = new FileSystemResource(EXPECTED_OUTPUT); FileSystemResource actualResult = new FileSystemResource(TEST_OUTPUT); // when JobExecution jobExecution = jobLauncherTestUtils.launchStep("step1", defaultJobParameters()); Collection<StepExecution> actualStepExecutions = jobExecution.getStepExecutions(); ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); // then assertEquals(1, actualStepExecutions.size()); assertEquals("COMPLETED", actualJobExitStatus.getExitCode()); AssertFile.assertFileEquals(expectedResult, actualResult); } @Test public void whenStep2Executed_thenSuccess() { // when JobExecution jobExecution = jobLauncherTestUtils.launchStep("step2", defaultJobParameters()); Collection<StepExecution> actualStepExecutions = jobExecution.getStepExecutions(); ExitStatus actualExitStatus = jobExecution.getExitStatus(); // then assertEquals(1, actualStepExecutions.size()); assertEquals("COMPLETED", actualExitStatus.getExitCode()); actualStepExecutions.forEach(stepExecution -> { assertEquals(8L, stepExecution.getWriteCount()); }); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java
spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java
package com.baeldung.batchtesting; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.batch.test.AssertFile.assertFileEquals; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.StepExecution; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.json.JsonFileItemWriter; import org.springframework.batch.test.JobRepositoryTestUtils; import org.springframework.batch.test.MetaDataInstanceFactory; import org.springframework.batch.test.StepScopeTestUtils; import org.springframework.batch.test.context.SpringBatchTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.core.io.FileSystemResource; import org.springframework.test.context.ContextConfiguration; import com.baeldung.batchtesting.model.Book; import com.baeldung.batchtesting.model.BookRecord; @SpringBatchTest @EnableAutoConfiguration @ContextConfiguration(classes = { SpringBatchConfiguration.class }) public class SpringBatchStepScopeIntegrationTest { private static String TEST_OUTPUT = "src/test/resources/output/actual-output.json"; private static final String EXPECTED_OUTPUT_ONE = "src/test/resources/output/expected-output-one.json"; private static final String TEST_INPUT_ONE = "src/test/resources/input/test-input-one.csv"; @Autowired private JsonFileItemWriter<Book> jsonItemWriter; @Autowired private FlatFileItemReader<BookRecord> itemReader; @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; @BeforeAll public static void setup() throws IOException { final File tempFile = Files.createTempFile("actual-output", ".json").toFile(); Files.copy(Paths.get(TEST_OUTPUT), Paths.get(tempFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); TEST_OUTPUT = tempFile.getAbsolutePath(); } private JobParameters defaultJobParameters() { JobParametersBuilder paramsBuilder = new JobParametersBuilder(); paramsBuilder.addString("file.input", TEST_INPUT_ONE); paramsBuilder.addString("file.output", TEST_OUTPUT); return paramsBuilder.toJobParameters(); } @AfterEach public void cleanUp() { jobRepositoryTestUtils.removeJobExecutions(); } @Test public void givenMockedStep_whenReaderCalled_thenSuccess() throws Exception { // given StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(defaultJobParameters()); // when StepScopeTestUtils.doInStepScope(stepExecution, () -> { BookRecord bookRecord; itemReader.open(stepExecution.getExecutionContext()); while ((bookRecord = itemReader.read()) != null) { // then assertEquals("Foundation", bookRecord.getBookName()); assertEquals("Asimov I.", bookRecord.getBookAuthor()); assertEquals("ISBN 12839", bookRecord.getBookISBN()); assertEquals("hardcover", bookRecord.getBookFormat()); assertEquals("2018", bookRecord.getPublishingYear()); } itemReader.close(); return null; }); } @Test public void givenMockedStep_whenWriterCalled_thenSuccess() throws Exception { // given FileSystemResource expectedResult = new FileSystemResource(EXPECTED_OUTPUT_ONE); FileSystemResource actualResult = new FileSystemResource(TEST_OUTPUT); Book demoBook = new Book(); demoBook.setAuthor("Grisham J."); demoBook.setName("The Firm"); StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(defaultJobParameters()); // when StepScopeTestUtils.doInStepScope(stepExecution, () -> { jsonItemWriter.open(stepExecution.getExecutionContext()); jsonItemWriter.write(new Chunk<>(List.of(demoBook))); jsonItemWriter.close(); return null; }); // then assertFileEquals(expectedResult, actualResult); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerLiveTest.java
spring-batch/src/test/java/com/baeldung/batchscheduler/SpringBatchSchedulerLiveTest.java
package com.baeldung.batchscheduler; import static java.util.concurrent.TimeUnit.SECONDS; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.test.annotation.DirtiesContext; @SpringBootTest @DirtiesContext @PropertySource("classpath:application.properties") public class SpringBatchSchedulerLiveTest { @Autowired private ApplicationContext context; @Test public void stopJobsWhenSchedulerDisabled() { SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> assertEquals(2, schedulerBean.getBatchRunCounter() .get())); schedulerBean.stop(); await().atLeast(3, SECONDS); assertEquals(2, schedulerBean.getBatchRunCounter().get()); } @Test public void stopJobSchedulerWhenSchedulerDestroyed() { ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class); SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> assertEquals(2, schedulerBean.getBatchRunCounter() .get())); bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler"); await().atLeast(3, SECONDS); assertEquals(2, schedulerBean.getBatchRunCounter() .get()); } @Test public void stopJobSchedulerWhenFutureTasksCancelled() { SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); await().untilAsserted(() -> assertEquals(2, schedulerBean.getBatchRunCounter() .get())); schedulerBean.cancelFutureSchedulerTasks(); await().atLeast(3, SECONDS); assertEquals(2, schedulerBean.getBatchRunCounter() .get()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java
spring-batch/src/test/java/com/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java
package com.baeldung.taskletsvschunks.chunks; import static org.junit.jupiter.api.Assertions.assertEquals; import com.baeldung.taskletsvschunks.config.ChunksConfig; import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.batch.test.context.SpringBatchTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.test.context.ContextConfiguration; @SpringBatchTest @EnableAutoConfiguration @ContextConfiguration(classes = ChunksConfig.class) public class ChunksIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Test public void givenChunksJob_WhenJobEnds_ThenStatusCompleted() throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob(); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java
spring-batch/src/test/java/com/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java
package com.baeldung.taskletsvschunks.tasklets; import static org.junit.jupiter.api.Assertions.assertEquals; import com.baeldung.taskletsvschunks.config.TaskletsConfig; import org.junit.jupiter.api.Test; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.batch.test.context.SpringBatchTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.test.context.ContextConfiguration; @SpringBatchTest @EnableAutoConfiguration @ContextConfiguration(classes = TaskletsConfig.class) public class TaskletsIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Test public void givenTaskletsJob_WhenJobEnds_ThenStatusCompleted() throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob(); assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/App.java
spring-batch/src/main/java/com/baeldung/batch/App.java
package com.baeldung.batch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Profile; @Profile("spring") public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); public static void main(final String[] args) { // Spring Java config final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.getEnvironment().addActiveProfile("spring"); context.register(SpringBatchConfig.class); context.refresh(); // Spring xml config // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch-intro.xml"); runJob(context, "parentJob"); runJob(context, "firstBatchJob"); runJob(context, "skippingBatchJob"); runJob(context, "skipPolicyBatchJob"); } private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) { final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); final Job job = (Job) context.getBean(batchJobName); LOGGER.info("Starting the batch job: {}", batchJobName); try { // To enable multiple execution of a job with the same parameters JobParameters jobParameters = new JobParametersBuilder().addString("jobID", String.valueOf(System.currentTimeMillis())) .toJobParameters(); final JobExecution execution = jobLauncher.run(job, jobParameters); LOGGER.info("Job Status : {}", execution.getStatus()); } catch (final Exception e) { e.printStackTrace(); LOGGER.error("Job failed {}", e.getMessage()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java
spring-batch/src/main/java/com/baeldung/batch/SpringBatchConfig.java
package com.baeldung.batch; import java.util.stream.Stream; import javax.sql.DataSource; import com.baeldung.batch.model.Transaction; import com.baeldung.batch.service.CustomItemProcessor; import com.baeldung.batch.service.CustomSkipPolicy; import com.baeldung.batch.service.MissingUsernameException; import com.baeldung.batch.service.NegativeAmountException; import com.baeldung.batch.service.RecordFieldSetMapper; import com.baeldung.batch.service.SkippingItemProcessor; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.UnexpectedInputException; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.batch.item.support.IteratorItemReader; import org.springframework.batch.item.xml.StaxEventItemWriter; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.Resource; import org.springframework.core.io.WritableResource; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.transaction.PlatformTransactionManager; @Configuration @Profile("spring") public class SpringBatchConfig { @Value("input/record.csv") private Resource inputCsv; @Value("input/recordWithInvalidData.csv") private Resource invalidInputCsv; @Value("file:xml/output.xml") private WritableResource outputXml; public ItemReader<Transaction> itemReader(Resource inputData) throws UnexpectedInputException { FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(inputData); DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } @Bean public ItemProcessor<Transaction, Transaction> itemProcessor() { return new CustomItemProcessor(); } @Bean public ItemProcessor<Transaction, Transaction> skippingItemProcessor() { return new SkippingItemProcessor(); } @Bean public ItemWriter<Transaction> itemWriter(Marshaller marshaller) { StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); itemWriter.setResource(outputXml); return itemWriter; } @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean protected Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("itemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) { return new StepBuilder("step1", jobRepository) .<Transaction, Transaction> chunk(10, transactionManager) .reader(itemReader(inputCsv)) .processor(processor) .writer(writer) .build(); } @Bean(name = "firstBatchJob") public Job job(JobRepository jobRepository, @Qualifier("step1") Step step1) { return new JobBuilder("firstBatchJob", jobRepository).preventRestart().start(step1).build(); } @Bean public Step skippingStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) { return new StepBuilder("skippingStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(invalidInputCsv)) .processor(processor) .writer(writer) .faultTolerant() .skipLimit(2) .skip(MissingUsernameException.class) .skip(NegativeAmountException.class) .build(); } @Bean(name = "skippingBatchJob") public Job skippingJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingStep") Step skippingStep) { return new JobBuilder("skippingBatchJob", jobRepository) .start(skippingStep) .preventRestart() .build(); } @Bean public Step skipPolicyStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) { return new StepBuilder("skipPolicyStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(invalidInputCsv)) .processor(processor) .writer(writer) .faultTolerant() .skipPolicy(new CustomSkipPolicy()) .build(); } @Bean(name = "skipPolicyBatchJob") public Job skipPolicyBatchJob(JobRepository jobRepository, @Qualifier("skipPolicyStep") Step skipPolicyStep) { return new JobBuilder("skipPolicyBatchJob", jobRepository) .start(skipPolicyStep) .preventRestart() .build(); } public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2) .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") .addScript("classpath:org/springframework/batch/core/schema-h2.sql") .build(); } @Bean(name = "transactionManager") public PlatformTransactionManager getTransactionManager() { return new ResourcelessTransactionManager(); } @Bean(name = "jobRepository") public JobRepository getJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); return factory.getObject(); } @Bean(name = "jobLauncher") public JobLauncher getJobLauncher() throws Exception { TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); // TaskExecutorJobLauncher's methods Throws Generic Exception, // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; } @Bean public Step firstStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("firstStep", jobRepository) .<String, String>chunk(1, transactionManager) .reader(new IteratorItemReader<>(Stream.of("Data from Step 1").iterator())) .processor(item -> { System.out.println("Processing: " + item); return item; }) .writer(items -> items.forEach(System.out::println)) .build(); } @Bean public Step secondStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("secondStep", jobRepository) .<String, String>chunk(1, transactionManager) .reader(new IteratorItemReader<>(Stream.of("Data from Step 2").iterator())) .processor(item -> { System.out.println("Processing: " + item); return item; }) .writer(items -> items.forEach(System.out::println)) .build(); } @Bean(name = "parentJob") public Job parentJob(JobRepository jobRepository, @Qualifier("firstStep") Step firstStep, @Qualifier("secondStep") Step secondStep) { return new JobBuilder("parentJob", jobRepository) .start(firstStep) .next(secondStep) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java
spring-batch/src/main/java/com/baeldung/batch/service/SkippingItemProcessor.java
package com.baeldung.batch.service; import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class SkippingItemProcessor implements ItemProcessor<Transaction, Transaction> { @Override public Transaction process(Transaction transaction) { System.out.println("SkippingItemProcessor: " + transaction); if (transaction.getUsername() == null || transaction.getUsername().isEmpty()) { throw new MissingUsernameException(); } double txAmount = transaction.getAmount(); if (txAmount < 0) { throw new NegativeAmountException(txAmount); } return transaction; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java
spring-batch/src/main/java/com/baeldung/batch/service/NegativeAmountException.java
package com.baeldung.batch.service; public class NegativeAmountException extends RuntimeException { private double amount; public NegativeAmountException(double amount){ this.amount = amount; } public double getAmount() { return amount; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java
spring-batch/src/main/java/com/baeldung/batch/service/CustomSkipPolicy.java
package com.baeldung.batch.service; import org.springframework.batch.core.step.skip.SkipLimitExceededException; import org.springframework.batch.core.step.skip.SkipPolicy; public class CustomSkipPolicy implements SkipPolicy { private static final int MAX_SKIP_COUNT = 2; private static final int INVALID_TX_AMOUNT_LIMIT = -1000; @Override public boolean shouldSkip(Throwable throwable, long skipCount) throws SkipLimitExceededException { if (throwable instanceof MissingUsernameException && skipCount < MAX_SKIP_COUNT) { return true; } // if (throwable instanceof NegativeAmountException ex && skipCount < MAX_SKIP_COUNT ) { // return ex.getAmount() >= INVALID_TX_AMOUNT_LIMIT; // } return false; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java
spring-batch/src/main/java/com/baeldung/batch/service/MissingUsernameException.java
package com.baeldung.batch.service; public class MissingUsernameException extends RuntimeException { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java
spring-batch/src/main/java/com/baeldung/batch/service/RecordFieldSetMapper.java
package com.baeldung.batch.service; import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class RecordFieldSetMapper implements FieldSetMapper<Transaction> { public Transaction mapFieldSet(FieldSet fieldSet) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyy"); Transaction transaction = new Transaction(); // you can either use the indices or custom names // I personally prefer the custom names easy for debugging and // validating the pipelines transaction.setUsername(fieldSet.readString("username")); transaction.setUserId(fieldSet.readInt("userid")); transaction.setAmount(fieldSet.readDouble(3)); // Converting the date String dateString = fieldSet.readString(2); transaction.setTransactionDate(LocalDate.parse(dateString, formatter).atStartOfDay()); return transaction; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java
spring-batch/src/main/java/com/baeldung/batch/service/CustomItemProcessor.java
package com.baeldung.batch.service; import com.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor<Transaction, Transaction> { public Transaction process(Transaction item) { System.out.println("Processing..." + item); return item; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java
spring-batch/src/main/java/com/baeldung/batch/service/adapter/LocalDateTimeAdapter.java
package com.baeldung.batch.service.adapter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import jakarta.xml.bind.annotation.adapters.XmlAdapter; public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); public LocalDateTime unmarshal(String v) throws Exception { return LocalDateTime.parse(v, DATE_TIME_FORMATTER); } public String marshal(LocalDateTime v) throws Exception { return DATE_TIME_FORMATTER.format(v); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java
spring-batch/src/main/java/com/baeldung/batch/model/Transaction.java
package com.baeldung.batch.model; import java.time.LocalDateTime; import com.baeldung.batch.service.adapter.LocalDateTimeAdapter; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @SuppressWarnings("restriction") @XmlRootElement(name = "transactionRecord") public class Transaction { private String username; private int userId; private int age; private String postCode; private LocalDateTime transactionDate; private double amount; /* getters and setters for the attributes */ public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } @XmlJavaTypeAdapter(LocalDateTimeAdapter.class) public LocalDateTime getTransactionDate() { return transactionDate; } public void setTransactionDate(LocalDateTime transactionDate) { this.transactionDate = transactionDate; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } @Override public String toString() { return "Transaction [username=" + username + ", userId=" + userId + ", age=" + age + ", postCode=" + postCode + ", transactionDate=" + transactionDate + ", amount=" + amount + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionConfig.java
spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionConfig.java
package com.baeldung.batch.partitioner; import com.baeldung.batch.model.Transaction; import com.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.StepScope; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.UnexpectedInputException; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.batch.item.xml.StaxEventItemWriter; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.task.TaskExecutor; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; import java.io.IOException; import java.text.ParseException; @Configuration @EnableBatchProcessing public class SpringBatchPartitionConfig { @Autowired private ResourcePatternResolver resourcePatternResolver; @Bean(name = "partitionerJob") public Job partitionerJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) throws UnexpectedInputException, ParseException { return new JobBuilder("partitionerJob", jobRepository) .start(partitionStep(jobRepository, transactionManager)) .build(); } @Bean public Step partitionStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) throws UnexpectedInputException, ParseException { return new StepBuilder("partitionStep", jobRepository) .partitioner("slaveStep", partitioner()) .step(slaveStep(jobRepository, transactionManager)) .taskExecutor(taskExecutor()) .build(); } @Bean public Step slaveStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) throws UnexpectedInputException, ParseException { return new StepBuilder("slaveStep", jobRepository) .<Transaction, Transaction>chunk(1, transactionManager) .reader(itemReader(null)) .writer(itemWriter(marshaller(), null)) .build(); } @Bean public CustomMultiResourcePartitioner partitioner() { CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner(); Resource[] resources; try { resources = resourcePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv"); } catch (IOException e) { throw new RuntimeException("I/O problems when resolving the input file pattern.", e); } partitioner.setResources(resources); return partitioner; } @Bean @StepScope public FlatFileItemReader<Transaction> itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(new ClassPathResource("input/partitioner/" + filename)); DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } @Bean(destroyMethod = "") @StepScope public StaxEventItemWriter<Transaction> itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) { StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename)); return itemWriter; } @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setMaxPoolSize(5); taskExecutor.setCorePoolSize(5); taskExecutor.setQueueCapacity(5); taskExecutor.afterPropertiesSet(); return taskExecutor; } @Bean(name = "jobRepository") public JobRepository getJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); return factory.getObject(); } @Bean(name = "dataSource") public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2) .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") .addScript("classpath:org/springframework/batch/core/schema-h2.sql") .build(); } @Bean(name = "transactionManager") public PlatformTransactionManager getTransactionManager() { return new ResourcelessTransactionManager(); } @Bean(name = "jobLauncher") public JobLauncher getJobLauncher() throws Exception { TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); // SimpleJobLauncher's methods Throws Generic Exception, // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionerApp.java
spring-batch/src/main/java/com/baeldung/batch/partitioner/SpringBatchPartitionerApp.java
package com.baeldung.batch.partitioner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringBatchPartitionerApp { private static final Logger LOGGER = LoggerFactory.getLogger(SpringBatchPartitionerApp.class); public static void main(final String[] args) { // Spring Java config final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(SpringBatchPartitionConfig.class); context.refresh(); final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); final Job job = (Job) context.getBean("partitionerJob"); LOGGER.info("Starting the batch job"); try { final JobExecution execution = jobLauncher.run(job, new JobParameters()); LOGGER.info("Job Status : {}", execution.getStatus()); } catch (final Exception e) { e.printStackTrace(); LOGGER.error("Job failed {}", e.getMessage()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java
spring-batch/src/main/java/com/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java
/* * Copyright 2006-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baeldung.batch.partitioner; import java.util.HashMap; import java.util.Map; import org.springframework.batch.core.partition.support.Partitioner; import org.springframework.batch.item.ExecutionContext; import org.springframework.core.io.Resource; import org.springframework.util.Assert; public class CustomMultiResourcePartitioner implements Partitioner { private static final String DEFAULT_KEY_NAME = "fileName"; private static final String PARTITION_KEY = "partition"; private Resource[] resources = new Resource[0]; private String keyName = DEFAULT_KEY_NAME; /** * The resources to assign to each partition. In Spring configuration you * can use a pattern to select multiple resources. * @param resources the resources to use */ public void setResources(Resource[] resources) { this.resources = resources; } /** * The name of the key for the file name in each {@link ExecutionContext}. * Defaults to "fileName". * @param keyName the value of the key */ public void setKeyName(String keyName) { this.keyName = keyName; } /** * Assign the filename of each of the injected resources to an * {@link ExecutionContext}. * * @see Partitioner#partition(int) */ @Override public Map<String, ExecutionContext> partition(int gridSize) { Map<String, ExecutionContext> map = new HashMap<>(gridSize); int i = 0, k = 1; for (Resource resource : resources) { ExecutionContext context = new ExecutionContext(); Assert.state(resource.exists(), "Resource does not exist: " + resource); context.putString(keyName, resource.getFilename()); context.putString("opFileName", "output" + k++ + ".xml"); map.put(PARTITION_KEY + i, context); i++; } return map; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBootBatchConfig.java
spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBootBatchConfig.java
package com.baeldung.batch.springboot; import com.baeldung.batch.model.Transaction; import com.baeldung.batch.service.*; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.UnexpectedInputException; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.batch.item.xml.StaxEventItemWriter; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.Resource; import org.springframework.core.io.WritableResource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableBatchProcessing @Profile("spring-boot") public class SpringBootBatchConfig { @Value("input/record.csv") private Resource inputCsv; @Value("input/recordWithInvalidData.csv") private Resource invalidInputCsv; @Value("file:xml/output.xml") private WritableResource outputXml; public ItemReader<Transaction> itemReader(Resource inputData) throws UnexpectedInputException { FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(inputData); DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } @Bean public ItemProcessor<Transaction, Transaction> itemProcessor() { return new CustomItemProcessor(); } @Bean public ItemProcessor<Transaction, Transaction> skippingItemProcessor() { return new SkippingItemProcessor(); } @Bean public ItemWriter<Transaction> itemWriter3(Marshaller marshaller) { StaxEventItemWriter<Transaction> itemWriter3 = new StaxEventItemWriter<>(); itemWriter3.setMarshaller(marshaller); itemWriter3.setRootTagName("transactionRecord"); itemWriter3.setResource(outputXml); return itemWriter3; } @Bean public Marshaller marshaller3() { Jaxb2Marshaller marshaller3 = new Jaxb2Marshaller(); marshaller3.setClassesToBeBound(Transaction.class); return marshaller3; } @Bean(name = "step1") protected Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("itemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> itemWriter3) { return new StepBuilder("step1", jobRepository) .<Transaction, Transaction> chunk(10, transactionManager) .reader(itemReader(inputCsv)) .processor(processor) .writer(itemWriter3) .build(); } @Bean(name = "firstBatchJob") public Job job(@Qualifier("step1") Step step1, JobRepository jobRepository) { return new JobBuilder("firstBatchJob", jobRepository).start(step1).build(); } @Bean public Step skippingStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> itemWriter3) { return new StepBuilder("skippingStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(invalidInputCsv)) .processor(processor) .writer(itemWriter3) .faultTolerant() .skipLimit(2) .skip(MissingUsernameException.class) .skip(NegativeAmountException.class) .build(); } @Bean(name = "skippingBatchJob") public Job skippingJob(JobRepository jobRepository, @Qualifier("skippingStep") Step skippingStep) { return new JobBuilder("skippingBatchJob", jobRepository) .start(skippingStep) .build(); } @Bean(name = "skipPolicyStep") public Step skipPolicyStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> itemWriter3) { return new StepBuilder("skipPolicyStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(invalidInputCsv)) .processor(processor) .writer(itemWriter3) .faultTolerant() .skipPolicy(new CustomSkipPolicy()) .build(); } @Bean(name = "skipPolicyBatchJob") public Job skipPolicyBatchJob(JobRepository jobRepository, @Qualifier("skipPolicyStep") Step skipPolicyStep) { return new JobBuilder("skipPolicyBatchJob", jobRepository) .start(skipPolicyStep) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBatchApplication.java
spring-batch/src/main/java/com/baeldung/batch/springboot/SpringBatchApplication.java
package com.baeldung.batch.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBatchApplication { public static void main(String[] args) { SpringApplication springApp = new SpringApplication(SpringBatchApplication.class); springApp.setAdditionalProfiles("spring-boot"); springApp.run(args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/bootbatch/CoffeeItemProcessor.java
spring-batch/src/main/java/com/baeldung/bootbatch/CoffeeItemProcessor.java
package com.baeldung.bootbatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class CoffeeItemProcessor implements ItemProcessor<Coffee, Coffee> { private static final Logger LOGGER = LoggerFactory.getLogger(CoffeeItemProcessor.class); @Override public Coffee process(final Coffee coffee) { String brand = coffee.getBrand().toUpperCase(); String origin = coffee.getOrigin().toUpperCase(); String chracteristics = coffee.getCharacteristics().toUpperCase(); Coffee transformedCoffee = new Coffee(brand, origin, chracteristics); LOGGER.info("Converting ( {} ) into ( {} )", coffee, transformedCoffee); return transformedCoffee; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/bootbatch/Coffee.java
spring-batch/src/main/java/com/baeldung/bootbatch/Coffee.java
package com.baeldung.bootbatch; public class Coffee { private String brand; private String origin; private String characteristics; public Coffee() { } public Coffee(String brand, String origin, String characteristics) { this.brand = brand; this.origin = origin; this.characteristics = characteristics; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getCharacteristics() { return characteristics; } public void setCharacteristics(String characteristics) { this.characteristics = characteristics; } @Override public String toString() { return "Coffee [brand=" + getBrand() + ", origin=" + getOrigin() + ", characteristics=" + getCharacteristics() + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/bootbatch/SpringBootBatchProcessingApplication.java
spring-batch/src/main/java/com/baeldung/bootbatch/SpringBootBatchProcessingApplication.java
package com.baeldung.bootbatch; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootBatchProcessingApplication { public static void main(String[] args) { SpringApplication.run(SpringBootBatchProcessingApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/bootbatch/JobCompletionNotificationListener.java
spring-batch/src/main/java/com/baeldung/bootbatch/JobCompletionNotificationListener.java
package com.baeldung.bootbatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class JobCompletionNotificationListener implements JobExecutionListener { private static final Logger LOGGER = LoggerFactory.getLogger(JobCompletionNotificationListener.class); private final JdbcTemplate jdbcTemplate; @Autowired public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void afterJob(JobExecution jobExecution) { if (jobExecution.getStatus() == BatchStatus.COMPLETED) { LOGGER.info("!!! JOB FINISHED! Time to verify the results"); String query = "SELECT brand, origin, characteristics FROM coffee"; jdbcTemplate.query(query, (rs, row) -> new Coffee(rs.getString(1), rs.getString(2), rs.getString(3))) .forEach(coffee -> LOGGER.info("Found < {} > in the database.", coffee)); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/bootbatch/BatchConfiguration.java
spring-batch/src/main/java/com/baeldung/bootbatch/BatchConfiguration.java
package com.baeldung.bootbatch; import javax.sql.DataSource; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider; import org.springframework.batch.item.database.JdbcBatchItemWriter; import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.task.VirtualThreadTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; @Configuration public class BatchConfiguration { @Value("${file.input}") private String fileInput; @Bean public VirtualThreadTaskExecutor taskExecutor() { return new VirtualThreadTaskExecutor("virtual-thread-executor"); } @Bean public FlatFileItemReader<Coffee> reader() { return new FlatFileItemReaderBuilder<Coffee>().name("coffeeItemReader") .resource(new ClassPathResource(fileInput)) .delimited() .names(new String[] { "brand", "origin", "characteristics" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<Coffee>() {{ setTargetType(Coffee.class); }}) .build(); } @Bean public CoffeeItemProcessor processor() { return new CoffeeItemProcessor(); } @Bean public JdbcBatchItemWriter<Coffee> writer(DataSource dataSource) { return new JdbcBatchItemWriterBuilder<Coffee>().itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()) .sql("INSERT INTO coffee (brand, origin, characteristics) VALUES (:brand, :origin, :characteristics)") .dataSource(dataSource) .build(); } @Bean public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) { return new JobBuilder("importUserJob", jobRepository) .incrementer(new RunIdIncrementer()) .listener(listener) .flow(step1) .end() .build(); } @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter<Coffee> writer, VirtualThreadTaskExecutor taskExecutor) { return new StepBuilder("step1", jobRepository) .<Coffee, Coffee> chunk(10, transactionManager) .reader(reader()) .processor(processor()) .writer(writer) .taskExecutor(taskExecutor) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java
spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchApplication.java
package com.baeldung.batchtesting; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource("classpath:batchtesting/application.properties") public class SpringBatchApplication implements CommandLineRunner { @Autowired private JobLauncher jobLauncher; @Autowired @Qualifier("transformBooksRecords") private Job transformBooksRecordsJob; @Value("${file.input}") private String input; @Value("${file.output}") private String output; public static void main(String[] args) { SpringApplication.run(SpringBatchApplication.class, args); } @Override public void run(String... args) throws Exception { JobParametersBuilder paramsBuilder = new JobParametersBuilder(); paramsBuilder.addString("file.input", input); paramsBuilder.addString("file.output", output); jobLauncher.run(transformBooksRecordsJob, paramsBuilder.toJobParameters()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java
spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java
package com.baeldung.batchtesting; import com.baeldung.batchtesting.model.Book; import com.baeldung.batchtesting.model.BookDetails; import com.baeldung.batchtesting.model.BookRecord; import com.baeldung.batchtesting.service.BookDetailsItemProcessor; import com.baeldung.batchtesting.service.BookItemProcessor; import com.baeldung.batchtesting.service.BookRecordFieldSetMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.StepScope; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.json.JacksonJsonObjectMarshaller; import org.springframework.batch.item.json.JsonFileItemWriter; import org.springframework.batch.item.json.builder.JsonFileItemWriterBuilder; import org.springframework.batch.item.support.ListItemWriter; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.FileSystemResource; import org.springframework.transaction.PlatformTransactionManager; @Configuration public class SpringBatchConfiguration { private static Logger LOGGER = LoggerFactory.getLogger(SpringBatchConfiguration.class); private static final String[] TOKENS = { "bookname", "bookauthor", "bookformat", "isbn", "publishyear" }; @Bean @StepScope public FlatFileItemReader<BookRecord> csvItemReader(@Value("#{jobParameters['file.input']}") String input) { FlatFileItemReaderBuilder<BookRecord> builder = new FlatFileItemReaderBuilder<>(); FieldSetMapper<BookRecord> bookRecordFieldSetMapper = new BookRecordFieldSetMapper(); LOGGER.info("Configuring reader to input {}", input); // @formatter:off return builder .name("bookRecordItemReader") .resource(new FileSystemResource(input)) .delimited() .names(TOKENS) .fieldSetMapper(bookRecordFieldSetMapper) .build(); // @formatter:on } @Bean @StepScope public JsonFileItemWriter<Book> jsonItemWriter(@Value("#{jobParameters['file.output']}") String output) { JsonFileItemWriterBuilder<Book> builder = new JsonFileItemWriterBuilder<>(); JacksonJsonObjectMarshaller<Book> marshaller = new JacksonJsonObjectMarshaller<>(); LOGGER.info("Configuring writer to output {}", output); // @formatter:off return builder .name("bookItemWriter") .jsonObjectMarshaller(marshaller) .resource(new FileSystemResource(output)) .build(); // @formatter:on } @Bean @StepScope public ListItemWriter<BookDetails> listItemWriter() { return new ListItemWriter<>(); } @Bean @StepScope public BookItemProcessor bookItemProcessor() { return new BookItemProcessor(); } @Bean @StepScope public BookDetailsItemProcessor bookDetailsItemProcessor() { return new BookDetailsItemProcessor(); } @Bean(name = "step1") public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader<BookRecord> csvItemReader, ItemWriter<Book> jsonItemWriter) { // @formatter:off return new StepBuilder("step1", jobRepository) .<BookRecord, Book> chunk(3, transactionManager) .reader(csvItemReader) .processor(bookItemProcessor()) .writer(jsonItemWriter) .build(); // @formatter:on } @Bean(name = "step2") public Step step2(JobRepository jobRepository, PlatformTransactionManager transactionManager, ItemReader<BookRecord> csvItemReader, ItemWriter<BookDetails> listItemWriter) { // @formatter:off return new StepBuilder("step2", jobRepository) .<BookRecord, BookDetails> chunk(3, transactionManager) .reader(csvItemReader) .processor(bookDetailsItemProcessor()) .writer(listItemWriter) .build(); // @formatter:on } @Bean(name = "transformBooksRecords") public Job transformBookRecords(JobRepository jobRepository, @Qualifier("step1") Step step1, @Qualifier("step2") Step step2) { // @formatter:off return new JobBuilder("transformBooksRecords", jobRepository) .flow(step1) .next(step2) .end() .build(); // @formatter:on } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java
spring-batch/src/main/java/com/baeldung/batchtesting/service/BookRecordFieldSetMapper.java
package com.baeldung.batchtesting.service; import com.baeldung.batchtesting.model.BookRecord; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; public class BookRecordFieldSetMapper implements FieldSetMapper<BookRecord> { @Override public BookRecord mapFieldSet(FieldSet fieldSet) { BookRecord bookRecord = new BookRecord(); bookRecord.setBookName(fieldSet.readString("bookname")); bookRecord.setBookAuthor(fieldSet.readString("bookauthor")); bookRecord.setBookFormat(fieldSet.readString("bookformat")); bookRecord.setBookISBN(fieldSet.readString("isbn")); bookRecord.setPublishingYear(fieldSet.readString("publishyear")); return bookRecord; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java
spring-batch/src/main/java/com/baeldung/batchtesting/service/BookItemProcessor.java
package com.baeldung.batchtesting.service; import com.baeldung.batchtesting.model.Book; import com.baeldung.batchtesting.model.BookRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class BookItemProcessor implements ItemProcessor<BookRecord, Book> { private static Logger LOGGER = LoggerFactory.getLogger(BookItemProcessor.class); @Override public Book process(BookRecord item) { Book book = new Book(); book.setAuthor(item.getBookAuthor()); book.setName(item.getBookName()); LOGGER.info("Processing book {}", book); return book; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java
spring-batch/src/main/java/com/baeldung/batchtesting/service/BookDetailsItemProcessor.java
package com.baeldung.batchtesting.service; import com.baeldung.batchtesting.model.BookDetails; import com.baeldung.batchtesting.model.BookRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class BookDetailsItemProcessor implements ItemProcessor<BookRecord, BookDetails> { private static Logger LOGGER = LoggerFactory.getLogger(BookDetailsItemProcessor.class); @Override public BookDetails process(BookRecord item) { BookDetails bookDetails = new BookDetails(); bookDetails.setBookFormat(item.getBookFormat()); bookDetails.setBookISBN(item.getBookISBN()); bookDetails.setPublishingYear(item.getPublishingYear()); bookDetails.setBookName(item.getBookName()); LOGGER.info("Processing bookdetails {}", bookDetails); return bookDetails; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java
spring-batch/src/main/java/com/baeldung/batchtesting/model/BookDetails.java
package com.baeldung.batchtesting.model; public class BookDetails { private String bookName; private String bookFormat; private String publishingYear; private String bookISBN; public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getBookFormat() { return bookFormat; } public void setBookFormat(String bookFormat) { this.bookFormat = bookFormat; } public String getPublishingYear() { return publishingYear; } public void setPublishingYear(String publishingYear) { this.publishingYear = publishingYear; } public String getBookISBN() { return bookISBN; } public void setBookISBN(String bookISBN) { this.bookISBN = bookISBN; } @Override public String toString() { return "BookDetails [bookName=" + bookName + ", bookFormat=" + bookFormat + ", publishingYear=" + publishingYear + ", bookISBN=" + bookISBN + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java
spring-batch/src/main/java/com/baeldung/batchtesting/model/Book.java
package com.baeldung.batchtesting.model; public class Book { private String author; private String name; public Book() { } public String getAuthor() { return author; } public String getName() { return name; } public void setAuthor(String author) { this.author = author; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Book [author=" + author + ", name=" + name + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java
spring-batch/src/main/java/com/baeldung/batchtesting/model/BookRecord.java
package com.baeldung.batchtesting.model; public class BookRecord { private String bookName; private String bookAuthor; private String bookFormat; private String bookISBN; private String publishingYear; public void setBookName(String bookName) { this.bookName = bookName; } public void setBookAuthor(String bookAuthor) { this.bookAuthor = bookAuthor; } public void setBookFormat(String bookFormat) { this.bookFormat = bookFormat; } public void setBookISBN(String bookISBN) { this.bookISBN = bookISBN; } public void setPublishingYear(String publishingYear) { this.publishingYear = publishingYear; } public String getBookName() { return bookName; } public String getBookAuthor() { return bookAuthor; } public String getBookFormat() { return bookFormat; } public String getBookISBN() { return bookISBN; } public String getPublishingYear() { return publishingYear; } @Override public String toString() { return "BookRecord [bookName=" + bookName + ", bookAuthor=" + bookAuthor + ", bookFormat=" + bookFormat + ", bookISBN=" + bookISBN + ", publishingYear=" + publishingYear + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/ContainsJobParameters.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/ContainsJobParameters.java
package com.baeldung.batchreaderproperties; import java.time.ZonedDateTime; public interface ContainsJobParameters { ZonedDateTime getTriggeredDateTime(); String getTraceId(); void setTriggeredDateTime(ZonedDateTime triggeredDateTime); void setTraceId(String traceId); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/SpringBatchExpireMedicationApplication.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/SpringBatchExpireMedicationApplication.java
package com.baeldung.batchreaderproperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource("classpath:disable-job-autorun.properties") public class SpringBatchExpireMedicationApplication { public static void main(String[] args) { SpringApplication.run(SpringBatchExpireMedicationApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/MedExpirationBatchRunner.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/MedExpirationBatchRunner.java
package com.baeldung.batchreaderproperties; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.UUID; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @Slf4j @Component @EnableScheduling public class MedExpirationBatchRunner { @Autowired private Job medExpirationJob; @Autowired private JobLauncher jobLauncher; @Value("${batch.medicine.alert_type}") private String alertType; @Value("${batch.medicine.expiration.default.days}") private long defaultExpiration; @Value("${batch.medicine.start.sale.default.days}") private long saleStartDays; @Value("${batch.medicine.sale}") private double medicineSale; @Scheduled(cron = "${batch.medicine.cron}", zone = "GMT") public void runJob() { ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); launchJob(now); } public void launchJob(ZonedDateTime triggerZonedDateTime) { try { JobParameters jobParameters = new JobParametersBuilder().addString(BatchConstants.TRIGGERED_DATE_TIME, triggerZonedDateTime.toString()) .addString(BatchConstants.ALERT_TYPE, alertType) .addLong(BatchConstants.DEFAULT_EXPIRATION, defaultExpiration) .addLong(BatchConstants.SALE_STARTS_DAYS, saleStartDays) .addDouble(BatchConstants.MEDICINE_SALE, medicineSale) .addString(BatchConstants.TRACE_ID, UUID.randomUUID() .toString()) .toJobParameters(); jobLauncher.run(medExpirationJob, jobParameters); } catch (Exception e) { log.error("Failed to run", e); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/BatchConstants.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/BatchConstants.java
package com.baeldung.batchreaderproperties; public class BatchConstants { public static final String TRIGGERED_DATE_TIME = "TRIGGERED_DATE_TIME"; public static final String TRACE_ID = "TRACE_ID"; public static final String ALERT_TYPE = "ALERT_TYPE"; public static final String DEFAULT_EXPIRATION = "DEFAULT_EXPIRATION"; public static final String SALE_STARTS_DAYS = "SALE_STARTS_DAYS"; public static final String MEDICINE_SALE = "MEDICINE_SALE"; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/BatchConfiguration.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/BatchConfiguration.java
package com.baeldung.batchreaderproperties; import java.time.ZonedDateTime; import java.util.Map; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.StepScope; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; import com.baeldung.batchreaderproperties.job.ExpiresSoonMedicineReader; import com.baeldung.batchreaderproperties.job.MedicineProcessor; import com.baeldung.batchreaderproperties.job.MedicineWriter; import com.baeldung.batchreaderproperties.model.Medicine; @Configuration public class BatchConfiguration { @Bean @StepScope public ExpiresSoonMedicineReader expiresSoonMedicineReader(JdbcTemplate jdbcTemplate, @Value("#{jobParameters}") Map<String, Object> jobParameters) { ExpiresSoonMedicineReader medicineReader = new ExpiresSoonMedicineReader(jdbcTemplate); enrichWithJobParameters(jobParameters, medicineReader); return medicineReader; } @Bean @StepScope public MedicineProcessor medicineProcessor(@Value("#{jobParameters}") Map<String, Object> jobParameters) { MedicineProcessor medicineProcessor = new MedicineProcessor(); enrichWithJobParameters(jobParameters, medicineProcessor); return medicineProcessor; } @Bean @StepScope public MedicineWriter medicineWriter(@Value("#{jobParameters}") Map<String, Object> jobParameters) { MedicineWriter medicineWriter = new MedicineWriter(); enrichWithJobParameters(jobParameters, medicineWriter); return medicineWriter; } @Bean public Job medExpirationJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, MedicineWriter medicineWriter, MedicineProcessor medicineProcessor, ExpiresSoonMedicineReader expiresSoonMedicineReader) { Step notifyAboutExpiringMedicine = new StepBuilder("notifyAboutExpiringMedicine", jobRepository).<Medicine, Medicine>chunk(10) .reader(expiresSoonMedicineReader) .processor(medicineProcessor) .writer(medicineWriter) .faultTolerant() .transactionManager(transactionManager) .build(); return new JobBuilder("medExpirationJob", jobRepository).incrementer(new RunIdIncrementer()) .start(notifyAboutExpiringMedicine) .build(); } private void enrichWithJobParameters(Map<String, Object> jobParameters, ContainsJobParameters container) { if (jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) != null) { container.setTriggeredDateTime(ZonedDateTime.parse(jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) .toString())); } if (jobParameters.get(BatchConstants.TRACE_ID) != null) { container.setTraceId(jobParameters.get(BatchConstants.TRACE_ID) .toString()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/model/MedicineCategory.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/model/MedicineCategory.java
package com.baeldung.batchreaderproperties.model; public enum MedicineCategory { ANESTHETICS, ANTIBACTERIALS, ANTIDEPRESSANTS; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/model/Medicine.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/model/Medicine.java
package com.baeldung.batchreaderproperties.model; import java.sql.Timestamp; import java.util.UUID; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Medicine { private UUID id; private String name; private MedicineCategory type; private Timestamp expirationDate; private Double originalPrice; private Double salePrice; }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/job/ExpiresSoonMedicineReader.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/job/ExpiresSoonMedicineReader.java
package com.baeldung.batchreaderproperties.job; import java.sql.ResultSet; import java.sql.SQLException; import java.time.ZonedDateTime; import java.util.List; import java.util.UUID; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.annotation.BeforeStep; import org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.ClassUtils; import com.baeldung.batchreaderproperties.ContainsJobParameters; import com.baeldung.batchreaderproperties.model.Medicine; import com.baeldung.batchreaderproperties.model.MedicineCategory; import jakarta.annotation.PostConstruct; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Getter @Setter @RequiredArgsConstructor @Slf4j public class ExpiresSoonMedicineReader extends AbstractItemCountingItemStreamItemReader<Medicine> implements ContainsJobParameters { private static final String FIND_EXPIRING_SOON_MEDICINE = "Select * from MEDICINE where EXPIRATION_DATE >= CURRENT_DATE AND EXPIRATION_DATE <= DATEADD('DAY', ?, CURRENT_DATE)"; //common job parameters populated in bean initialization private ZonedDateTime triggeredDateTime; private String traceId; //job parameter injected by Spring @Value("#{jobParameters['DEFAULT_EXPIRATION']}") private long defaultExpiration; private final JdbcTemplate jdbcTemplate; private List<Medicine> expiringMedicineList; @Override protected Medicine doRead() { if (expiringMedicineList != null && !expiringMedicineList.isEmpty()) { return expiringMedicineList.get(getCurrentItemCount() - 1); } return null; } @Override protected void doOpen() { expiringMedicineList = jdbcTemplate.query(FIND_EXPIRING_SOON_MEDICINE, ps -> ps.setLong(1, defaultExpiration), (rs, row) -> getMedicine(rs)); log.info("Trace = {}. Found {} meds that expires soon", traceId, expiringMedicineList.size()); if (!expiringMedicineList.isEmpty()) { setMaxItemCount(expiringMedicineList.size()); } } private static Medicine getMedicine(ResultSet rs) throws SQLException { return new Medicine(UUID.fromString(rs.getString(1)), rs.getString(2), MedicineCategory.valueOf(rs.getString(3)), rs.getTimestamp(4), rs.getDouble(5), rs.getObject(6, Double.class)); } @Override protected void doClose() { } @PostConstruct public void init() { setName(ClassUtils.getShortName(getClass())); } @BeforeStep public void beforeStep(StepExecution stepExecution) { JobParameters parameters = stepExecution.getJobExecution() .getJobParameters(); log.info("Before step params: {}", parameters); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/job/MedicineProcessor.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/job/MedicineProcessor.java
package com.baeldung.batchreaderproperties.job; import java.sql.Timestamp; import java.time.Duration; import java.time.ZoneId; import java.time.ZonedDateTime; import org.springframework.batch.item.ItemProcessor; import org.springframework.beans.factory.annotation.Value; import com.baeldung.batchreaderproperties.ContainsJobParameters; import com.baeldung.batchreaderproperties.model.Medicine; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j @Getter @Setter public class MedicineProcessor implements ItemProcessor<Medicine, Medicine>, ContainsJobParameters { private ZonedDateTime triggeredDateTime; private String traceId; @Value("#{jobParameters['SALE_STARTS_DAYS']}") private long saleStartsDays; @Value("#{jobParameters['MEDICINE_SALE']}") private double medicineSale; @Override public Medicine process(Medicine medicine) { final Double originalPrice = medicine.getOriginalPrice(); final Timestamp expirationDate = medicine.getExpirationDate(); Duration daysToExpiration = Duration.between(ZonedDateTime.now(), ZonedDateTime.ofInstant(expirationDate.toInstant(), ZoneId.of("UTC"))); if (daysToExpiration.toDays() < saleStartsDays) { medicine.setSalePrice(originalPrice * (1 - medicineSale)); log.info("Trace = {}, calculated new sale price {} for medicine {}", traceId, medicine.getSalePrice(), medicine.getId()); } return medicine; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchreaderproperties/job/MedicineWriter.java
spring-batch/src/main/java/com/baeldung/batchreaderproperties/job/MedicineWriter.java
package com.baeldung.batchreaderproperties.job; import java.time.ZonedDateTime; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import com.baeldung.batchreaderproperties.ContainsJobParameters; import com.baeldung.batchreaderproperties.model.Medicine; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Getter @Setter @Slf4j public class MedicineWriter implements ItemWriter<Medicine>, ContainsJobParameters { private ZonedDateTime triggeredDateTime; private String traceId; @Override public void write(Chunk<? extends Medicine> chunk) { chunk.forEach((medicine) -> log.info("Trace = {}. This medicine is expiring {}", traceId, medicine)); log.info("Finishing job started at {}", triggeredDateTime); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java
spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchSchedulerApplication.java
package com.baeldung.batchscheduler; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBatchSchedulerApplication { public static void main(String[] args) { SpringApplication.run(SpringBatchSchedulerApplication.class, args); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
spring-batch/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
package com.baeldung.batchscheduler; import java.util.Date; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.Step; import org.springframework.batch.core.job.builder.JobBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.ScheduledMethodRunnable; import org.springframework.transaction.PlatformTransactionManager; import com.baeldung.batchscheduler.model.Book; @Configuration @EnableScheduling public class SpringBatchScheduler { private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class); private AtomicBoolean enabled = new AtomicBoolean(true); private AtomicInteger batchRunCounter = new AtomicInteger(0); private final Map<Object, ScheduledFuture<?>> scheduledTasks = new IdentityHashMap<>(); @Autowired private JobLauncher jobLauncher; @Autowired private JobRepository jobRepository; @Autowired private PlatformTransactionManager transactionManager; @Scheduled(fixedRate = 2000) public void launchJob() throws Exception { Date date = new Date(); logger.debug("scheduler starts at " + date); if (enabled.get()) { JobExecution jobExecution = jobLauncher.run(job(jobRepository, transactionManager), new JobParametersBuilder().addDate("launchDate", date) .toJobParameters()); batchRunCounter.incrementAndGet(); logger.debug("Batch job ends with status as " + jobExecution.getStatus()); } logger.debug("scheduler ends "); } public void stop() { enabled.set(false); } public void start() { enabled.set(true); } @Bean public TaskScheduler poolScheduler() { return new CustomTaskScheduler(); } private class CustomTaskScheduler extends ThreadPoolTaskScheduler { private static final long serialVersionUID = -7142624085505040603L; @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) { ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; scheduledTasks.put(runnable.getTarget(), future); return future; } } public void cancelFutureSchedulerTasks() { scheduledTasks.forEach((k, v) -> { if (k instanceof SpringBatchScheduler) { v.cancel(false); } }); } @Bean public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("job", jobRepository) .start(readBooks(jobRepository, transactionManager)) .build(); } @Bean protected Step readBooks(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("readBooks", jobRepository) .<Book, Book> chunk(2, transactionManager) .reader(reader()) .writer(writer()) .build(); } @Bean public FlatFileItemReader<Book> reader() { return new FlatFileItemReaderBuilder<Book>().name("bookItemReader") .resource(new ClassPathResource("books.csv")) .delimited() .names(new String[] { "id", "name" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<>() { { setTargetType(Book.class); } }) .build(); } @Bean public ItemWriter<Book> writer() { return items -> { logger.debug("writer..." + items.size()); for (Book item : items) { logger.debug(item.toString()); } }; } public AtomicInteger getBatchRunCounter() { return batchRunCounter; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java
spring-batch/src/main/java/com/baeldung/batchscheduler/model/Book.java
package com.baeldung.batchscheduler.model; public class Book { private int id; private String name; public Book() {} public Book(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "Book [id=" + id + ", name=" + name + "]"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/model/Line.java
package com.baeldung.taskletsvschunks.model; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import java.io.Serializable; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Line implements Serializable { private String name; @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate dob; private Long age; public Line(String name, LocalDate dob) { this.name = name; this.dob = dob; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(this.name); sb.append(","); sb.append(this.dob.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); if (this.age != null) { sb.append(","); sb.append(this.age); } sb.append("]"); return sb.toString(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LineProcessor.java
package com.baeldung.taskletsvschunks.chunks; import com.baeldung.taskletsvschunks.model.Line; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.item.ItemProcessor; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public class LineProcessor implements ItemProcessor<Line, Line>, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LineProcessor.class); @Override public void beforeStep(StepExecution stepExecution) { logger.debug("Line Processor initialized."); } @Override public Line process(Line line) throws Exception { long age = ChronoUnit.YEARS.between(line.getDob(), LocalDate.now()); logger.debug("Calculated age " + age + " for line " + line.toString()); line.setAge(age); return line; } @Override public ExitStatus afterStep(StepExecution stepExecution) { logger.debug("Line Processor ended."); return ExitStatus.COMPLETED; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java
spring-batch/src/main/java/com/baeldung/taskletsvschunks/chunks/LinesWriter.java
package com.baeldung.taskletsvschunks.chunks; import com.baeldung.taskletsvschunks.model.Line; import com.baeldung.taskletsvschunks.utils.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; public class LinesWriter implements ItemWriter<Line>, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); private FileUtils fu; @Override public void beforeStep(StepExecution stepExecution) { fu = new FileUtils("output.csv"); logger.debug("Line Writer initialized."); } @Override public ExitStatus afterStep(StepExecution stepExecution) { fu.closeWriter(); logger.debug("Line Writer ended."); return ExitStatus.COMPLETED; } @Override public void write(Chunk<? extends Line> lines) { for (Line line : lines) { fu.writeLine(line); logger.debug("Wrote line " + line.toString()); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false