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 |
|---|---|---|---|---|---|---|---|---|
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/web/controller/ValidateController.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/web/controller/ValidateController.java | package cc.mrbird.web.controller;
import cc.mrbird.validate.code.ImageCode;
import cc.mrbird.validate.smscode.SmsCode;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@RestController
public class ValidateController {
public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
public final static String SESSION_KEY_SMS_CODE = "SESSION_KEY_SMS_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = createImageCode();
ImageCode codeInRedis = new ImageCode(null,imageCode.getCode(),imageCode.getExpireTime());
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, codeInRedis);
ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());
}
@GetMapping("/code/sms")
public void createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) {
SmsCode smsCode = createSMSCode();
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_SMS_CODE + mobile, smsCode);
// 输出验证码到控制台代替短信发送服务
System.out.println("您的登录验证码为:" + smsCode.getCode() + ",有效时间为60秒");
}
private SmsCode createSMSCode() {
String code = RandomStringUtils.randomNumeric(6);
return new SmsCode(code, 60);
}
private ImageCode createImageCode() {
int width = 100; // 验证码图片宽度
int height = 36; // 验证码图片长度
int length = 4; // 验证码位数
int expireIn = 60; // 验证码有效时间 60s
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sRand = new StringBuilder();
for (int i = 0; i < length; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand.append(rand);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
return new ImageCode(image, sRand.toString(), expireIn);
}
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/code/ImageCode.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/code/ImageCode.java | package cc.mrbird.validate.code;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.time.LocalDateTime;
public class ImageCode implements Serializable {
private static final long serialVersionUID = -7831615057416168810L;
private BufferedImage image;
private String code;
private LocalDateTime expireTime;
public ImageCode(BufferedImage image, String code, int expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
this.image = image;
this.code = code;
this.expireTime = expireTime;
}
boolean isExpire() {
return LocalDateTime.now().isAfter(expireTime);
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/code/ValidateCodeException.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/code/ValidateCodeException.java | package cc.mrbird.validate.code;
import org.springframework.security.core.AuthenticationException;
public class ValidateCodeException extends AuthenticationException {
private static final long serialVersionUID = 5022575393500654458L;
public ValidateCodeException(String message) {
super(message);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/code/ValidateCodeFilter.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/code/ValidateCodeFilter.java | package cc.mrbird.validate.code;
import cc.mrbird.web.controller.ValidateController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI())
&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
try {
validateCode(new ServletWebRequest(httpServletRequest));
} catch (ValidateCodeException e) {
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
return;
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");
if (StringUtils.isBlank(codeInRequest)) {
throw new ValidateCodeException("验证码不能为空!");
}
if (codeInSession == null) {
throw new ValidateCodeException("验证码不存在!");
}
if (codeInSession.isExpire()) {
sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
throw new ValidateCodeException("验证码已过期!");
}
if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
throw new ValidateCodeException("验证码不正确!");
}
sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationToken.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationToken.java | package cc.mrbird.validate.smscode;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import java.util.Collection;
public class SmsAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
public SmsAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public SmsAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true); // must use super, as we override
}
@Override
public Object getCredentials() {
return null;
}
public Object getPrincipal() {
return this.principal;
}
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationProvider.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationProvider.java | package cc.mrbird.validate.smscode;
import cc.mrbird.security.browser.UserDetailService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
public class SmsAuthenticationProvider implements AuthenticationProvider {
private UserDetailService userDetailService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());
if (userDetails == null)
throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户");
SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
authenticationResult.setDetails(authenticationToken.getDetails());
return authenticationResult;
}
@Override
public boolean supports(Class<?> aClass) {
return SmsAuthenticationToken.class.isAssignableFrom(aClass);
}
public UserDetailService getUserDetailService() {
return userDetailService;
}
public void setUserDetailService(UserDetailService userDetailService) {
this.userDetailService = userDetailService;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationFilter.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationFilter.java | package cc.mrbird.validate.smscode;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String MOBILE_KEY = "mobile";
private String mobileParameter = MOBILE_KEY;
private boolean postOnly = true;
public SmsAuthenticationFilter() {
super(new AntPathRequestMatcher("/login/mobile", "POST"));
}
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
SmsAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
protected String obtainMobile(HttpServletRequest request) {
return request.getParameter(mobileParameter);
}
protected void setDetails(HttpServletRequest request,
SmsAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
public void setMobileParameter(String mobileParameter) {
Assert.hasText(mobileParameter, "mobile parameter must not be empty or null");
this.mobileParameter = mobileParameter;
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getMobileParameter() {
return mobileParameter;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsCodeFilter.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsCodeFilter.java | package cc.mrbird.validate.smscode;
import cc.mrbird.validate.code.ValidateCodeException;
import cc.mrbird.web.controller.ValidateController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SmsCodeFilter extends OncePerRequestFilter {
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (StringUtils.equalsIgnoreCase("/login/mobile", httpServletRequest.getRequestURI())
&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
try {
validateCode(new ServletWebRequest(httpServletRequest));
} catch (ValidateCodeException e) {
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
return;
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
String smsCodeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsCode");
String mobileInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsCode");
SmsCode codeInSession = (SmsCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_SMS_CODE + mobileInRequest);
if (StringUtils.isBlank(smsCodeInRequest)) {
throw new ValidateCodeException("验证码不能为空!");
}
if (codeInSession == null) {
throw new ValidateCodeException("验证码不存在!");
}
if (codeInSession.isExpire()) {
sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
throw new ValidateCodeException("验证码已过期!");
}
if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), smsCodeInRequest)) {
throw new ValidateCodeException("验证码不正确!");
}
sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
}
} | java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationConfig.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsAuthenticationConfig.java | package cc.mrbird.validate.smscode;
import cc.mrbird.security.browser.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
@Component
public class SmsAuthenticationConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private UserDetailService userDetailService;
@Override
public void configure(HttpSecurity http) throws Exception {
SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
smsAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
smsAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
smsAuthenticationProvider.setUserDetailService(userDetailService);
http.authenticationProvider(smsAuthenticationProvider)
.addFilterAfter(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsCode.java | 59.Spring-Security-SessionManager/src/main/java/cc/mrbird/validate/smscode/SmsCode.java | package cc.mrbird.validate.smscode;
import java.time.LocalDateTime;
public class SmsCode {
private String code;
private LocalDateTime expireTime;
public SmsCode(String code, int expireIn) {
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
public SmsCode(String code, LocalDateTime expireTime) {
this.code = code;
this.expireTime = expireTime;
}
boolean isExpire() {
return LocalDateTime.now().isAfter(expireTime);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/Application.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/Application.java | package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/controller/TestController.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/controller/TestController.java | package com.springboot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.annotation.Log;
@RestController
public class TestController {
@Log("执行方法一")
@GetMapping("/one")
public void methodOne(String name) {
}
@Log("执行方法二")
@GetMapping("/two")
public void methodTwo() throws InterruptedException {
Thread.sleep(2000);
}
@Log("执行方法三")
@GetMapping("/three")
public void methodThree(String name, String age) {
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/dao/SysLogDao.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/dao/SysLogDao.java | package com.springboot.dao;
import com.springboot.domain.SysLog;
public interface SysLogDao {
void saveSysLog(SysLog syslog);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/dao/impl/SysLogDaoImp.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/dao/impl/SysLogDaoImp.java | package com.springboot.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import com.springboot.dao.SysLogDao;
import com.springboot.domain.SysLog;
@Repository
public class SysLogDaoImp implements SysLogDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void saveSysLog(SysLog syslog) {
StringBuffer sql = new StringBuffer("insert into sys_log ");
sql.append("(id,username,operation,time,method,params,ip,create_time) ");
sql.append("values(seq_sys_log.nextval,:username,:operation,:time,:method,");
sql.append(":params,:ip,:createTime)");
NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource());
npjt.update(sql.toString(), new BeanPropertySqlParameterSource(syslog));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/util/HttpContextUtils.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/util/HttpContextUtils.java | package com.springboot.util;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/util/IPUtils.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/util/IPUtils.java | package com.springboot.util;
import javax.servlet.http.HttpServletRequest;
public class IPUtils {
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/domain/SysLog.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/domain/SysLog.java | package com.springboot.domain;
import java.io.Serializable;
import java.util.Date;
public class SysLog implements Serializable{
private static final long serialVersionUID = -6309732882044872298L;
private Integer id;
private String username;
private String operation;
private Integer time;
private String method;
private String params;
private String ip;
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Integer getTime() {
return time;
}
public void setTime(Integer time) {
this.time = time;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/aspect/LogAspect.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/aspect/LogAspect.java | package com.springboot.aspect;
import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import com.springboot.annotation.Log;
import com.springboot.dao.SysLogDao;
import com.springboot.domain.SysLog;
import com.springboot.util.HttpContextUtils;
import com.springboot.util.IPUtils;
@Aspect
@Component
public class LogAspect {
@Autowired
private SysLogDao sysLogDao;
@Pointcut("@annotation(com.springboot.annotation.Log)")
public void pointcut() {
}
@Around("pointcut()")
public void around(ProceedingJoinPoint point) {
long beginTime = System.currentTimeMillis();
try {
// 执行方法
point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 保存日志
saveLog(point, time);
}
private void saveLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog sysLog = new SysLog();
Log logAnnotation = method.getAnnotation(Log.class);
if (logAnnotation != null) {
// 注解上的描述
sysLog.setOperation(logAnnotation.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的方法参数值
Object[] args = joinPoint.getArgs();
// 请求的方法参数名称
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method);
if (args != null && paramNames != null) {
String params = "";
for (int i = 0; i < args.length; i++) {
params += " " + paramNames[i] + ": " + args[i];
}
sysLog.setParams(params);
}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
// 模拟一个用户名
sysLog.setUsername("mrbird");
sysLog.setTime((int) time);
Date date = new Date();
sysLog.setCreateTime(date);
// 保存系统日志
sysLogDao.saveSysLog(sysLog);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/07.Spring-Boot-AOP-Log/src/main/java/com/springboot/annotation/Log.java | 07.Spring-Boot-AOP-Log/src/main/java/com/springboot/annotation/Log.java | package com.springboot.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/Application.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/Application.java | package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/controller/StudentController.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/controller/StudentController.java | package com.springboot.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.service.StudentService;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("querystudentsfromoracle")
public List<Map<String, Object>> queryStudentsFromOracle(){
return this.studentService.getAllStudentsFromOralce();
}
@RequestMapping("querystudentsfrommysql")
public List<Map<String, Object>> queryStudentsFromMysql(){
return this.studentService.getAllStudentsFromMysql();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/service/StudentService.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/service/StudentService.java | package com.springboot.service;
import java.util.List;
import java.util.Map;
public interface StudentService {
List<Map<String, Object>> getAllStudentsFromOralce();
List<Map<String, Object>> getAllStudentsFromMysql();
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/service/impl/StudentServiceImp.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/service/impl/StudentServiceImp.java | package com.springboot.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.mysqldao.MysqlStudentMapper;
import com.springboot.oracledao.OracleStudentMapper;
import com.springboot.service.StudentService;
@Service("studentService")
public class StudentServiceImp implements StudentService{
@Autowired
private OracleStudentMapper oracleStudentMapper;
@Autowired
private MysqlStudentMapper mysqlStudentMapper;
@Override
public List<Map<String, Object>> getAllStudentsFromOralce() {
return this.oracleStudentMapper.getAllStudents();
}
@Override
public List<Map<String, Object>> getAllStudentsFromMysql() {
return this.mysqlStudentMapper.getAllStudents();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/datasource/OracleDatasourceConfig.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/datasource/OracleDatasourceConfig.java | package com.springboot.datasource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
@Configuration
@MapperScan(basePackages = OracleDatasourceConfig.PACKAGE,
sqlSessionFactoryRef = "oracleSqlSessionFactory")
public class OracleDatasourceConfig {
// oracledao扫描路径
static final String PACKAGE = "com.springboot.oracledao";
// mybatis mapper扫描路径
static final String MAPPER_LOCATION = "classpath:mapper/oracle/*.xml";
@Bean(name = "oracledatasource")
@ConfigurationProperties("spring.datasource.druid.oracle")
public DataSource oracleDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "oracleTransactionManager")
public DataSourceTransactionManager oracleTransactionManager() {
return new DataSourceTransactionManager(oracleDataSource());
}
@Bean(name = "oracleSqlSessionFactory")
public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracledatasource") DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
//如果不使用xml的方式配置mapper,则可以省去下面这行mapper location的配置。
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(OracleDatasourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/datasource/MysqlDatasourceConfig.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/datasource/MysqlDatasourceConfig.java | package com.springboot.datasource;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
@Configuration
@MapperScan(basePackages = MysqlDatasourceConfig.PACKAGE, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDatasourceConfig {
// mysqldao扫描路径
static final String PACKAGE = "com.springboot.mysqldao";
// mybatis mapper扫描路径
static final String MAPPER_LOCATION = "classpath:mapper/mysql/*.xml";
@Primary
@Bean(name = "mysqldatasource")
@ConfigurationProperties("spring.datasource.druid.mysql")
public DataSource mysqlDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "mysqlTransactionManager")
@Primary
public DataSourceTransactionManager mysqlTransactionManager() {
return new DataSourceTransactionManager(mysqlDataSource());
}
@Bean(name = "mysqlSqlSessionFactory")
@Primary
public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqldatasource") DataSource dataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
//如果不使用xml的方式配置mapper,则可以省去下面这行mapper location的配置。
sessionFactory.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources(MysqlDatasourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/mysqldao/MysqlStudentMapper.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/mysqldao/MysqlStudentMapper.java | package com.springboot.mysqldao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MysqlStudentMapper {
List<Map<String, Object>> getAllStudents();
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/oracledao/OracleStudentMapper.java | 05.Spring-Boot-MyBatis-MultiDataSource/src/main/java/com/springboot/oracledao/OracleStudentMapper.java | package com.springboot.oracledao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface OracleStudentMapper {
List<Map<String, Object>> getAllStudents();
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/SpringBatchExceptionApplication.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/SpringBatchExceptionApplication.java | package cc.mrbird.batch;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchExceptionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBatchExceptionApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/exception/MyJobExecutionException.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/exception/MyJobExecutionException.java | package cc.mrbird.batch.exception;
/**
* @author MrBird
*/
public class MyJobExecutionException extends Exception{
private static final long serialVersionUID = 7168487913507656106L;
public MyJobExecutionException(String message) {
super(message);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/listener/MySkipListener.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/listener/MySkipListener.java | package cc.mrbird.batch.listener;
import org.springframework.batch.core.SkipListener;
import org.springframework.stereotype.Component;
/**
* @author MrBird
*/
@Component
public class MySkipListener implements SkipListener<String, String> {
@Override
public void onSkipInRead(Throwable t) {
System.out.println("在读取数据的时候遇到异常并跳过,异常:" + t.getMessage());
}
@Override
public void onSkipInWrite(String item, Throwable t) {
System.out.println("在输出数据的时候遇到异常并跳过,待输出数据:" + item + ",异常:" + t.getMessage());
}
@Override
public void onSkipInProcess(String item, Throwable t) {
System.out.println("在处理数据的时候遇到异常并跳过,待输出数据:" + item + ",异常:" + t.getMessage());
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/DefaultExceptionJobDemo.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/DefaultExceptionJobDemo.java | package cc.mrbird.batch.job;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author MrBird
*/
@Component
public class DefaultExceptionJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job defaultExceptionJob() {
return jobBuilderFactory.get("defaultExceptionJob")
.start(
stepBuilderFactory.get("step")
.tasklet((stepContribution, chunkContext) -> {
// 获取执行上下文
ExecutionContext executionContext = chunkContext.getStepContext().getStepExecution().getExecutionContext();
if (executionContext.containsKey("success")) {
System.out.println("任务执行成功");
return RepeatStatus.FINISHED;
} else {
String errorMessage = "处理任务过程发生异常";
System.out.println(errorMessage);
executionContext.put("success", true);
throw new RuntimeException(errorMessage);
}
}).build()
).build();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/RestartJobDemo.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/RestartJobDemo.java | package cc.mrbird.batch.job;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import java.util.ArrayList;
import java.util.stream.IntStream;
/**
* @author MrBird
*/
@Component
public class RestartJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job restartJob() {
return jobBuilderFactory.get("restartJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<String, String>chunk(2)
.reader(listItemReader())
.writer(list -> list.forEach(System.out::println))
// .allowStartIfComplete(true)
.startLimit(1)
.build();
}
private ListItemReader<String> listItemReader() {
ArrayList<String> datas = new ArrayList<>();
IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i)));
return new ListItemReader<>(datas);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/TransactionJobDemo.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/TransactionJobDemo.java | package cc.mrbird.batch.job;
import cc.mrbird.batch.exception.MyJobExecutionException;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import java.util.ArrayList;
import java.util.stream.IntStream;
/**
* @author MrBird
*/
@Component
public class TransactionJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job transactionJob() {
return jobBuilderFactory.get("transactionJob")
.start(step())
.build();
}
private Step step() {
DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
attribute.setPropagationBehavior(Propagation.REQUIRED.value());
attribute.setIsolationLevel(Isolation.DEFAULT.value());
attribute.setTimeout(30);
return stepBuilderFactory.get("step")
.<String, String>chunk(2)
.reader(listItemReader())
.writer(list -> list.forEach(System.out::println))
.readerIsTransactionalQueue()
.transactionAttribute(attribute)
.build();
}
private ListItemReader<String> listItemReader() {
ArrayList<String> datas = new ArrayList<>();
IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i)));
return new ListItemReader<>(datas);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/SkipExceptionJobDemo.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/SkipExceptionJobDemo.java | package cc.mrbird.batch.job;
import cc.mrbird.batch.exception.MyJobExecutionException;
import cc.mrbird.batch.listener.MySkipListener;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.stream.IntStream;
/**
* @author MrBird
*/
@Component
public class SkipExceptionJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private MySkipListener mySkipListener;
@Bean
public Job skipExceptionJob() {
return jobBuilderFactory.get("skipExceptionJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<String, String>chunk(2)
.reader(listItemReader())
.processor(myProcessor())
.writer(list -> list.forEach(System.out::println))
.faultTolerant() // 配置错误容忍
.skip(MyJobExecutionException.class) // 配置跳过的异常类型
.skipLimit(1) // 最多跳过1次,1次过后还是异常的话,则任务会结束,
// 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常跳过
.listener(mySkipListener)
.build();
}
private ListItemReader<String> listItemReader() {
ArrayList<String> datas = new ArrayList<>();
IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i)));
return new ListItemReader<>(datas);
}
private ItemProcessor<String, String> myProcessor() {
return item -> {
System.out.println("当前处理的数据:" + item);
if ("2".equals(item)) {
throw new MyJobExecutionException("任务处理出错");
} else {
return item;
}
};
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/RetryExceptionJobDemo.java | 72.spring-batch-exception/src/main/java/cc/mrbird/batch/job/RetryExceptionJobDemo.java | package cc.mrbird.batch.job;
import cc.mrbird.batch.exception.MyJobExecutionException;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.stream.IntStream;
/**
* @author MrBird
*/
@Component
public class RetryExceptionJobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job retryExceptionJob() {
return jobBuilderFactory.get("retryExceptionJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<String, String>chunk(2)
.reader(listItemReader())
.processor(myProcessor())
.writer(list -> list.forEach(System.out::println))
.faultTolerant() // 配置错误容忍
.retry(MyJobExecutionException.class) // 配置重试的异常类型
.retryLimit(3) // 重试3次,三次过后还是异常的话,则任务会结束,
// 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常重试
.build();
}
private ListItemReader<String> listItemReader() {
ArrayList<String> datas = new ArrayList<>();
IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i)));
return new ListItemReader<>(datas);
}
private ItemProcessor<String, String> myProcessor() {
return new ItemProcessor<String, String>() {
private int count;
@Override
public String process(String item) throws Exception {
System.out.println("当前处理的数据:" + item);
if (count >= 2) {
return item;
} else {
count++;
throw new MyJobExecutionException("任务处理出错");
}
}
};
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/validation/ValidationIntegrationTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/validation/ValidationIntegrationTest.java | package com.baeldung.apache.validation;
import java.io.File;
import java.util.Set;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.apache.bval.jsr.ApacheValidationProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.apache.bval.model.User;
import static org.junit.Assert.*;
public class ValidationIntegrationTest {
private static ValidatorFactory validatorFactory;
private static Validator validator;
@BeforeClass
public static void setup() {
validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
.configure()
.buildValidatorFactory();
validator = validatorFactory.getValidator();
}
@Test
public void givenUser_whenValidate_thenValidationViolations() {
User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
Set<ConstraintViolation<User>> violations = validator.validate(user);
assertTrue("no violations", violations.size() > 0);
}
@Test
public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
User user = new User("ana@yahoo.com", "pass", "Ana", 12);
Set<ConstraintViolation<User>> propertyViolations = validator.validateProperty(user, "age");
assertEquals("size is not 1", 1, propertyViolations.size());
}
@Test
public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
User user = new User("ana@yahoo.com", "pass", "Ana", 18);
Set<ConstraintViolation<User>> valueViolations = validator.validateValue(User.class, "age", 20);
assertEquals("size is not 0", 0, valueViolations.size());
}
@Test
public void whenValidateNonJSR_thenCorrect() {
User user = new User("ana@yahoo.com", "pass", "Ana", 20);
user.setCardNumber("1234");
user.setIban("1234");
user.setWebsite("10.0.2.50");
user.setMainDirectory(new File("."));
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "iban");
assertEquals("size is not 1", 1, violations.size());
violations = validator.validateProperty(user, "website");
assertEquals("size is not 0", 0, violations.size());
violations = validator.validateProperty(user, "mainDirectory");
assertEquals("size is not 0", 0, violations.size());
}
@Test
public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
User user = new User("ana@yahoo.com", "password", "Ana", 20);
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
assertEquals("message incorrect", "Invalid password", violations.iterator()
.next()
.getMessage());
}
@Test
public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
User user = new User("ana@yahoo.com", "password#", "Ana", 20);
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
assertEquals("size is not 0", 0, violations.size());
}
@AfterClass
public static void close() {
if (validatorFactory != null) {
validatorFactory.close();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/avrotojson/AvroFileToJsonFileTests.java | apache-libraries-2/src/test/java/com/baeldung/apache/avrotojson/AvroFileToJsonFileTests.java | package com.baeldung.apache.avrotojson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import org.apache.avro.Schema;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class AvroFileToJsonFileTests {
private AvroFileToJsonFile avroFileToJsonFile;
private File dataLocation;
private File jsonDataLocation;
private Point p;
private String expectedOutput;
@BeforeEach
public void setup() {
avroFileToJsonFile = new AvroFileToJsonFile();
// Load files from the resources folder
ClassLoader classLoader = getClass().getClassLoader();
dataLocation = new File(classLoader.getResource("").getFile(), "data.avro");
jsonDataLocation = new File(classLoader.getResource("").getFile(), "data.json");
p = new Point(2, 4);
expectedOutput = "{\"x\":2,\"y\":4}";
}
@Test
public void whenConvertedToJson_ThenEquals() {
String response = avroFileToJsonFile.convertObjectToJson(p, avroFileToJsonFile.inferSchema(p));
assertEquals(expectedOutput, response);
}
@Test
public void whenAvroContentWrittenToFile_ThenExist() {
Schema schema = avroFileToJsonFile.inferSchema(p);
avroFileToJsonFile.writeAvroToFile(schema, List.of(p), dataLocation);
assertTrue(dataLocation.exists());
}
@Test
public void whenAvroFileWrittenToJsonFile_ThenJsonContentEquals() throws IOException {
// read avro to json
avroFileToJsonFile.readAvroFromFileToJsonFile(dataLocation, jsonDataLocation);
// read json file content
String text = Files.readString(jsonDataLocation.toPath());
assertEquals(expectedOutput, text);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/camel/DynamicRouterRouteUnitTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/camel/DynamicRouterRouteUnitTest.java | package com.baeldung.apache.camel;
import com.baeldung.apache.camel.DynamicRouterRoute;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
public class DynamicRouterRouteUnitTest extends CamelTestSupport {
@Override
protected RoutesBuilder createRouteBuilder() {
return new DynamicRouterRoute();
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndMockAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:dynamicRouter");
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("mock"));
MockEndpoint.assertIsSatisfied(context);
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndDirectAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:directDynamicRouter", MockEndpoint.class);
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("direct"));
MockEndpoint.assertIsSatisfied(context);
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndSedaAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = context.getEndpoint("mock:sedaDynamicRouter", MockEndpoint.class);
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("seda"));
MockEndpoint.assertIsSatisfied(context);
}
@Test
void givenDynamicRouter_whenMockEndpointExpectedMessageCountOneAndBookAsMessageBody_thenMessageSentToDynamicRouter() throws InterruptedException {
MockEndpoint mockDynamicEndpoint = getMockEndpoint("mock:fileDynamicRouter");
mockDynamicEndpoint.expectedMessageCount(1);
template.send("direct:dynamicRouter", exchange -> exchange.getIn()
.setBody("file"));
MockEndpoint.assertIsSatisfied(context);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/camel/postrequest/PostRequestRouteUnitTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/camel/postrequest/PostRequestRouteUnitTest.java | package com.baeldung.apache.camel.postrequest;
import com.baeldung.apache.camel.postrequest.Post;
import com.baeldung.apache.camel.postrequest.PostRequestRoute;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
class PostRequestRouteUnitTest extends CamelTestSupport {
@EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
@Produce("direct:start")
protected ProducerTemplate template;
@Test
public void givenCamelPostRequestRoute_whenMakingAPostRequestToDummyServer_thenAscertainTheMockEndpointReceiveOneMessage() throws Exception {
resultEndpoint.expectedMessageCount(1);
resultEndpoint.message(0)
.header(Exchange.HTTP_RESPONSE_CODE)
.isEqualTo(201);
resultEndpoint.message(0)
.body()
.isNotNull();
template.sendBody(new Post(1, "Java 21", "Virtual Thread"));
resultEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new PostRequestRoute();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/avro/AvroDefaultValuesUnitTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/avro/AvroDefaultValuesUnitTest.java | package com.baeldung.apache.avro;
import com.baeldung.apache.avro.generated.Car;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
public class AvroDefaultValuesUnitTest {
@Test
public void givenCarJsonSchema_whenCarIsSerialized_thenCarIsSuccessfullyDeserialized() throws IOException {
Car car = Car.newBuilder()
.build();
SerializationDeserializationLogic.serializeCar(car);
Car deserializedCar = SerializationDeserializationLogic.deserializeCar();
assertEquals("Dacia", deserializedCar.getBrand());
assertEquals(4, deserializedCar.getNumberOfDoors());
assertNull(deserializedCar.getColor());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/curator/BaseManualTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/curator/BaseManualTest.java | package com.baeldung.apache.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.junit.Before;
public abstract class BaseManualTest {
@Before
public void setup() {
org.apache.log4j.BasicConfigurator.configure();
}
protected CuratorFramework newClient() {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries);
return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java | package com.baeldung.apache.curator.modeled;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import com.baeldung.apache.curator.BaseManualTest;
import com.baeldung.apache.curator.HostConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModeledFramework;
import org.apache.curator.x.async.modeled.ZPath;
import org.junit.Test;
public class ModelTypedExamplesManualTest extends BaseManualTest {
@Test
public void givenPath_whenStoreAModel_thenNodesAreCreated()
throws InterruptedException {
ModelSpec<HostConfig> mySpec = ModelSpec
.builder(ZPath.parseWithIds("/config/dev"),
JacksonModelSerializer.build(HostConfig.class))
.build();
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
ModeledFramework<HostConfig> modeledClient = ModeledFramework
.wrap(async, mySpec);
modeledClient.set(new HostConfig("host-name", 8080));
modeledClient.read()
.whenComplete((value, e) -> {
if (e != null) {
fail("Cannot read host config", e);
} else {
assertThat(value).isNotNull();
assertThat(value.getHostname()).isEqualTo("host-name");
assertThat(value.getPort()).isEqualTo(8080);
}
});
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java | package com.baeldung.apache.curator.configuration;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import com.baeldung.apache.curator.BaseManualTest;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.junit.Test;
public class ConfigurationManagementManualTest extends BaseManualTest {
private static final String KEY_FORMAT = "/%s";
@Test
public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
String key = getKey();
String expected = "my_value";
// Create key nodes structure
client.create()
.forPath(key);
// Set data value for our key
async.setData()
.forPath(key, expected.getBytes());
// Get data value
AtomicBoolean isEquals = new AtomicBoolean();
async.getData()
.forPath(key)
.thenAccept(
data -> isEquals.set(new String(data).equals(expected)));
await().until(() -> assertThat(isEquals.get()).isTrue());
}
}
@Test
public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
String key = getKey();
String expected = "my_value";
// Create key structure
async.create()
.forPath(key);
List<String> changes = new ArrayList<>();
// Watch data value
async.watched()
.getData()
.forPath(key)
.event()
.thenAccept(watchedEvent -> {
try {
changes.add(new String(client.getData()
.forPath(watchedEvent.getPath())));
} catch (Exception e) {
// fail ...
}
});
// Set data value for our key
async.setData()
.forPath(key, expected.getBytes());
await().until(() -> assertThat(changes.size() > 0).isTrue());
}
}
private String getKey() {
return String.format(KEY_FORMAT, UUID.randomUUID()
.toString());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java | package com.baeldung.apache.curator.recipes;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.apache.curator.BaseManualTest;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.framework.recipes.shared.SharedCount;
import org.apache.curator.framework.state.ConnectionState;
import org.junit.Test;
public class RecipesManualTest extends BaseManualTest {
@Test
public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
try (CuratorFramework client = newClient()) {
client.start();
LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
}
@Override
public void takeLeadership(CuratorFramework client) throws Exception {
// I'm the leader of the job A !
}
});
leaderSelector.start();
// Wait until the job A is done among all the members
leaderSelector.close();
}
}
@Test
public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");
sharedLock.acquire();
// Do process A
sharedLock.release();
}
}
@Test
public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) {
counter.start();
counter.setCount(0);
counter.setCount(counter.getCount() + 1);
assertThat(counter.getCount()).isEqualTo(1);
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java | package com.baeldung.apache.curator.connection;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.junit.Test;
public class ConnectionManagementManualTest {
@Test
public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened()
throws Exception {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
assertThat(Collections.singletonList(client.checkExists()
.forPath("/"))).isNotNull();
}
}
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
throws InterruptedException {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
AtomicBoolean exists = new AtomicBoolean(false);
async.checkExists()
.forPath("/")
.thenAcceptAsync(s -> exists.set(s != null));
await().until(() -> assertThat(exists.get()).isTrue());
}
}
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
throws InterruptedException {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
AtomicBoolean exists = new AtomicBoolean(false);
async.checkExists()
.forPath("/")
.thenAccept(s -> exists.set(s != null));
await().until(() -> assertThat(exists.get()).isTrue());
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/beam/WordCountIntegrationTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/beam/WordCountIntegrationTest.java | package com.baeldung.apache.beam;
import com.baeldung.apache.beam.WordCount;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class WordCountIntegrationTest {
@Test
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
boolean jobDone = WordCount.wordCount("src/test/resources/wordcount.txt", "target/output");
assertTrue(jobDone);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/ConsumerLiveTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/ConsumerLiveTest.java | package com.baeldung.apache.pulsar;
import java.io.IOException;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.SubscriptionType;
public class ConsumerLiveTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
public static void main(String[] args) throws IOException {
// Create a Pulsar client instance. A single instance can be shared across many
// producers and consumer within the same application
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
//Configure consumer specific settings.
Consumer<byte[]> consumer = client.newConsumer()
.topic(TOPIC_NAME)
// Allow multiple consumers to attach to the same subscription
// and get messages dispatched as a queue
.subscriptionType(SubscriptionType.Shared)
.subscriptionName(SUBSCRIPTION_NAME)
.subscribe();
// Once the consumer is created, it can be used for the entire application lifecycle
System.out.println("Created consumer for the topic "+ TOPIC_NAME);
do {
// Wait until a message is available
Message<byte[]> msg = consumer.receive();
// Extract the message as a printable string and then log
String content = new String(msg.getData());
System.out.println("Received message '"+content+"' with ID "+msg.getMessageId());
// Acknowledge processing of the message so that it can be deleted
consumer.acknowledge(msg);
} while (true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/ProducerLiveTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/ProducerLiveTest.java | package com.baeldung.apache.pulsar;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import java.io.IOException;
import java.util.stream.IntStream;
public class ProducerLiveTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
public static void main(String[] args) throws IOException {
// Create a Pulsar client instance. A single instance can be shared across many
// producers and consumer within the same application
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
// Configure producer specific settings
Producer<byte[]> producer = client.newProducer()
// Set the topic
.topic(TOPIC_NAME)
// Enable compression
.compressionType(CompressionType.LZ4)
.create();
// Once the producer is created, it can be used for the entire application life-cycle
System.out.println("Created producer for the topic "+TOPIC_NAME);
// Send 5 test messages
IntStream.range(1, 5).forEach(i -> {
String content = String.format("hi-pulsar-%d", i);
// Build a message object
Message<byte[]> msg = MessageBuilder.create()
.setContent(content.getBytes())
.build();
// Send each message and log message content and ID when successfully received
try {
MessageId msgId = producer.send(msg);
System.out.println("Published message '"+content+"' with the ID "+msgId);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
});
client.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/subscriptions/FailoverSubscriptionLiveTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/subscriptions/FailoverSubscriptionLiveTest.java | package com.baeldung.apache.pulsar.subscriptions;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import java.util.stream.IntStream;
public class FailoverSubscriptionLiveTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "failover-subscription-test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Failover;
private static final int NUM_MSGS = 10;
public static void main(String[] args) throws PulsarClientException {
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
Producer<byte[]> producer = client.newProducer()
.topic(TOPIC_NAME)
.create();
ConsumerBuilder<byte[]> consumerBuilder = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
Consumer<byte[]> mainConsumer = consumerBuilder
.consumerName("consumer-a")
.messageListener((consumer, msg) -> {
System.out.println("Message received by main consumer");
try {
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
})
.subscribe();
Consumer<byte[]> failoverConsumer = consumerBuilder
.consumerName("consumer-b")
.messageListener((consumer, msg) -> {
System.out.println("Message received by failover consumer");
try {
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
})
.subscribe();
IntStream.range(0, NUM_MSGS).forEach(i -> {
Message<byte[]> msg = MessageBuilder.create()
.setContent(String.format("message-%d", i).getBytes())
.build();
try {
producer.send(msg);
Thread.sleep(100);
if (i > 5) mainConsumer.close();
} catch (InterruptedException | PulsarClientException e) {
System.out.println(e.getMessage());
}
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/subscriptions/ExclusiveSubscriptionLiveTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/pulsar/subscriptions/ExclusiveSubscriptionLiveTest.java | package com.baeldung.apache.pulsar.subscriptions;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import java.util.stream.IntStream;
public class ExclusiveSubscriptionLiveTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Exclusive;
public static void main(String[] args) throws PulsarClientException {
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
Producer<byte[]> producer = client.newProducer()
.topic(TOPIC_NAME)
.create();
ConsumerBuilder<byte[]> consumer1 = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
ConsumerBuilder<byte[]> consumer2 = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
IntStream.range(0, 999).forEach(i -> {
Message<byte[]> msg = MessageBuilder.create()
.setContent(String.format("message-%d", i).getBytes())
.build();
try {
producer.send(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
});
// Consumer 1 can subscribe to the topic
consumer1.subscribe();
// Consumer 2 cannot due to the exclusive subscription held by consumer 1
consumer2.subscribeAsync()
.handle((consumer, exception) -> {
System.out.println(exception.getMessage());
return null;
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/geode/GeodeSamplesLiveTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/geode/GeodeSamplesLiveTest.java | package com.baeldung.apache.geode;
import com.baeldung.apache.geode.functions.UpperCaseNames;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.cache.query.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class GeodeSamplesLiveTest {
ClientCache cache = null;
Region<String, String> region = null;
Region<Integer, Customer> queryRegion = null;
Region<CustomerKey, Customer> customerRegion = null;
@Before
public void connect() {
this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334)
.create();
this.region = this.cache.<String, String> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("baeldung");
this.customerRegion = this.cache.<CustomerKey, Customer> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("baeldung-customers");
}
@After
public void cleanup() {
this.cache.close();
}
@Test
public void whenSendMessageToRegion_thenMessageSavedSuccessfully() {
this.region.put("1", "Hello");
this.region.put("2", "Baeldung");
assertEquals("Hello", region.get("1"));
assertEquals("Baeldung", region.get("2"));
}
@Test
public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() {
Supplier<Stream<String>> keys = () -> Stream.of("A", "B", "C", "D", "E");
Map<String, String> values = keys.get()
.collect(Collectors.toMap(Function.identity(), String::toLowerCase));
this.region.putAll(values);
keys.get()
.forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k)));
}
@Test
public void whenPutCustomKey_thenValuesSavedSuccessfully() {
CustomerKey key = new CustomerKey(123);
Customer customer = new Customer(key, "William", "Russell", 35);
Map<CustomerKey, Customer> customerInfo = new HashMap<>();
customerInfo.put(key, customer);
this.customerRegion.putAll(customerInfo);
Customer storedCustomer = this.customerRegion.get(key);
assertEquals("William", storedCustomer.getFirstName());
assertEquals("Russell", storedCustomer.getLastName());
}
@Test
public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
Map<CustomerKey, Customer> data = new HashMap<>();
data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36));
data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43));
this.customerRegion.putAll(data);
QueryService queryService = this.cache.getQueryService();
String query = "select * from /baeldung-customers c where c.firstName = 'Allan'";
SelectResults<Customer> queryResults = (SelectResults<Customer>) queryService.newQuery(query)
.execute();
assertEquals(1, queryResults.size());
}
@Test
public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() {
Execution execution = FunctionService.onRegion(this.customerRegion);
execution.execute(UpperCaseNames.class.getName());
Customer customer = this.customerRegion.get(new CustomerKey(1));
assertEquals("GHEORGE", customer.getFirstName());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/test/java/com/baeldung/apache/meecrowave/ArticleEndpointsIntegrationTest.java | apache-libraries-2/src/test/java/com/baeldung/apache/meecrowave/ArticleEndpointsIntegrationTest.java | package com.baeldung.apache.meecrowave;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.apache.meecrowave.Meecrowave;
import org.apache.meecrowave.junit.MonoMeecrowave;
import org.apache.meecrowave.testing.ConfigurationInject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@RunWith(MonoMeecrowave.Runner.class)
public class ArticleEndpointsIntegrationTest {
@ConfigurationInject
private Meecrowave.Builder config;
private static OkHttpClient client;
@BeforeClass
public static void setup() {
client = new OkHttpClient();
}
@Test
public void whenRetunedArticle_thenCorrect() throws IOException {
final String base = "http://localhost:"+config.getHttpPort();
Request request = new Request.Builder()
.url(base+"/article")
.build();
Response response = client.newCall(request).execute();
assertEquals(200, response.code());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/avrotojson/Point.java | apache-libraries-2/src/main/java/com/baeldung/apache/avrotojson/Point.java | package com.baeldung.apache.avrotojson;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// Getters and setters
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/avrotojson/AvroFileToJsonFile.java | apache-libraries-2/src/main/java/com/baeldung/apache/avrotojson/AvroFileToJsonFile.java | package com.baeldung.apache.avrotojson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.io.JsonEncoder;
import org.apache.avro.reflect.ReflectData;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
public class AvroFileToJsonFile {
// Method to infer schema for Point class
public Schema inferSchema(Point p) {
return ReflectData.get().getSchema(p.getClass());
}
// Method to convert object to JSON using JsonEncoder
public String convertObjectToJson(Point p, Schema schema) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
// Use GenericRecord since we're using a manually built schema
GenericRecord genericRecord = new GenericData.Record(schema);
genericRecord.put("x", p.getX());
genericRecord.put("y", p.getY());
// Use JSON encoder to serialize GenericRecord to JSON
Encoder encoder = EncoderFactory.get().jsonEncoder(schema, outputStream);
datumWriter.write(genericRecord, encoder);
encoder.flush();
outputStream.close();
return outputStream.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Method to write Avro file using GenericRecord
public void writeAvroToFile(Schema schema, List<Point> records, File writeLocation) {
try {
// Delete file if it exists
if (writeLocation.exists()) {
if (!writeLocation.delete()) {
System.err.println("Failed to delete existing file.");
return;
}
}
// Create the Avro file writer
GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
dataFileWriter.create(schema, writeLocation);
// Write each record as a GenericRecord
for (Point record : records) {
GenericRecord genericRecord = new GenericData.Record(schema);
genericRecord.put("x", record.getX());
genericRecord.put("y", record.getY());
dataFileWriter.append(genericRecord);
}
dataFileWriter.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error writing Avro file.");
}
}
// Method to read Avro file and convert to JSON
public void readAvroFromFileToJsonFile(File readLocation, File jsonFilePath) {
DatumReader<GenericRecord> reader = new GenericDatumReader<>();
try {
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<>(readLocation, reader);
DatumWriter<GenericRecord> jsonWriter = new GenericDatumWriter<>(dataFileReader.getSchema());
Schema schema = dataFileReader.getSchema();
// Read each Avro record and write as JSON
OutputStream fos = new FileOutputStream(jsonFilePath);
JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, fos);
while (dataFileReader.hasNext()) {
GenericRecord record = dataFileReader.next();
System.out.println(record.toString());
jsonWriter.write(record, jsonEncoder);
jsonEncoder.flush();
}
dataFileReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/bval/validation/Password.java | apache-libraries-2/src/main/java/com/baeldung/apache/bval/validation/Password.java | package com.baeldung.apache.bval.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import static java.lang.annotation.ElementType.*;
@Constraint(validatedBy = { PasswordValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Password {
String message() default "Invalid password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int length() default 6;
int nonAlpha() default 1;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/bval/validation/PasswordValidator.java | apache-libraries-2/src/main/java/com/baeldung/apache/bval/validation/PasswordValidator.java | package com.baeldung.apache.bval.validation;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class PasswordValidator implements ConstraintValidator<Password, String> {
private int length;
private int nonAlpha;
@Override
public void initialize(Password password) {
this.length = password.length();
this.nonAlpha = password.nonAlpha();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value.length() < length) {
return false;
}
int nonAlphaNr = 0;
for (int i = 0; i < value.length(); i++) {
if (!Character.isLetterOrDigit(value.charAt(i))) {
nonAlphaNr++;
}
}
if (nonAlphaNr < nonAlpha) {
return false;
}
return true;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/bval/model/User.java | apache-libraries-2/src/main/java/com/baeldung/apache/bval/model/User.java | package com.baeldung.apache.bval.model;
import java.io.File;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.apache.bval.constraints.Email;
import org.apache.bval.constraints.NotEmpty;
import org.apache.bval.extras.constraints.checkdigit.IBAN;
import org.apache.bval.extras.constraints.creditcard.Visa;
import org.apache.bval.extras.constraints.file.Directory;
import org.apache.bval.extras.constraints.net.InetAddress;
import com.baeldung.apache.bval.validation.Password;
public class User {
@NotNull
@Email
private String email;
@NotEmpty
@Password
private String password;
@Size(min = 1, max = 20)
private String name;
@Min(18)
private int age;
@Visa
private String cardNumber = "";
@IBAN
private String iban = "";
@InetAddress
private String website = "";
@Directory
private File mainDirectory=new File(".");
public User() {
}
public User(String email, String password, String name, int age) {
super();
this.email = email;
this.password = password;
this.name = name;
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public File getMainDirectory() {
return mainDirectory;
}
public void setMainDirectory(File mainDirectory) {
this.mainDirectory = mainDirectory;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/DynamicRouterRoute.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/DynamicRouterRoute.java | package com.baeldung.apache.camel;
import org.apache.camel.builder.RouteBuilder;
public class DynamicRouterRoute extends RouteBuilder {
@Override
public void configure() {
from("direct:dynamicRouter").dynamicRouter(method(DynamicRouterBean.class, "route"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/DynamicRouterBean.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/DynamicRouterBean.java | package com.baeldung.apache.camel;
import org.apache.camel.ExchangeProperties;
import java.util.Map;
public class DynamicRouterBean {
public String route(String body, @ExchangeProperties Map<String, Object> properties) {
int invoked = (int) properties.getOrDefault("invoked", 0) + 1;
properties.put("invoked", invoked);
if (invoked == 1) {
switch (body.toLowerCase()) {
case "mock":
return "mock:dynamicRouter";
case "direct":
return "mock:directDynamicRouter";
case "seda":
return "mock:sedaDynamicRouter";
case "file":
return "mock:fileDynamicRouter";
default:
break;
}
}
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/FileProcessor.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/FileProcessor.java | package com.baeldung.apache.camel.logging;
import org.apache.camel.Body;
import java.util.Map;
public class FileProcessor {
public String process(@Body String fileContent) {
String processedContent = fileContent.toUpperCase();
return processedContent;
}
public Map<String, Object> transform(Map<String, Object> input) {
String name = (String) input.get("name");
int age = (int) input.get("age");
input.put("transformedName", name.toUpperCase());
input.put("transformedAge", age + 10);
return input;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/FileCopierCamelRoute.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/FileCopierCamelRoute.java | package com.baeldung.apache.camel.logging;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileCopierCamelRoute extends RouteBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(FileCopierCamelRoute.class);
public void configure() {
from("file:data/inbox?noop=true").log("We got an incoming file ${file:name} containing: ${body}")
.to("log:com.baeldung.apachecamellogging?level=INFO")
.process(process -> {
LOGGER.info("We are passing the message to a FileProcesor bean to capitalize the message body");
})
.bean(FileProcessor.class)
.to("file:data/outbox")
.to("log:com.baeldung.apachecamellogging?showBodyType=false&maxChars=20")
.log(LoggingLevel.DEBUG, "Output Process", "The Process ${id}")
.log("Successfully transfer file: ${file:name}");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/CamelLoggingMainApp.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/CamelLoggingMainApp.java | package com.baeldung.apache.camel.logging;
import org.apache.camel.main.Main;
public class CamelLoggingMainApp {
public static void main(String[] args) throws Exception {
Main main = new Main();
main.configure()
.addRoutesBuilder(new FileCopierCamelRoute());
main.run(args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/FileCopierTracerCamelRoute.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/logging/FileCopierTracerCamelRoute.java | package com.baeldung.apache.camel.logging;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileCopierTracerCamelRoute extends RouteBuilder {
Logger logger = LoggerFactory.getLogger(FileCopierTracerCamelRoute.class);
public void configure() {
getContext().setTracing(true);
from("file:data/json?noop=true").to("log:input?level=INFO")
.unmarshal()
.json(JsonLibrary.Jackson)
.bean(FileProcessor.class, "transform")
.marshal()
.json(JsonLibrary.Jackson)
.to("file:data/output");
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/postrequest/PostRequestRoute.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/postrequest/PostRequestRoute.java | package com.baeldung.apache.camel.postrequest;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary;
public class PostRequestRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:start").process(exchange -> exchange.getIn()
.setBody(new Post(1, "Java 21", "Virtual Thread")))
.marshal()
.json(JsonLibrary.Jackson)
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.to("https://jsonplaceholder.typicode.com/posts")
.process(exchange -> log.debug("The HTTP response code is: {}", exchange.getIn()
.getHeader(Exchange.HTTP_RESPONSE_CODE)))
.process(exchange -> log.debug("The response body is: {}", exchange.getIn()
.getBody(String.class)))
.to("mock:result");
from("direct:post").process(exchange -> exchange.getIn()
.setBody("{\"title\":\"Java 21\",\"body\":\"Virtual Thread\",\"userId\":\"1\"}"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.to("https://jsonplaceholder.typicode.com/posts?httpMethod=POST")
.to("mock:post");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/camel/postrequest/Post.java | apache-libraries-2/src/main/java/com/baeldung/apache/camel/postrequest/Post.java | package com.baeldung.apache.camel.postrequest;
public class Post {
private int userId;
private String title;
private String body;
public Post() {
}
public Post(int userId, String title, String body) {
this.userId = userId;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/avro/SerializationDeserializationLogic.java | apache-libraries-2/src/main/java/com/baeldung/apache/avro/SerializationDeserializationLogic.java | package com.baeldung.apache.avro;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import java.io.File;
import java.io.IOException;
import com.baeldung.apache.avro.generated.Car;
public class SerializationDeserializationLogic {
static void serializeCar(Car car) throws IOException {
DatumWriter<Car> userDatumWriter = new SpecificDatumWriter(Car.class);
try (DataFileWriter<Car> dataFileWriter = new DataFileWriter(userDatumWriter)) {
dataFileWriter.create(car.getSchema(), new File("cars.avro"));
dataFileWriter.append(car);
}
}
static Car deserializeCar() throws IOException {
DatumReader<Car> userDatumReader = new SpecificDatumReader(Car.class);
try (DataFileReader<Car> dataFileReader = new DataFileReader(new File("cars.avro"), userDatumReader)) {
return dataFileReader.next();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/avro/generated/Car.java | apache-libraries-2/src/main/java/com/baeldung/apache/avro/generated/Car.java | /**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package com.baeldung.apache.avro.generated;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.avro.message.BinaryMessageEncoder;
import org.apache.avro.message.BinaryMessageDecoder;
import org.apache.avro.message.SchemaStore;
@org.apache.avro.specific.AvroGenerated
public class Car extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final long serialVersionUID = 5432057678575069597L;
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"Car\",\"namespace\":\"com.baeldung.apache.avro.generated\",\"fields\":[{\"name\":\"brand\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"default\":\"Dacia\"},{\"name\":\"number_of_doors\",\"type\":\"int\",\"default\":4},{\"name\":\"color\",\"type\":[\"null\",{\"type\":\"string\",\"avro.java.string\":\"String\"}],\"default\":null}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
private static final SpecificData MODEL$ = new SpecificData();
private static final BinaryMessageEncoder<Car> ENCODER =
new BinaryMessageEncoder<>(MODEL$, SCHEMA$);
private static final BinaryMessageDecoder<Car> DECODER =
new BinaryMessageDecoder<>(MODEL$, SCHEMA$);
/**
* Return the BinaryMessageEncoder instance used by this class.
* @return the message encoder used by this class
*/
public static BinaryMessageEncoder<Car> getEncoder() {
return ENCODER;
}
/**
* Return the BinaryMessageDecoder instance used by this class.
* @return the message decoder used by this class
*/
public static BinaryMessageDecoder<Car> getDecoder() {
return DECODER;
}
/**
* Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
* @param resolver a {@link SchemaStore} used to find schemas by fingerprint
* @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore
*/
public static BinaryMessageDecoder<Car> createDecoder(SchemaStore resolver) {
return new BinaryMessageDecoder<>(MODEL$, SCHEMA$, resolver);
}
/**
* Serializes this Car to a ByteBuffer.
* @return a buffer holding the serialized data for this instance
* @throws java.io.IOException if this instance could not be serialized
*/
public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
return ENCODER.encode(this);
}
/**
* Deserializes a Car from a ByteBuffer.
* @param b a byte buffer holding serialized data for an instance of this class
* @return a Car instance decoded from the given buffer
* @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class
*/
public static Car fromByteBuffer(
java.nio.ByteBuffer b) throws java.io.IOException {
return DECODER.decode(b);
}
private java.lang.String brand;
private int number_of_doors;
private java.lang.String color;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use <code>newBuilder()</code>.
*/
public Car() {}
/**
* All-args constructor.
* @param brand The new value for brand
* @param number_of_doors The new value for number_of_doors
* @param color The new value for color
*/
public Car(java.lang.String brand, java.lang.Integer number_of_doors, java.lang.String color) {
this.brand = brand;
this.number_of_doors = number_of_doors;
this.color = color;
}
@Override
public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; }
@Override
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
@Override
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return brand;
case 1: return number_of_doors;
case 2: return color;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
// Used by DatumReader. Applications should not call.
@Override
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: brand = value$ != null ? value$.toString() : null; break;
case 1: number_of_doors = (java.lang.Integer)value$; break;
case 2: color = value$ != null ? value$.toString() : null; break;
default: throw new IndexOutOfBoundsException("Invalid index: " + field$);
}
}
/**
* Gets the value of the 'brand' field.
* @return The value of the 'brand' field.
*/
public java.lang.String getBrand() {
return brand;
}
/**
* Sets the value of the 'brand' field.
* @param value the value to set.
*/
public void setBrand(java.lang.String value) {
this.brand = value;
}
/**
* Gets the value of the 'number_of_doors' field.
* @return The value of the 'number_of_doors' field.
*/
public int getNumberOfDoors() {
return number_of_doors;
}
/**
* Sets the value of the 'number_of_doors' field.
* @param value the value to set.
*/
public void setNumberOfDoors(int value) {
this.number_of_doors = value;
}
/**
* Gets the value of the 'color' field.
* @return The value of the 'color' field.
*/
public java.lang.String getColor() {
return color;
}
/**
* Sets the value of the 'color' field.
* @param value the value to set.
*/
public void setColor(java.lang.String value) {
this.color = value;
}
/**
* Creates a new Car RecordBuilder.
* @return A new Car RecordBuilder
*/
public static com.baeldung.apache.avro.generated.Car.Builder newBuilder() {
return new com.baeldung.apache.avro.generated.Car.Builder();
}
/**
* Creates a new Car RecordBuilder by copying an existing Builder.
* @param other The existing builder to copy.
* @return A new Car RecordBuilder
*/
public static com.baeldung.apache.avro.generated.Car.Builder newBuilder(com.baeldung.apache.avro.generated.Car.Builder other) {
if (other == null) {
return new com.baeldung.apache.avro.generated.Car.Builder();
} else {
return new com.baeldung.apache.avro.generated.Car.Builder(other);
}
}
/**
* Creates a new Car RecordBuilder by copying an existing Car instance.
* @param other The existing instance to copy.
* @return A new Car RecordBuilder
*/
public static com.baeldung.apache.avro.generated.Car.Builder newBuilder(com.baeldung.apache.avro.generated.Car other) {
if (other == null) {
return new com.baeldung.apache.avro.generated.Car.Builder();
} else {
return new com.baeldung.apache.avro.generated.Car.Builder(other);
}
}
/**
* RecordBuilder for Car instances.
*/
@org.apache.avro.specific.AvroGenerated
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<Car>
implements org.apache.avro.data.RecordBuilder<Car> {
private java.lang.String brand;
private int number_of_doors;
private java.lang.String color;
/** Creates a new Builder */
private Builder() {
super(SCHEMA$, MODEL$);
}
/**
* Creates a Builder by copying an existing Builder.
* @param other The existing Builder to copy.
*/
private Builder(com.baeldung.apache.avro.generated.Car.Builder other) {
super(other);
if (isValidValue(fields()[0], other.brand)) {
this.brand = data().deepCopy(fields()[0].schema(), other.brand);
fieldSetFlags()[0] = other.fieldSetFlags()[0];
}
if (isValidValue(fields()[1], other.number_of_doors)) {
this.number_of_doors = data().deepCopy(fields()[1].schema(), other.number_of_doors);
fieldSetFlags()[1] = other.fieldSetFlags()[1];
}
if (isValidValue(fields()[2], other.color)) {
this.color = data().deepCopy(fields()[2].schema(), other.color);
fieldSetFlags()[2] = other.fieldSetFlags()[2];
}
}
/**
* Creates a Builder by copying an existing Car instance
* @param other The existing instance to copy.
*/
private Builder(com.baeldung.apache.avro.generated.Car other) {
super(SCHEMA$, MODEL$);
if (isValidValue(fields()[0], other.brand)) {
this.brand = data().deepCopy(fields()[0].schema(), other.brand);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.number_of_doors)) {
this.number_of_doors = data().deepCopy(fields()[1].schema(), other.number_of_doors);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.color)) {
this.color = data().deepCopy(fields()[2].schema(), other.color);
fieldSetFlags()[2] = true;
}
}
/**
* Gets the value of the 'brand' field.
* @return The value.
*/
public java.lang.String getBrand() {
return brand;
}
/**
* Sets the value of the 'brand' field.
* @param value The value of 'brand'.
* @return This builder.
*/
public com.baeldung.apache.avro.generated.Car.Builder setBrand(java.lang.String value) {
validate(fields()[0], value);
this.brand = value;
fieldSetFlags()[0] = true;
return this;
}
/**
* Checks whether the 'brand' field has been set.
* @return True if the 'brand' field has been set, false otherwise.
*/
public boolean hasBrand() {
return fieldSetFlags()[0];
}
/**
* Clears the value of the 'brand' field.
* @return This builder.
*/
public com.baeldung.apache.avro.generated.Car.Builder clearBrand() {
brand = null;
fieldSetFlags()[0] = false;
return this;
}
/**
* Gets the value of the 'number_of_doors' field.
* @return The value.
*/
public int getNumberOfDoors() {
return number_of_doors;
}
/**
* Sets the value of the 'number_of_doors' field.
* @param value The value of 'number_of_doors'.
* @return This builder.
*/
public com.baeldung.apache.avro.generated.Car.Builder setNumberOfDoors(int value) {
validate(fields()[1], value);
this.number_of_doors = value;
fieldSetFlags()[1] = true;
return this;
}
/**
* Checks whether the 'number_of_doors' field has been set.
* @return True if the 'number_of_doors' field has been set, false otherwise.
*/
public boolean hasNumberOfDoors() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'number_of_doors' field.
* @return This builder.
*/
public com.baeldung.apache.avro.generated.Car.Builder clearNumberOfDoors() {
fieldSetFlags()[1] = false;
return this;
}
/**
* Gets the value of the 'color' field.
* @return The value.
*/
public java.lang.String getColor() {
return color;
}
/**
* Sets the value of the 'color' field.
* @param value The value of 'color'.
* @return This builder.
*/
public com.baeldung.apache.avro.generated.Car.Builder setColor(java.lang.String value) {
validate(fields()[2], value);
this.color = value;
fieldSetFlags()[2] = true;
return this;
}
/**
* Checks whether the 'color' field has been set.
* @return True if the 'color' field has been set, false otherwise.
*/
public boolean hasColor() {
return fieldSetFlags()[2];
}
/**
* Clears the value of the 'color' field.
* @return This builder.
*/
public com.baeldung.apache.avro.generated.Car.Builder clearColor() {
color = null;
fieldSetFlags()[2] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public Car build() {
try {
Car record = new Car();
record.brand = fieldSetFlags()[0] ? this.brand : (java.lang.String) defaultValue(fields()[0]);
record.number_of_doors = fieldSetFlags()[1] ? this.number_of_doors : (java.lang.Integer) defaultValue(fields()[1]);
record.color = fieldSetFlags()[2] ? this.color : (java.lang.String) defaultValue(fields()[2]);
return record;
} catch (org.apache.avro.AvroMissingFieldException e) {
throw e;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<Car>
WRITER$ = (org.apache.avro.io.DatumWriter<Car>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<Car>
READER$ = (org.apache.avro.io.DatumReader<Car>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
@Override protected boolean hasCustomCoders() { return true; }
@Override public void customEncode(org.apache.avro.io.Encoder out)
throws java.io.IOException
{
out.writeString(this.brand);
out.writeInt(this.number_of_doors);
if (this.color == null) {
out.writeIndex(0);
out.writeNull();
} else {
out.writeIndex(1);
out.writeString(this.color);
}
}
@Override public void customDecode(org.apache.avro.io.ResolvingDecoder in)
throws java.io.IOException
{
org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff();
if (fieldOrder == null) {
this.brand = in.readString();
this.number_of_doors = in.readInt();
if (in.readIndex() != 1) {
in.readNull();
this.color = null;
} else {
this.color = in.readString();
}
} else {
for (int i = 0; i < 3; i++) {
switch (fieldOrder[i].pos()) {
case 0:
this.brand = in.readString();
break;
case 1:
this.number_of_doors = in.readInt();
break;
case 2:
if (in.readIndex() != 1) {
in.readNull();
this.color = null;
} else {
this.color = in.readString();
}
break;
default:
throw new java.io.IOException("Corrupt ResolvingDecoder.");
}
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/zookeeper/manager/ZKManagerImpl.java | apache-libraries-2/src/main/java/com/baeldung/apache/zookeeper/manager/ZKManagerImpl.java | package com.baeldung.apache.zookeeper.manager;
import com.baeldung.apache.zookeeper.connection.ZKConnection;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
public class ZKManagerImpl implements ZKManager {
private static ZooKeeper zkeeper;
private static ZKConnection zkConnection;
public ZKManagerImpl() {
initialize();
}
/** * Initialize connection */
private void initialize() {
try {
zkConnection = new ZKConnection();
zkeeper = zkConnection.connect("localhost");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void closeConnection() {
try {
zkConnection.close();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public void create(String path, byte[] data) throws KeeperException, InterruptedException {
zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public Object getZNodeData(String path, boolean watchFlag) {
try {
byte[] b = null;
b = zkeeper.getData(path, null, null);
String data = new String(b, "UTF-8");
System.out.println(data);
return data;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public void update(String path, byte[] data) throws KeeperException, InterruptedException {
int version = zkeeper.exists(path, true)
.getVersion();
zkeeper.setData(path, data, version);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/zookeeper/manager/ZKManager.java | apache-libraries-2/src/main/java/com/baeldung/apache/zookeeper/manager/ZKManager.java | package com.baeldung.apache.zookeeper.manager;
import org.apache.zookeeper.KeeperException;
public interface ZKManager {
/**
* Create a Znode and save some data
*
* @param path
* @param data
* @throws KeeperException
* @throws InterruptedException
*/
public void create(String path, byte[] data) throws KeeperException, InterruptedException;
/**
* Get ZNode Data
*
* @param path
* @param boolean watchFlag
* @throws KeeperException
* @throws InterruptedException
*/
public Object getZNodeData(String path, boolean watchFlag);
/**
* Update the ZNode Data
*
* @param path
* @param data
* @throws KeeperException
* @throws InterruptedException
*/
public void update(String path, byte[] data) throws KeeperException, InterruptedException, KeeperException;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/zookeeper/connection/ZKConnection.java | apache-libraries-2/src/main/java/com/baeldung/apache/zookeeper/connection/ZKConnection.java | package com.baeldung.apache.zookeeper.connection;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class ZKConnection {
private ZooKeeper zoo;
final CountDownLatch connectionLatch = new CountDownLatch(1);
public ZKConnection() {
}
public ZooKeeper connect(String host) throws IOException, InterruptedException {
zoo = new ZooKeeper(host, 2000, new Watcher() {
public void process(WatchedEvent we) {
if (we.getState() == KeeperState.SyncConnected) {
connectionLatch.countDown();
}
}
});
connectionLatch.await();
return zoo;
}
public void close() throws InterruptedException {
zoo.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/curator/HostConfig.java | apache-libraries-2/src/main/java/com/baeldung/apache/curator/HostConfig.java | package com.baeldung.apache.curator;
public class HostConfig {
private String hostname;
private int port;
public HostConfig() {
}
public HostConfig(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/beam/WordCount.java | apache-libraries-2/src/main/java/com/baeldung/apache/beam/WordCount.java | package com.baeldung.apache.beam;
import java.util.Arrays;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.Filter;
import org.apache.beam.sdk.transforms.FlatMapElements;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TypeDescriptors;
public class WordCount {
public static boolean wordCount(String inputFilePath, String outputFilePath) {
// We use default options
PipelineOptions options = PipelineOptionsFactory.create();
// to create the pipeline
Pipeline p = Pipeline.create(options);
// Here is our workflow graph
PCollection<KV<String, Long>> wordCount = p
.apply("(1) Read all lines", TextIO.read().from(inputFilePath))
.apply("(2) Flatmap to a list of words", FlatMapElements.into(TypeDescriptors.strings())
.via(line -> Arrays.asList(line.split("\\s"))))
.apply("(3) Lowercase all", MapElements.into(TypeDescriptors.strings())
.via(word -> word.toLowerCase()))
.apply("(4) Trim punctuations", MapElements.into(TypeDescriptors.strings())
.via(word -> trim(word)))
.apply("(5) Filter stopwords", Filter.by(word -> !isStopWord(word)))
.apply("(6) Count words", Count.perElement());
// We convert the PCollection to String so that we can write it to file
wordCount.apply(MapElements.into(TypeDescriptors.strings())
.via(count -> count.getKey() + " --> " + count.getValue()))
.apply(TextIO.write().to(outputFilePath));
// Finally we must run the pipeline, otherwise it's only a definition
p.run().waitUntilFinish();
return true;
}
public static boolean isStopWord(String word) {
String[] stopwords = {"am", "are", "is", "i", "you", "me",
"he", "she", "they", "them", "was",
"were", "from", "in", "of", "to", "be",
"him", "her", "us", "and", "or"};
for (String stopword : stopwords) {
if (stopword.compareTo(word) == 0) {
return true;
}
}
return false;
}
public static String trim(String word) {
return word.replace("(","")
.replace(")", "")
.replace(",", "")
.replace(".", "")
.replace("\"", "")
.replace("'", "")
.replace(":", "")
.replace(";", "")
.replace("-", "")
.replace("?", "")
.replace("!", "");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/geode/CustomerKey.java | apache-libraries-2/src/main/java/com/baeldung/apache/geode/CustomerKey.java | package com.baeldung.apache.geode;
import java.io.Serializable;
public class CustomerKey implements Serializable {
private static final long serialVersionUID = -3529253035303792458L;
private long id;
private String country;
public CustomerKey(long id) {
this.id = id;
this.country = "USA";
}
public CustomerKey(long id, String country) {
this.id = id;
this.country = country;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CustomerKey that = (CustomerKey) o;
if (id != that.id)
return false;
return country != null ? country.equals(that.country) : that.country == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (country != null ? country.hashCode() : 0);
return result;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/geode/Customer.java | apache-libraries-2/src/main/java/com/baeldung/apache/geode/Customer.java | package com.baeldung.apache.geode;
import java.io.Serializable;
import java.util.Objects;
public class Customer implements Serializable {
private static final long serialVersionUID = -7482516011038799900L;
private CustomerKey key;
private String firstName;
private String lastName;
private Integer age;
public Customer() {
}
public Customer(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public Customer(CustomerKey key, String firstName, String lastName, int age) {
this(firstName, lastName, age);
this.key = key;
}
// setters and getters
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Customer customer = (Customer) o;
return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/geode/functions/UpperCaseNames.java | apache-libraries-2/src/main/java/com/baeldung/apache/geode/functions/UpperCaseNames.java | package com.baeldung.apache.geode.functions;
import com.baeldung.apache.geode.Customer;
import com.baeldung.apache.geode.CustomerKey;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.RegionFunctionContext;
import java.util.Map;
public class UpperCaseNames implements Function<Boolean> {
private static final long serialVersionUID = -8946294032165677602L;
@Override
public void execute(FunctionContext<Boolean> context) {
RegionFunctionContext regionContext = (RegionFunctionContext) context;
Region<CustomerKey, Customer> region = regionContext.getDataSet();
for (Map.Entry<CustomerKey, Customer> entry : region.entrySet()) {
Customer customer = entry.getValue();
customer.setFirstName(customer.getFirstName()
.toUpperCase());
}
context.getResultSender()
.lastResult(true);
}
@Override
public String getId() {
return getClass().getName();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/Server.java | apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/Server.java | package com.baeldung.apache.meecrowave;
import org.apache.meecrowave.Meecrowave;
public class Server {
public static void main(String[] args) {
final Meecrowave.Builder builder = new Meecrowave.Builder();
builder.setScanningPackageIncludes("com.baeldung.meecrowave");
builder.setJaxrsMapping("/api/*");
builder.setJsonpPrettify(true);
try (Meecrowave meecrowave = new Meecrowave(builder)) {
meecrowave.bake().await();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/Article.java | apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/Article.java | package com.baeldung.apache.meecrowave;
public class Article {
private String name;
private String author;
public Article() {
}
public Article(String name, String author) {
this.author = author;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/ArticleService.java | apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/ArticleService.java | package com.baeldung.apache.meecrowave;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class ArticleService {
public Article createArticle(Article article) {
return article;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/ArticleEndpoints.java | apache-libraries-2/src/main/java/com/baeldung/apache/meecrowave/ArticleEndpoints.java | package com.baeldung.apache.meecrowave;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
@RequestScoped
@Path("article")
public class ArticleEndpoints {
@Inject
ArticleService articleService;
@GET
public Response getArticle() {
return Response.ok()
.entity(new Article("name", "author"))
.build();
}
@POST
public Response createArticle(Article article) {
return Response.status(Status.CREATED)
.entity(articleService.createArticle(article))
.build();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java | libraries-stream/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java | package com.baeldung.stream;
import org.jooq.lambda.Seq;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static junit.framework.TestCase.assertEquals;
public class JoolMergeStreamsUnitTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
Stream<Integer> seq1 = Stream.of(1, 3, 5);
Stream<Integer> seq2 = Stream.of(2, 4, 6);
Stream<Integer> resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList()));
}
@Test
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<String> seq = Stream.of("foo", "bar");
Stream<String> openingBracketSeq = Stream.of("[");
Stream<String> closingBracketSeq = Stream.of("]");
Stream<String> resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq);
Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java | libraries-stream/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java | package com.baeldung.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class MergeStreamsUnitTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> resultingStream = Stream.concat(stream1, stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
}
@Test
public void givenThreeStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> stream3 = Stream.of(18, 15, 36);
Stream<Integer> resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), resultingStream.collect(Collectors.toList()));
}
@Test
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> stream3 = Stream.of(18, 15, 36);
Stream<Integer> stream4 = Stream.of(99);
Stream<Integer> resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity());
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java | libraries-stream/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java | package com.baeldung.streamex;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import one.util.streamex.StreamEx;
public class StreamExMergeStreamsUnitTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
}
@Test
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> stream3 = Stream.of(18, 15, 36);
Stream<Integer> stream4 = Stream.of(99);
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
}
@Test
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<String> stream1 = Stream.of("foo", "bar");
Stream<String> openingBracketStream = Stream.of("[");
Stream<String> closingBracketStream = Stream.of("]");
Stream<String> resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream);
assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java | libraries-stream/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java | package com.baeldung.protonpack;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import com.codepoetics.protonpack.Indexed;
import com.codepoetics.protonpack.StreamUtils;
import com.codepoetics.protonpack.collectors.CollectorUtils;
import com.codepoetics.protonpack.collectors.NonUniqueValueException;
import com.codepoetics.protonpack.selectors.Selectors;
public class ProtonpackUnitTest {
@Test
public void whenTakeWhile_thenTakenWhile() {
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
List<Integer> result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList());
assertThat(result).contains(1, 2, 3, 4);
}
@Test
public void whenTakeUntil_thenTakenUntil() {
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
List<Integer> result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList());
assertThat(result).contains(10, 20, 30, 40);
}
@Test
public void givenMultipleStream_whenZipped_thenZipped() {
String[] clubs = {"Juventus", "Barcelona", "Liverpool", "PSG"};
String[] players = {"Ronaldo", "Messi", "Salah"};
Set<String> zippedFrom2Sources = StreamUtils
.zip(stream(clubs), stream(players), (club, player) -> club + " " + player)
.collect(Collectors.toSet());
assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah");
String[] leagues = {"Serie A", "La Liga", "Premier League"};
Set<String> zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues),
(club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet());
assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga",
"Liverpool Salah Premier League");
}
@Test
public void whenZippedWithIndex_thenZippedWithIndex() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
Set<Indexed<String>> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet());
assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"),
Indexed.index(2, "Liverpool"));
}
@Test
public void givenMultipleStream_whenMerged_thenMerged() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG");
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah");
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League");
Set<String> merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs,
streamOfPlayers, streamOfLeagues).collect(Collectors.toSet());
assertThat(merged)
.contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League",
" PSG");
}
@Test
public void givenMultipleStream_whenMergedToList_thenMergedToList() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG");
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
List<List<String>> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers)
.collect(Collectors.toList());
assertThat(mergedListOfList.get(0)).isInstanceOf(List.class);
assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo");
assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi");
assertThat(mergedListOfList.get(2)).containsExactly("PSG");
}
@Test
public void givenMultipleStream_whenInterleaved_thenInterleaved() {
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga");
List<String> interleavedList = StreamUtils
.interleave(Selectors.roundRobin(), streamOfClubs, streamOfPlayers, streamOfLeagues)
.collect(Collectors.toList());
assertThat(interleavedList)
.hasSize(7)
.containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", "Liverpool");
}
@Test
public void whenSkippedUntil_thenSkippedUntil() {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5)
.collect(Collectors.toList());
assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10);
List<Integer> skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5)
.collect(Collectors.toList());
assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void whenSkippedWhile_thenSkippedWhile() {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5)
.collect(Collectors.toList());
assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10);
List<Integer> skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5)
.collect(Collectors.toList());
assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() {
Stream<Integer> unfolded = StreamUtils.unfold(2, i -> (i < 100) ? Optional.of(i * i) : Optional.empty());
assertThat(unfolded.collect(Collectors.toList())).containsExactly(2, 4, 16, 256);
}
@Test
public void whenWindowed_thenWindowed() {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7};
List<List<Integer>> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1)
.collect(Collectors.toList());
assertThat(windowedWithSkip1)
.containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6),
asList(5, 6, 7));
List<List<Integer>> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2)
.collect(Collectors.toList());
assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7));
}
@Test
public void whenAggregated_thenAggregated() {
Integer[] numbers = {1, 2, 2, 3, 4, 4, 4, 5};
List<List<Integer>> aggregated = StreamUtils
.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0)
.collect(Collectors.toList());
assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5));
List<List<Integer>> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList());
assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5));
}
@Test
public void whenGroupedRun_thenGroupedRun() {
Integer[] numbers = {1, 1, 2, 3, 4, 4, 5};
List<List<Integer>> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList());
assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5));
Integer[] numbers2 = {1, 2, 3, 1};
List<List<Integer>> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList());
assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1));
}
@Test
public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() {
Integer[] numbers = {1, 1, 2, 3, 4, 4, 5};
Stream<List<Integer>> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers),
(currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5);
assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5));
}
@Test
public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() {
Stream<String> clubs = Stream.of("Juventus", "Barcelona", "PSG");
Optional<String> longestName = clubs.collect(CollectorUtils.maxBy(String::length));
assertThat(longestName).contains("Barcelona");
}
@Test
public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() {
Stream<Integer> singleElement = Stream.of(1);
Optional<Integer> unique = singleElement.collect(CollectorUtils.unique());
assertThat(unique).contains(1);
}
@Test
public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() {
Stream<Integer> multipleElement = Stream.of(1, 2, 3);
assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> {
multipleElement.collect(CollectorUtils.unique());
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsVirtualThreadsManualTest.java | libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsVirtualThreadsManualTest.java | package com.baeldung.parallel_collectors;
import com.pivovarit.collectors.ParallelCollectors;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class ParallelCollectorsVirtualThreadsManualTest {
private static final Logger log = LoggerFactory.getLogger(ParallelCollectorsVirtualThreadsManualTest.class);
// increase the number of parallel processes to find the max number of threads on your machine
@Test
public void givenParallelism_whenUsingOSThreads_thenShouldRunOutOfThreads() {
int parallelProcesses = 50_000;
var e = Executors.newFixedThreadPool(parallelProcesses);
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), e, parallelProcesses))
.join());
log.info("{}", result);
}
@Test
public void givenParallelism_whenUsingVThreads_thenShouldProcessInParallel() {
int parallelProcesses = 1000_000;
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList()))
.join());
log.info("{}", result);
}
@Test
public void givenParallelismAndPCollectors2_whenUsingVThreads_thenShouldProcessInParallel() {
int parallelProcesses = 1000_000;
var result = timed(() -> Stream.iterate(0, i -> i + 1).limit(parallelProcesses)
.collect(ParallelCollectors.parallel(i -> fetchById(i), toList(), Executors.newVirtualThreadPerTaskExecutor(), Integer.MAX_VALUE))
.join());
log.info("{}", result);
}
private static String fetchById(int id) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore shamelessly
}
return "user-" + id;
}
private static <T> T timed(Supplier<T> supplier) {
var before = Instant.now();
T result = supplier.get();
var after = Instant.now();
log.info("Execution time: {} ms", Duration.between(before, after).toMillis());
return result;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java | libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java | package com.baeldung.parallel_collectors;
import com.pivovarit.collectors.ParallelCollectors;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.pivovarit.collectors.ParallelCollectors.parallel;
import static com.pivovarit.collectors.ParallelCollectors.parallelToOrderedStream;
import static com.pivovarit.collectors.ParallelCollectors.parallelToStream;
import static java.util.concurrent.CompletableFuture.completedFuture;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
public class ParallelCollectorsUnitTest {
@Test
public void shouldProcessInParallelWithStreams() {
List<Integer> ids = Arrays.asList(1, 2, 3);
List<String> results = ids.parallelStream()
.map(i -> fetchById(i))
.collect(toList());
assertThat(results).containsExactly("user-1", "user-2", "user-3");
}
@Test
public void shouldCollectInParallel() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<Stream<String>> results = ids.stream()
.collect(parallel(ParallelCollectorsUnitTest::fetchById, executor, 4));
assertThat(results.join()).containsExactly("user-1", "user-2", "user-3");
}
@Test
public void shouldCollectToList() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<List<String>> results = ids.stream()
.collect(parallel(ParallelCollectorsUnitTest::fetchById, toList(), executor, 4));
assertThat(results.join()).containsExactly("user-1", "user-2", "user-3");
}
@Test
public void shouldCollectToCollection() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<List<String>> results = ids.stream()
.collect(parallel(i -> fetchById(i), toCollection(LinkedList::new), executor, 4));
assertThat(results.join())
.containsExactly("user-1", "user-2", "user-3");
}
@Test
public void shouldCollectToStream() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<Map<Integer, List<String>>> results = ids.stream()
.collect(parallel(i -> fetchById(i), executor, 4))
.thenApply(stream -> stream.collect(Collectors.groupingBy(String::length)));
assertThat(results.join())
.hasSize(1)
.containsEntry(6, Arrays.asList("user-1", "user-2", "user-3"));
}
@Test
public void shouldStreamInCompletionOrder() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Stream<String> result = ids.stream()
.collect(parallelToStream(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4));
assertThat(result).contains("user-1", "user-2", "user-3");
}
@Test
public void shouldStreamInOriginalOrder() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
Stream<String> result = ids.stream()
.collect(parallelToOrderedStream(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4));
assertThat(result).containsExactly("user-1", "user-2", "user-3");
}
@Test
public void shouldCollectToMap() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<Map<Integer, String>> results = ids.stream()
.collect(parallel(i -> i, Collectors.toMap(i -> i, ParallelCollectorsUnitTest::fetchById), executor, 4));
assertThat(results.join())
.hasSize(3)
.containsEntry(1, "user-1")
.containsEntry(2, "user-2")
.containsEntry(3, "user-3");
}
@Test
public void shouldCollectToTreeMapAndResolveClashes() {
ExecutorService executor = Executors.newFixedThreadPool(10);
List<Integer> ids = Arrays.asList(1, 2, 3);
CompletableFuture<Map<Integer, String>> results = ids.stream()
.collect(parallel(i -> i, Collectors.toMap(i -> i, ParallelCollectorsUnitTest::fetchById, (u1, u2) -> u1, TreeMap::new), executor, 4));
assertThat(results.join())
.hasSize(3)
.containsEntry(1, "user-1")
.containsEntry(2, "user-2")
.containsEntry(3, "user-3");
}
@Test
public void shouldCollectListOfFutures() {
List<CompletableFuture<Integer>> futures = Arrays.asList(completedFuture(1), completedFuture(2), completedFuture(3));
CompletableFuture<List<Integer>> result = futures.stream()
.collect(ParallelCollectors.toFuture());
assertThat(result.join()).containsExactly(1, 2, 3);
}
private static String fetchById(int id) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore shamelessly
}
return "user-" + id;
}
private static String fetchByIdWithRandomDelay(int id) {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
} catch (InterruptedException e) {
// ignore shamelessly
}
return "user-" + id;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java | libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java | package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithVavrUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList();
assertTrue(personListFiltered.size() == 2);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java | libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java | package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.eclipse.collections.impl.block.factory.HashingStrategies;
import org.eclipse.collections.impl.utility.ListIterate;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithEclipseCollectionsUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName));
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge));
assertTrue(personListFiltered.size() == 2);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java | libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java | package com.baeldung.distinct;
import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class DistinctWithJavaFunctionUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList());
assertTrue(personListFiltered.size() == 2);
}
@Test
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
List<Person> personListFiltered = personList.stream().distinct().collect(Collectors.toList());
assertTrue(personListFiltered.size() == 5);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/distinct/PersonDataGenerator.java | libraries-stream/src/test/java/com/baeldung/distinct/PersonDataGenerator.java | package com.baeldung.distinct;
import java.util.Arrays;
import java.util.List;
public class PersonDataGenerator {
public static List<Person> getPersonListWithFakeValues() {
// @formatter:off
return Arrays.asList(
new Person(20, "Jhon", "jhon@test.com"),
new Person(20, "Jhon", "jhon1@test.com"),
new Person(20, "Jhon", "jhon2@test.com"),
new Person(21, "Tom", "Tom@test.com"),
new Person(21, "Mark", "Mark@test.com"),
new Person(20, "Julia", "jhon@test.com"));
// @formatter:on
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java | libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java | package com.baeldung.distinct;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import one.util.streamex.StreamEx;
public class DistinctWithStreamexUnitTest {
List<Person> personList;
@Before
public void init() {
personList = PersonDataGenerator.getPersonListWithFakeValues();
}
@Test
public void whenFilterListByName_thenSizeShouldBe4() {
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList();
assertTrue(personListFiltered.size() == 4);
}
@Test
public void whenFilterListByAge_thenSizeShouldBe2() {
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList();
assertTrue(personListFiltered.size() == 2);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/main/java/com/baeldung/streamex/StreamEX.java | libraries-stream/src/main/java/com/baeldung/streamex/StreamEX.java | package com.baeldung.streamex;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import one.util.streamex.DoubleStreamEx;
import one.util.streamex.EntryStream;
import one.util.streamex.IntStreamEx;
import one.util.streamex.StreamEx;
public class StreamEX {
public static void main(String[] args) {
// Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
List<User> users = Arrays.asList(new User("name"), new User(), new User());
users.stream().map(User::getName).collect(Collectors.toList());
List<String> userNames = StreamEx.of(users).map(User::getName).toList();
Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole);
StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
// Selecting stream elements of specific type
List usersAndRoles = Arrays.asList(new User(), new Role());
List<Role> roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
System.out.println(roles);
// adding elements to Stream
List<String> appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
System.out.println(appendedUsers);
// Removing unwanted elements and using the stream as Iterable:
for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
System.out.println(line);
}
// Selecting map keys by value predicate:
Map<String, Role> nameToRole = new HashMap<>();
nameToRole.put("first", new Role());
nameToRole.put("second", null);
Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
System.out.println(nonNullRoles);
// Operating on key-value pairs:
Map<User, List<Role>> users2roles = transformMap(role2users);
Map<String, String> mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
// Support of byte/char/short/float types:
short[] src = { 1, 2, 3 };
char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
}
public double[] getDiffBetweenPairs(double... numbers) {
return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray();
}
public static Map<User, List<Role>> transformMap(Map<Role, List<User>> role2users) {
Map<User, List<Role>> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping();
return users2roles;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/main/java/com/baeldung/streamex/Role.java | libraries-stream/src/main/java/com/baeldung/streamex/Role.java | package com.baeldung.streamex;
public class Role {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/main/java/com/baeldung/streamex/User.java | libraries-stream/src/main/java/com/baeldung/streamex/User.java | package com.baeldung.streamex;
public class User {
int id;
String name;
Role role = new Role();
public User() {
}
public User(String name) {
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 Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/main/java/com/baeldung/distinct/Person.java | libraries-stream/src/main/java/com/baeldung/distinct/Person.java | package com.baeldung.distinct;
public class Person {
int age;
String name;
String email;
public Person(int age, String name, String email) {
super();
this.age = age;
this.name = name;
this.email = email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [age=");
builder.append(age);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-stream/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java | libraries-stream/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java | package com.baeldung.distinct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class DistinctWithJavaFunction {
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java | libraries-4/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java | package com.baeldung.mapdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
public class HTreeMapUnitTest {
@Test
public void givenValidDB_whenHTreeMapAddedToAndRetrieved_CheckedRetrievalCorrect() {
DB db = DBMaker.memoryDB().make();
HTreeMap<String, String> hTreeMap = db
.hashMap("myTreMap")
.keySerializer(Serializer.STRING)
.valueSerializer(Serializer.STRING)
.create();
hTreeMap.put("key1", "value1");
hTreeMap.put("key2", "value2");
assertEquals(2, hTreeMap.size());
//add another value with the same key
hTreeMap.put("key1", "value3");
assertEquals(2, hTreeMap.size());
assertEquals("value3", hTreeMap.get("key1"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java | libraries-4/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java | package com.baeldung.mapdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
public class InMemoryModesUnitTest {
@Test
public void givenDBCreatedOnHeap_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.heapDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
@Test
public void givenDBCreatedBaseOnByteArray_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.memoryDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
@Test
public void givenDBCreatedBaseOnDirectByteBuffer_whenUsed_checkUsageCorrect() {
DB heapDB = DBMaker.memoryDirectDB().make();
HTreeMap<Integer, String> map = heapDB
.hashMap("myMap")
.keySerializer(Serializer.INTEGER)
.valueSerializer(Serializer.STRING)
.createOrOpen();
map.put(1, "ONE");
assertEquals("ONE", map.get(1));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java | libraries-4/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java | package com.baeldung.mapdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.NavigableSet;
import org.junit.jupiter.api.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
public class TransactionsUnitTest {
@Test
public void givenValidDBSetup_whenTransactionCommittedAndRolledBack_checkPreviousStateAchieved() {
DB db = DBMaker.memoryDB().transactionEnable().make();
NavigableSet<String> set = db
.treeSet("mySet")
.serializer(Serializer.STRING)
.createOrOpen();
set.add("One");
set.add("Two");
db.commit();
assertEquals(2, set.size());
set.add("Three");
assertEquals(3, set.size());
db.rollback();
assertEquals(2, set.size());
db.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java | libraries-4/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java | package com.baeldung.mapdb;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapdb.Serializer;
import org.mapdb.SortedTableMap;
import org.mapdb.volume.MappedFileVol;
import org.mapdb.volume.Volume;
public class SortedTableMapUnitTest {
private static final String VOLUME_LOCATION = "sortedTableMapVol.db";
@Test
public void givenValidSortedTableMapSetup_whenQueried_checkValuesCorrect() {
//create memory mapped volume, readonly false
Volume vol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, false);
//create sink to feed the map with data
SortedTableMap.Sink<Integer, String> sink =
SortedTableMap.create(
vol,
Serializer.INTEGER,
Serializer.STRING
).createFromSink();
//add content
for(int i = 0; i < 100; i++){
sink.put(i, "Value " + Integer.toString(i));
}
sink.create();
//now open in read-only mode
Volume openVol = MappedFileVol.FACTORY.makeVolume(VOLUME_LOCATION, true);
SortedTableMap<Integer, String> sortedTableMap = SortedTableMap.open(
openVol,
Serializer.INTEGER,
Serializer.STRING
);
assertEquals(100, sortedTableMap.size());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-4/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java | libraries-4/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java | package com.baeldung.mapdb;
import static junit.framework.Assert.assertEquals;
import java.util.NavigableSet;
import org.junit.Test;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Serializer;
public class CollectionsUnitTest {
@Test
public void givenSetCreatedInDB_whenMultipleElementsAdded_checkOnlyOneExists() {
DB db = DBMaker.memoryDB().make();
NavigableSet<String> set = db.
treeSet("mySet")
.serializer(Serializer.STRING)
.createOrOpen();
String myString = "Baeldung!";
set.add(myString);
set.add(myString);
assertEquals(1, set.size());
db.close();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.