repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java | spring-5-rest-docs/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java | package com.baeldung.queryparamdoc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document;
import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.reactive.server.WebTestClient;
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@WebFluxTest
class BookControllerReactiveIntegrationTest {
@Autowired
private WebTestClient webTestClient;
@BeforeEach
public void setUp(ApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.webTestClient = WebTestClient.bindToApplicationContext(webApplicationContext)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
@Test
void smokeTest() {
assertThat(webTestClient).isNotNull();
}
@Test
@WithMockUser
void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() {
webTestClient.get().uri("/books?page=2")
.exchange().expectStatus().isOk().expectBody()
.consumeWith(document("books",
queryParameters(parameterWithName("page").description("The page to retrieve"))));
}
@TestConfiguration
public static class TestConfig {
@Bean
BookService bookService() {
return new BookService();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java | spring-5-rest-docs/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java | package com.baeldung.queryparamdoc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@WebMvcTest(controllers = {BookController.class, BookService.class},
excludeAutoConfiguration = SecurityAutoConfiguration.class)
class BookControllerMvcIntegrationTest {
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.mockMvc = webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
@Test
void smokeTest() {
assertThat(mockMvc).isNotNull();
}
@Test
void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() throws Exception {
mockMvc.perform(get("/books?page=2"))
.andExpect(status().isOk())
.andDo(document("books",
queryParameters(parameterWithName("page").description("The page to retrieve"))));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/restdocs/CRUDController.java | spring-5-rest-docs/src/main/java/com/baeldung/restdocs/CRUDController.java | package com.baeldung.restdocs;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import java.util.ArrayList;
import java.util.List;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/crud")
public class CRUDController {
@GetMapping
public List<CrudInput> read(@RequestBody @Valid CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
returnList.add(crudInput);
return returnList;
}
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public HttpHeaders save(@RequestBody @Valid CrudInput crudInput) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(CRUDController.class).slash(crudInput.getId()).toUri());
return httpHeaders;
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
HttpHeaders delete(@PathVariable("id") long id) {
return new HttpHeaders();
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.ACCEPTED)
void put(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
}
@PatchMapping("/{id}")
public List<CrudInput> patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) {
List<CrudInput> returnList = new ArrayList<>();
crudInput.setId(id);
returnList.add(crudInput);
return returnList;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/restdocs/CrudInput.java | spring-5-rest-docs/src/main/java/com/baeldung/restdocs/CrudInput.java | package com.baeldung.restdocs;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CrudInput {
@NotNull
private long id;
@NotBlank
private String title;
private String body;
private List<URI> tagUris;
@JsonCreator
public CrudInput(@JsonProperty("id") long id, @JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List<URI> tagUris) {
this.id=id;
this.title = title;
this.body = body;
this.tagUris = tagUris == null ? Collections.<URI> emptyList() : tagUris;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
public void setTagUris(List<URI> tagUris) {
this.tagUris = tagUris;
}
@JsonProperty("tags")
public List<URI> getTagUris() {
return this.tagUris;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/restdocs/IndexController.java | spring-5-rest-docs/src/main/java/com/baeldung/restdocs/IndexController.java | package com.baeldung.restdocs;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
@RestController
@RequestMapping("/")
public class IndexController {
static class CustomRepresentationModel extends RepresentationModel<CustomRepresentationModel> {
public CustomRepresentationModel(Link initialLink) {
super(initialLink);
}
}
@GetMapping
public CustomRepresentationModel index() {
return new CustomRepresentationModel(linkTo(CRUDController.class).withRel("crud"));
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java | spring-5-rest-docs/src/main/java/com/baeldung/restdocs/SpringRestDocsApplication.java | package com.baeldung.restdocs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SpringRestDocsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringRestDocsApplication.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/Book.java | spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/Book.java | package com.baeldung.queryparamdoc;
public class Book {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/BookService.java | spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/BookService.java | package com.baeldung.queryparamdoc;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class BookService {
@SuppressWarnings("unused")
public List<Book> getBooks(Integer page) {
return new ArrayList<>();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/BookController.java | spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/BookController.java | package com.baeldung.queryparamdoc;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<Book> getBooks(@RequestParam(name = "page") Integer page) {
return service.getBooks(page);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/Application.java | spring-5-rest-docs/src/main/java/com/baeldung/queryparamdoc/Application.java | package com.baeldung.queryparamdoc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis/MyBatisApplication.java | mybatis/src/main/java/com/baeldung/mybatis/MyBatisApplication.java | package com.baeldung.mybatis;
import com.baeldung.mybatis.model.Address;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisApplication {
public static void main(String[] args) throws IOException {
// Create a SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Open a SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
// Execute a query
List<Address> addressList = session.selectList("com.baeldung.mybatis.mapper.AddressMapper.getAddresses", 1);
for (Address address : addressList) {
System.out.println(address);
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis/model/Person.java | mybatis/src/main/java/com/baeldung/mybatis/model/Person.java | package com.baeldung.mybatis.model;
import java.util.ArrayList;
import java.util.List;
public class Person {
private Integer personId;
private String name;
private List<Address> addresses;
public Person() {
}
public Person(Integer personId, String name) {
this.personId = personId;
this.name = name;
addresses = new ArrayList<Address>();
}
public Person(String name) {
this.name = name;
}
public Integer getPersonId() {
return personId;
}
public String getName() {
return name;
}
public void addAddress(Address address) {
addresses.add(address);
}
public List<Address> getAddresses() {
return addresses;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis/model/Address.java | mybatis/src/main/java/com/baeldung/mybatis/model/Address.java | package com.baeldung.mybatis.model;
public class Address {
private Integer addressId;
private String streetAddress;
private Integer personId;
public Address() {
}
public Integer getPersonId() {
return personId;
}
public void setPersonId(Integer personId) {
this.personId = personId;
}
public Address(String streetAddress) {
this.streetAddress = streetAddress;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
private Person person;
public Address(int i, String name) {
this.streetAddress = name;
}
public Integer getAddressId() {
return addressId;
}
public String getStreetAddress() {
return streetAddress;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis/utils/MyBatisUtil.java | mybatis/src/main/java/com/baeldung/mybatis/utils/MyBatisUtil.java | package com.baeldung.mybatis.utils;
import com.baeldung.mybatis.mapper.AddressMapper;
import com.baeldung.mybatis.mapper.PersonMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
public class MyBatisUtil {
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String URL = "jdbc:derby:testdb1;create=true";
public static final String USERNAME = "sa";
public static final String PASSWORD = "pass123";
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory buildqlSessionFactory() {
DataSource dataSource = new PooledDataSource(DRIVER, URL, USERNAME, PASSWORD);
Environment environment = new Environment("Development", new JdbcTransactionFactory(), dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(PersonMapper.class);
configuration.addMapper(AddressMapper.class);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(configuration);
return factory;
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public String getPersonByName(String name) {
return new SQL() {
{
SELECT("*");
FROM("person");
WHERE("name like #{name} || '%'");
}
}.toString();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis/mapper/PersonMapper.java | mybatis/src/main/java/com/baeldung/mybatis/mapper/PersonMapper.java | package com.baeldung.mybatis.mapper;
import com.baeldung.mybatis.model.Address;
import com.baeldung.mybatis.model.Person;
import com.baeldung.mybatis.utils.MyBatisUtil;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.StatementType;
import java.util.List;
import java.util.Map;
public interface PersonMapper {
@Insert("Insert into person(name) values (#{name})")
public Integer save(Person person);
@Update("Update Person set name= #{name} where personId=#{personId}")
public void updatePerson(Person person);
@Delete("Delete from Person where personId=#{personId}")
public void deletePersonById(Integer personId);
@Select("SELECT person.personId, person.name FROM person WHERE person.personId = #{personId}")
Person getPerson(Integer personId);
@Select("Select personId,name from Person where personId=#{personId}")
@Results(value = { @Result(property = "personId", column = "personId"), @Result(property = "name", column = "name"),
@Result(property = "addresses", javaType = List.class, column = "personId", many = @Many(select = "getAddresses"))
})
public Person getPersonById(Integer personId);
@Select("select addressId,streetAddress,personId from address where personId=#{personId}")
public Address getAddresses(Integer personId);
@Select("select * from Person ")
@MapKey("personId")
Map<Integer, Person> getAllPerson();
@SelectProvider(type = MyBatisUtil.class, method = "getPersonByName")
public Person getPersonByName(String name);
@Select(value = "{ CALL getPersonByProc( #{personId, mode=IN, jdbcType=INTEGER})}")
@Options(statementType = StatementType.CALLABLE)
public Person getPersonByProc(Integer personId);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis/mapper/AddressMapper.java | mybatis/src/main/java/com/baeldung/mybatis/mapper/AddressMapper.java | package com.baeldung.mybatis.mapper;
import com.baeldung.mybatis.model.Address;
import com.baeldung.mybatis.model.Person;
import org.apache.ibatis.annotations.*;
public interface AddressMapper {
@Insert("Insert into address (streetAddress,personId) values(#{streetAddress},#{personId})")
@Options(useGeneratedKeys = true, flushCache = true)
public Integer saveAddress(Address address);
@Select("SELECT addressId, streetAddress FROM Address WHERE addressId = #{addressId}")
@Results(value = { @Result(property = "addressId", column = "addressId"),
@Result(property = "streetAddress", column = "streetAddress"),
@Result(property = "person", column = "personId", javaType = Person.class, one = @One(select = "getPerson")) })
Address getAddresses(Integer addressId);
@Select("SELECT personId FROM address WHERE addressId = #{addressId})")
Person getPerson(Integer addressId);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/mybatis/src/main/java/com/baeldung/mybatis_sqlscript/Main.java | mybatis/src/main/java/com/baeldung/mybatis_sqlscript/Main.java | package com.baeldung.mybatis_sqlscript;
import org.apache.ibatis.jdbc.ScriptRunner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.*;
import java.util.List;
import java.util.Scanner;
public class Main {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:mem:testDB";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
private static Connection conn;
private static Statement stmt;
public static void main(String[] args){
try {
//Register JDBC driver
Class.forName(JDBC_DRIVER);
//Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
}
catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
try {
Scanner sc = new Scanner(System.in);
System.out.println("Enter full path of the file: ");
String filePath= sc.next();
Path path = Paths.get(filePath);
System.out.println("Press 1: Execute SQL Script Using Plain Java: ");
System.out.println("Press 2: Execute SQL Script Using Apache iBatis: ");
List<String> sqlLines=Files.readAllLines(path);
int choice = sc.nextInt();
switch (choice)
{
case 1:
// Running SQL Script using Plain Java
for (String sql : sqlLines) {
System.out.println("Query: " + sql);
if (sql.contains("SELECT")) {
ResultSet rs = stmt.executeQuery(sql);
System.out.print("ID" + "\t" + "Name" + "\t" + "Surname" + "\t" + "Age");
System.out.println("");
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getRow();
int age = rs.getInt("age");
String name = rs.getString("name");
String surname = rs.getString("surname");
// Display values
System.out.print(id + "\t" + name + "\t" + surname + "\t" + age);
System.out.println("");
}
}
else
stmt.execute(sql);
}
break;
case 2:
ScriptRunner scriptExecutor = new ScriptRunner(conn);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
scriptExecutor.runScript(reader);
reader.close();
break;
}
}
catch(SQLException se)
{
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
System.out.println("Reached End of Code!");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-mobile/src/test/java/org/baeldung/SpringContextTest.java | spring-mobile/src/test/java/org/baeldung/SpringContextTest.java | package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-mobile/src/main/java/com/baeldung/AppConfig.java | spring-mobile/src/main/java/com/baeldung/AppConfig.java | package com.baeldung;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver;
import org.springframework.mobile.device.DeviceResolverHandlerInterceptor;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Bean
public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() {
return new DeviceResolverHandlerInterceptor();
}
@Bean
public DeviceHandlerMethodArgumentResolver deviceHandlerMethodArgumentResolver() {
return new DeviceHandlerMethodArgumentResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(deviceResolverHandlerInterceptor());
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(deviceHandlerMethodArgumentResolver());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-mobile/src/main/java/com/baeldung/Application.java | spring-mobile/src/main/java/com/baeldung/Application.java | package com.baeldung;
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 | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java | spring-mobile/src/main/java/com/baeldung/controller/IndexController.java | package com.baeldung.controller;
import java.util.logging.Logger;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
private final static Logger LOGGER = Logger.getLogger(IndexController.class.getName());
@GetMapping("/")
public String greeting(Device device) {
String deviceType = "browser";
String platform = "browser";
String viewName = "index";
if (device.isNormal()) {
deviceType = "browser";
} else if (device.isMobile()) {
deviceType = "mobile";
viewName = "mobile/index";
} else if (device.isTablet()) {
deviceType = "tablet";
viewName = "tablet/index";
}
platform = device.getDevicePlatform().name();
if (platform.equalsIgnoreCase("UNKNOWN")) {
platform = "browser";
}
LOGGER.info("Client Device Type: " + deviceType + ", Platform: " + platform);
return viewName;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java | apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java | package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CrossPlatformServiceIntegrationTest {
private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
@Before
public void setUp() {
new Thread(() -> {
try {
server.start();
} catch (TTransportException e) {
e.printStackTrace();
}
}).start();
try {
// wait for the server start up
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() {
server.stop();
}
@Test
public void ping() {
CrossPlatformServiceClient client = new CrossPlatformServiceClient();
Assert.assertTrue(client.ping());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java | apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java | package com.baeldung.thrift;
import com.baeldung.thrift.impl.CrossPlatformService;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
public class CrossPlatformServiceServer {
private TServer server;
public void start() throws TTransportException {
TServerTransport serverTransport = new TServerSocket(9090);
server = new TSimpleServer(new TServer.Args(serverTransport)
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
System.out.print("Starting the server... ");
server.serve();
System.out.println("done.");
}
public void stop() {
if (server != null && server.isServing()) {
System.out.print("Stopping the server... ");
server.stop();
System.out.println("done.");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java | apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java | package com.baeldung.thrift;
import com.baeldung.thrift.impl.CrossPlatformResource;
import com.baeldung.thrift.impl.CrossPlatformService;
import com.baeldung.thrift.impl.InvalidOperationException;
import org.apache.thrift.TException;
import java.util.Collections;
import java.util.List;
public class CrossPlatformServiceImpl implements CrossPlatformService.Iface {
@Override
public CrossPlatformResource get(final int id) throws InvalidOperationException, TException {
// add some action
return new CrossPlatformResource();
}
@Override
public void save(final CrossPlatformResource resource) throws InvalidOperationException, TException {
// add some action
}
@Override
public List<CrossPlatformResource> getList() throws InvalidOperationException, TException {
// add some action
return Collections.emptyList();
}
@Override
public boolean ping() throws InvalidOperationException, TException {
return true;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java | apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java | package com.baeldung.thrift;
import com.baeldung.thrift.impl.CrossPlatformService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class CrossPlatformServiceClient {
public boolean ping() {
try {
TTransport transport;
transport = new TSocket("localhost", 9090);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
CrossPlatformService.Client client = new CrossPlatformService.Client(protocol);
System.out.print("Calling remote method...");
boolean result = client.ping();
System.out.println("done.");
transport.close();
return result;
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException x) {
x.printStackTrace();
}
return false;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java | apache-thrift/src/main/java/com/baeldung/thrift/Application.java | package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
public class Application {
public static void main(String[] args) throws TTransportException {
CrossPlatformServiceServer server = new CrossPlatformServiceServer();
server.start();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java | apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.baeldung.thrift.impl;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
public class InvalidOperationException extends org.apache.thrift.TException implements org.apache.thrift.TBase<InvalidOperationException, InvalidOperationException._Fields>, java.io.Serializable, Cloneable, Comparable<InvalidOperationException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperationException");
private static final org.apache.thrift.protocol.TField CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("code", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new InvalidOperationExceptionStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new InvalidOperationExceptionTupleSchemeFactory();
public int code; // required
public java.lang.String description; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
CODE((short)1, "code"),
DESCRIPTION((short)2, "description");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // CODE
return CODE;
case 2: // DESCRIPTION
return DESCRIPTION;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __CODE_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.CODE, new org.apache.thrift.meta_data.FieldMetaData("code", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvalidOperationException.class, metaDataMap);
}
public InvalidOperationException() {
}
public InvalidOperationException(
int code,
java.lang.String description)
{
this();
this.code = code;
setCodeIsSet(true);
this.description = description;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public InvalidOperationException(InvalidOperationException other) {
__isset_bitfield = other.__isset_bitfield;
this.code = other.code;
if (other.isSetDescription()) {
this.description = other.description;
}
}
public InvalidOperationException deepCopy() {
return new InvalidOperationException(this);
}
@Override
public void clear() {
setCodeIsSet(false);
this.code = 0;
this.description = null;
}
public int getCode() {
return this.code;
}
public InvalidOperationException setCode(int code) {
this.code = code;
setCodeIsSet(true);
return this;
}
public void unsetCode() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CODE_ISSET_ID);
}
/** Returns true if field code is set (has been assigned a value) and false otherwise */
public boolean isSetCode() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CODE_ISSET_ID);
}
public void setCodeIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CODE_ISSET_ID, value);
}
public java.lang.String getDescription() {
return this.description;
}
public InvalidOperationException setDescription(java.lang.String description) {
this.description = description;
return this;
}
public void unsetDescription() {
this.description = null;
}
/** Returns true if field description is set (has been assigned a value) and false otherwise */
public boolean isSetDescription() {
return this.description != null;
}
public void setDescriptionIsSet(boolean value) {
if (!value) {
this.description = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case CODE:
if (value == null) {
unsetCode();
} else {
setCode((java.lang.Integer)value);
}
break;
case DESCRIPTION:
if (value == null) {
unsetDescription();
} else {
setDescription((java.lang.String)value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case CODE:
return getCode();
case DESCRIPTION:
return getDescription();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case CODE:
return isSetCode();
case DESCRIPTION:
return isSetDescription();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof InvalidOperationException)
return this.equals((InvalidOperationException)that);
return false;
}
public boolean equals(InvalidOperationException that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_code = true;
boolean that_present_code = true;
if (this_present_code || that_present_code) {
if (!(this_present_code && that_present_code))
return false;
if (this.code != that.code)
return false;
}
boolean this_present_description = true && this.isSetDescription();
boolean that_present_description = true && that.isSetDescription();
if (this_present_description || that_present_description) {
if (!(this_present_description && that_present_description))
return false;
if (!this.description.equals(that.description))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + code;
hashCode = hashCode * 8191 + ((isSetDescription()) ? 131071 : 524287);
if (isSetDescription())
hashCode = hashCode * 8191 + description.hashCode();
return hashCode;
}
@Override
public int compareTo(InvalidOperationException other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetCode()).compareTo(other.isSetCode());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCode()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.code, other.code);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDescription()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("InvalidOperationException(");
boolean first = true;
sb.append("code:");
sb.append(this.code);
first = false;
if (!first) sb.append(", ");
sb.append("description:");
if (this.description == null) {
sb.append("null");
} else {
sb.append(this.description);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class InvalidOperationExceptionStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public InvalidOperationExceptionStandardScheme getScheme() {
return new InvalidOperationExceptionStandardScheme();
}
}
private static class InvalidOperationExceptionStandardScheme extends org.apache.thrift.scheme.StandardScheme<InvalidOperationException> {
public void read(org.apache.thrift.protocol.TProtocol iprot, InvalidOperationException struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // CODE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.code = iprot.readI32();
struct.setCodeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // DESCRIPTION
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.description = iprot.readString();
struct.setDescriptionIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, InvalidOperationException struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(CODE_FIELD_DESC);
oprot.writeI32(struct.code);
oprot.writeFieldEnd();
if (struct.description != null) {
oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);
oprot.writeString(struct.description);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class InvalidOperationExceptionTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public InvalidOperationExceptionTupleScheme getScheme() {
return new InvalidOperationExceptionTupleScheme();
}
}
private static class InvalidOperationExceptionTupleScheme extends org.apache.thrift.scheme.TupleScheme<InvalidOperationException> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetCode()) {
optionals.set(0);
}
if (struct.isSetDescription()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetCode()) {
oprot.writeI32(struct.code);
}
if (struct.isSetDescription()) {
oprot.writeString(struct.description);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.code = iprot.readI32();
struct.setCodeIsSet(true);
}
if (incoming.get(1)) {
struct.description = iprot.readString();
struct.setDescriptionIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java | apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.baeldung.thrift.impl;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
public class CrossPlatformService {
public interface Iface {
public CrossPlatformResource get(int id) throws InvalidOperationException, org.apache.thrift.TException;
public void save(CrossPlatformResource resource) throws InvalidOperationException, org.apache.thrift.TException;
public java.util.List<CrossPlatformResource> getList() throws InvalidOperationException, org.apache.thrift.TException;
public boolean ping() throws InvalidOperationException, org.apache.thrift.TException;
}
public interface AsyncIface {
public void get(int id, org.apache.thrift.async.AsyncMethodCallback<CrossPlatformResource> resultHandler) throws org.apache.thrift.TException;
public void save(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws org.apache.thrift.TException;
public void getList(org.apache.thrift.async.AsyncMethodCallback<java.util.List<CrossPlatformResource>> resultHandler) throws org.apache.thrift.TException;
public void ping(org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public CrossPlatformResource get(int id) throws InvalidOperationException, org.apache.thrift.TException
{
send_get(id);
return recv_get();
}
public void send_get(int id) throws org.apache.thrift.TException
{
get_args args = new get_args();
args.setId(id);
sendBase("get", args);
}
public CrossPlatformResource recv_get() throws InvalidOperationException, org.apache.thrift.TException
{
get_result result = new get_result();
receiveBase(result, "get");
if (result.isSetSuccess()) {
return result.success;
}
if (result.e != null) {
throw result.e;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "get failed: unknown result");
}
public void save(CrossPlatformResource resource) throws InvalidOperationException, org.apache.thrift.TException
{
send_save(resource);
recv_save();
}
public void send_save(CrossPlatformResource resource) throws org.apache.thrift.TException
{
save_args args = new save_args();
args.setResource(resource);
sendBase("save", args);
}
public void recv_save() throws InvalidOperationException, org.apache.thrift.TException
{
save_result result = new save_result();
receiveBase(result, "save");
if (result.e != null) {
throw result.e;
}
return;
}
public java.util.List<CrossPlatformResource> getList() throws InvalidOperationException, org.apache.thrift.TException
{
send_getList();
return recv_getList();
}
public void send_getList() throws org.apache.thrift.TException
{
getList_args args = new getList_args();
sendBase("getList", args);
}
public java.util.List<CrossPlatformResource> recv_getList() throws InvalidOperationException, org.apache.thrift.TException
{
getList_result result = new getList_result();
receiveBase(result, "getList");
if (result.isSetSuccess()) {
return result.success;
}
if (result.e != null) {
throw result.e;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getList failed: unknown result");
}
public boolean ping() throws InvalidOperationException, org.apache.thrift.TException
{
send_ping();
return recv_ping();
}
public void send_ping() throws org.apache.thrift.TException
{
ping_args args = new ping_args();
sendBase("ping", args);
}
public boolean recv_ping() throws InvalidOperationException, org.apache.thrift.TException
{
ping_result result = new ping_result();
receiveBase(result, "ping");
if (result.isSetSuccess()) {
return result.success;
}
if (result.e != null) {
throw result.e;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "ping failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void get(int id, org.apache.thrift.async.AsyncMethodCallback<CrossPlatformResource> resultHandler) throws org.apache.thrift.TException {
checkReady();
get_call method_call = new get_call(id, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class get_call extends org.apache.thrift.async.TAsyncMethodCall<CrossPlatformResource> {
private int id;
public get_call(int id, org.apache.thrift.async.AsyncMethodCallback<CrossPlatformResource> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.id = id;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("get", org.apache.thrift.protocol.TMessageType.CALL, 0));
get_args args = new get_args();
args.setId(id);
args.write(prot);
prot.writeMessageEnd();
}
public CrossPlatformResource getResult() throws InvalidOperationException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_get();
}
}
public void save(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws org.apache.thrift.TException {
checkReady();
save_call method_call = new save_call(resource, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class save_call extends org.apache.thrift.async.TAsyncMethodCall<Void> {
private CrossPlatformResource resource;
public save_call(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.resource = resource;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("save", org.apache.thrift.protocol.TMessageType.CALL, 0));
save_args args = new save_args();
args.setResource(resource);
args.write(prot);
prot.writeMessageEnd();
}
public Void getResult() throws InvalidOperationException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return null;
}
}
public void getList(org.apache.thrift.async.AsyncMethodCallback<java.util.List<CrossPlatformResource>> resultHandler) throws org.apache.thrift.TException {
checkReady();
getList_call method_call = new getList_call(resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class getList_call extends org.apache.thrift.async.TAsyncMethodCall<java.util.List<CrossPlatformResource>> {
public getList_call(org.apache.thrift.async.AsyncMethodCallback<java.util.List<CrossPlatformResource>> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getList", org.apache.thrift.protocol.TMessageType.CALL, 0));
getList_args args = new getList_args();
args.write(prot);
prot.writeMessageEnd();
}
public java.util.List<CrossPlatformResource> getResult() throws InvalidOperationException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_getList();
}
}
public void ping(org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
checkReady();
ping_call method_call = new ping_call(resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class ping_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.Boolean> {
public ping_call(org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("ping", org.apache.thrift.protocol.TMessageType.CALL, 0));
ping_args args = new ping_args();
args.write(prot);
prot.writeMessageEnd();
}
public java.lang.Boolean getResult() throws InvalidOperationException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_ping();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("get", new get());
processMap.put("save", new save());
processMap.put("getList", new getList());
processMap.put("ping", new ping());
return processMap;
}
public static class get<I extends Iface> extends org.apache.thrift.ProcessFunction<I, get_args> {
public get() {
super("get");
}
public get_args getEmptyArgsInstance() {
return new get_args();
}
protected boolean isOneway() {
return false;
}
public get_result getResult(I iface, get_args args) throws org.apache.thrift.TException {
get_result result = new get_result();
try {
result.success = iface.get(args.id);
} catch (InvalidOperationException e) {
result.e = e;
}
return result;
}
}
public static class save<I extends Iface> extends org.apache.thrift.ProcessFunction<I, save_args> {
public save() {
super("save");
}
public save_args getEmptyArgsInstance() {
return new save_args();
}
protected boolean isOneway() {
return false;
}
public save_result getResult(I iface, save_args args) throws org.apache.thrift.TException {
save_result result = new save_result();
try {
iface.save(args.resource);
} catch (InvalidOperationException e) {
result.e = e;
}
return result;
}
}
public static class getList<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getList_args> {
public getList() {
super("getList");
}
public getList_args getEmptyArgsInstance() {
return new getList_args();
}
protected boolean isOneway() {
return false;
}
public getList_result getResult(I iface, getList_args args) throws org.apache.thrift.TException {
getList_result result = new getList_result();
try {
result.success = iface.getList();
} catch (InvalidOperationException e) {
result.e = e;
}
return result;
}
}
public static class ping<I extends Iface> extends org.apache.thrift.ProcessFunction<I, ping_args> {
public ping() {
super("ping");
}
public ping_args getEmptyArgsInstance() {
return new ping_args();
}
protected boolean isOneway() {
return false;
}
public ping_result getResult(I iface, ping_args args) throws org.apache.thrift.TException {
ping_result result = new ping_result();
try {
result.success = iface.ping();
result.setSuccessIsSet(true);
} catch (InvalidOperationException e) {
result.e = e;
}
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new java.util.HashMap<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("get", new get());
processMap.put("save", new save());
processMap.put("getList", new getList());
processMap.put("ping", new ping());
return processMap;
}
public static class get<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, get_args, CrossPlatformResource> {
public get() {
super("get");
}
public get_args getEmptyArgsInstance() {
return new get_args();
}
public org.apache.thrift.async.AsyncMethodCallback<CrossPlatformResource> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<CrossPlatformResource>() {
public void onComplete(CrossPlatformResource o) {
get_result result = new get_result();
result.success = o;
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
get_result result = new get_result();
if (e instanceof InvalidOperationException) {
result.e = (InvalidOperationException) e;
result.setEIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, get_args args, org.apache.thrift.async.AsyncMethodCallback<CrossPlatformResource> resultHandler) throws org.apache.thrift.TException {
iface.get(args.id,resultHandler);
}
}
public static class save<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, save_args, Void> {
public save() {
super("save");
}
public save_args getEmptyArgsInstance() {
return new save_args();
}
public org.apache.thrift.async.AsyncMethodCallback<Void> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<Void>() {
public void onComplete(Void o) {
save_result result = new save_result();
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
save_result result = new save_result();
if (e instanceof InvalidOperationException) {
result.e = (InvalidOperationException) e;
result.setEIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, save_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws org.apache.thrift.TException {
iface.save(args.resource,resultHandler);
}
}
public static class getList<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getList_args, java.util.List<CrossPlatformResource>> {
public getList() {
super("getList");
}
public getList_args getEmptyArgsInstance() {
return new getList_args();
}
public org.apache.thrift.async.AsyncMethodCallback<java.util.List<CrossPlatformResource>> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.util.List<CrossPlatformResource>>() {
public void onComplete(java.util.List<CrossPlatformResource> o) {
getList_result result = new getList_result();
result.success = o;
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
getList_result result = new getList_result();
if (e instanceof InvalidOperationException) {
result.e = (InvalidOperationException) e;
result.setEIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, getList_args args, org.apache.thrift.async.AsyncMethodCallback<java.util.List<CrossPlatformResource>> resultHandler) throws org.apache.thrift.TException {
iface.getList(resultHandler);
}
}
public static class ping<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, ping_args, java.lang.Boolean> {
public ping() {
super("ping");
}
public ping_args getEmptyArgsInstance() {
return new ping_args();
}
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean>() {
public void onComplete(java.lang.Boolean o) {
ping_result result = new ping_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
ping_result result = new ping_result();
if (e instanceof InvalidOperationException) {
result.e = (InvalidOperationException) e;
result.setEIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, ping_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Boolean> resultHandler) throws org.apache.thrift.TException {
iface.ping(resultHandler);
}
}
}
public static class get_args implements org.apache.thrift.TBase<get_args, get_args._Fields>, java.io.Serializable, Cloneable, Comparable<get_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("get_args");
private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new get_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new get_argsTupleSchemeFactory();
public int id; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
ID((short)1, "id");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // ID
return ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | true |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java | apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.baeldung.thrift.impl;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
public class CrossPlatformResource implements org.apache.thrift.TBase<CrossPlatformResource, CrossPlatformResource._Fields>, java.io.Serializable, Cloneable, Comparable<CrossPlatformResource> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CrossPlatformResource");
private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField SALUTATION_FIELD_DESC = new org.apache.thrift.protocol.TField("salutation", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new CrossPlatformResourceStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new CrossPlatformResourceTupleSchemeFactory();
public int id; // required
public java.lang.String name; // required
public java.lang.String salutation; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
ID((short)1, "id"),
NAME((short)2, "name"),
SALUTATION((short)3, "salutation");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // ID
return ID;
case 2: // NAME
return NAME;
case 3: // SALUTATION
return SALUTATION;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __ID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.SALUTATION};
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.SALUTATION, new org.apache.thrift.meta_data.FieldMetaData("salutation", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CrossPlatformResource.class, metaDataMap);
}
public CrossPlatformResource() {
}
public CrossPlatformResource(
int id,
java.lang.String name)
{
this();
this.id = id;
setIdIsSet(true);
this.name = name;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public CrossPlatformResource(CrossPlatformResource other) {
__isset_bitfield = other.__isset_bitfield;
this.id = other.id;
if (other.isSetName()) {
this.name = other.name;
}
if (other.isSetSalutation()) {
this.salutation = other.salutation;
}
}
public CrossPlatformResource deepCopy() {
return new CrossPlatformResource(this);
}
@Override
public void clear() {
setIdIsSet(false);
this.id = 0;
this.name = null;
this.salutation = null;
}
public int getId() {
return this.id;
}
public CrossPlatformResource setId(int id) {
this.id = id;
setIdIsSet(true);
return this;
}
public void unsetId() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID);
}
/** Returns true if field id is set (has been assigned a value) and false otherwise */
public boolean isSetId() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID);
}
public void setIdIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value);
}
public java.lang.String getName() {
return this.name;
}
public CrossPlatformResource setName(java.lang.String name) {
this.name = name;
return this;
}
public void unsetName() {
this.name = null;
}
/** Returns true if field name is set (has been assigned a value) and false otherwise */
public boolean isSetName() {
return this.name != null;
}
public void setNameIsSet(boolean value) {
if (!value) {
this.name = null;
}
}
public java.lang.String getSalutation() {
return this.salutation;
}
public CrossPlatformResource setSalutation(java.lang.String salutation) {
this.salutation = salutation;
return this;
}
public void unsetSalutation() {
this.salutation = null;
}
/** Returns true if field salutation is set (has been assigned a value) and false otherwise */
public boolean isSetSalutation() {
return this.salutation != null;
}
public void setSalutationIsSet(boolean value) {
if (!value) {
this.salutation = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case ID:
if (value == null) {
unsetId();
} else {
setId((java.lang.Integer)value);
}
break;
case NAME:
if (value == null) {
unsetName();
} else {
setName((java.lang.String)value);
}
break;
case SALUTATION:
if (value == null) {
unsetSalutation();
} else {
setSalutation((java.lang.String)value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case ID:
return getId();
case NAME:
return getName();
case SALUTATION:
return getSalutation();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case ID:
return isSetId();
case NAME:
return isSetName();
case SALUTATION:
return isSetSalutation();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof CrossPlatformResource)
return this.equals((CrossPlatformResource)that);
return false;
}
public boolean equals(CrossPlatformResource that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_id = true;
boolean that_present_id = true;
if (this_present_id || that_present_id) {
if (!(this_present_id && that_present_id))
return false;
if (this.id != that.id)
return false;
}
boolean this_present_name = true && this.isSetName();
boolean that_present_name = true && that.isSetName();
if (this_present_name || that_present_name) {
if (!(this_present_name && that_present_name))
return false;
if (!this.name.equals(that.name))
return false;
}
boolean this_present_salutation = true && this.isSetSalutation();
boolean that_present_salutation = true && that.isSetSalutation();
if (this_present_salutation || that_present_salutation) {
if (!(this_present_salutation && that_present_salutation))
return false;
if (!this.salutation.equals(that.salutation))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + id;
hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287);
if (isSetName())
hashCode = hashCode * 8191 + name.hashCode();
hashCode = hashCode * 8191 + ((isSetSalutation()) ? 131071 : 524287);
if (isSetSalutation())
hashCode = hashCode * 8191 + salutation.hashCode();
return hashCode;
}
@Override
public int compareTo(CrossPlatformResource other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetName()).compareTo(other.isSetName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetSalutation()).compareTo(other.isSetSalutation());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSalutation()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.salutation, other.salutation);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("CrossPlatformResource(");
boolean first = true;
sb.append("id:");
sb.append(this.id);
first = false;
if (!first) sb.append(", ");
sb.append("name:");
if (this.name == null) {
sb.append("null");
} else {
sb.append(this.name);
}
first = false;
if (isSetSalutation()) {
if (!first) sb.append(", ");
sb.append("salutation:");
if (this.salutation == null) {
sb.append("null");
} else {
sb.append(this.salutation);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class CrossPlatformResourceStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public CrossPlatformResourceStandardScheme getScheme() {
return new CrossPlatformResourceStandardScheme();
}
}
private static class CrossPlatformResourceStandardScheme extends org.apache.thrift.scheme.StandardScheme<CrossPlatformResource> {
public void read(org.apache.thrift.protocol.TProtocol iprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.id = iprot.readI32();
struct.setIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // SALUTATION
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.salutation = iprot.readString();
struct.setSalutationIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(ID_FIELD_DESC);
oprot.writeI32(struct.id);
oprot.writeFieldEnd();
if (struct.name != null) {
oprot.writeFieldBegin(NAME_FIELD_DESC);
oprot.writeString(struct.name);
oprot.writeFieldEnd();
}
if (struct.salutation != null) {
if (struct.isSetSalutation()) {
oprot.writeFieldBegin(SALUTATION_FIELD_DESC);
oprot.writeString(struct.salutation);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class CrossPlatformResourceTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public CrossPlatformResourceTupleScheme getScheme() {
return new CrossPlatformResourceTupleScheme();
}
}
private static class CrossPlatformResourceTupleScheme extends org.apache.thrift.scheme.TupleScheme<CrossPlatformResource> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetId()) {
optionals.set(0);
}
if (struct.isSetName()) {
optionals.set(1);
}
if (struct.isSetSalutation()) {
optionals.set(2);
}
oprot.writeBitSet(optionals, 3);
if (struct.isSetId()) {
oprot.writeI32(struct.id);
}
if (struct.isSetName()) {
oprot.writeString(struct.name);
}
if (struct.isSetSalutation()) {
oprot.writeString(struct.salutation);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(3);
if (incoming.get(0)) {
struct.id = iprot.readI32();
struct.setIdIsSet(true);
}
if (incoming.get(1)) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
}
if (incoming.get(2)) {
struct.salutation = iprot.readString();
struct.setSalutationIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/error-prone-library/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java | static-analysis-modules/error-prone-library/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java | package com.baeldung;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.MethodTree;
@AutoService(BugChecker.class)
@BugPattern(name = "EmptyMethodCheck", summary = "Empty methods should be deleted", severity = BugPattern.SeverityLevel.ERROR)
public class EmptyMethodChecker extends BugChecker implements BugChecker.MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState visitorState) {
if (methodTree.getBody()
.getStatements()
.isEmpty()) {
return describeMatch(methodTree, SuggestedFix.delete(methodTree));
}
return Description.NO_MATCH;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/error-prone-library/pmd/src/test/java/com/baeldung/pmd/CntUnitTest.java | static-analysis-modules/error-prone-library/pmd/src/test/java/com/baeldung/pmd/CntUnitTest.java | package com.baeldung.pmd;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CntUnitTest {
private Cnt service;
@Test
public void whenSecondParamIsZeroShouldReturnIntMax(){
service = new Cnt();
int answer = service.d(100,0);
assertEquals(Integer.MAX_VALUE, answer);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/error-prone-library/pmd/src/main/java/com/baeldung/pmd/Cnt.java | static-analysis-modules/error-prone-library/pmd/src/main/java/com/baeldung/pmd/Cnt.java | package com.baeldung.pmd;
public class Cnt {
public int d(int a, int b) {
if (b == 0)
return Integer.MAX_VALUE;
else
return a / b;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/error-prone-library/error-prone-project/src/main/java/com/baeldung/BuggyClass.java | static-analysis-modules/error-prone-library/error-prone-project/src/main/java/com/baeldung/BuggyClass.java | package com.baeldung;
public class BuggyClass {
public static void main(String[] args) {
if (args.length == 0 || args[0] != null) {
new IllegalArgumentException();
}
}
public void emptyMethod() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/error-prone-library/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java | static-analysis-modules/error-prone-library/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java | package com.baeldung;
public class ClassWithEmptyMethod {
public void theEmptyMethod() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/infer/src/main/java/com/baeldung/infer/NullPointerDereference.java | static-analysis-modules/infer/src/main/java/com/baeldung/infer/NullPointerDereference.java | package com.baeldung.infer;
public class NullPointerDereference {
public static void main(String[] args) {
NullPointerDereference.nullPointerDereference();
}
private static void nullPointerDereference() {
String str = null;
int length = str.length();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/infer/src/main/java/com/baeldung/infer/ResourceLeak.java | static-analysis-modules/infer/src/main/java/com/baeldung/infer/ResourceLeak.java | package com.baeldung.infer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ResourceLeak {
public static void main(String[] args) throws IOException {
ResourceLeak.resourceLeak();
}
private static void resourceLeak() throws IOException {
FileOutputStream stream;
try {
File file = new File("randomName.txt");
stream = new FileOutputStream(file);
} catch (IOException e) {
return;
}
stream.write(0);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/infer/src/main/java/com/baeldung/infer/DivideByZero.java | static-analysis-modules/infer/src/main/java/com/baeldung/infer/DivideByZero.java | package com.baeldung.infer;
public class DivideByZero {
public static void main(String[] args) {
DivideByZero.divideByZero();
}
private static void divideByZero() {
int dividend = 5;
int divisor = 0;
int result = dividend / divisor;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/static-analysis-modules/jspecify-nullsafety/src/test/java/com/baeldung/jspecify/JspecifyNullSafetyTest.java | static-analysis-modules/jspecify-nullsafety/src/test/java/com/baeldung/jspecify/JspecifyNullSafetyTest.java | package com.baeldung.jspecify;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Objects;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
public class JspecifyNullSafetyTest {
@Test
void givenKnownUserId_whenFindNickname_thenReturnsOptionalWithValue() {
Optional<String> nickname = findNickname("user123");
assertTrue(nickname.isPresent());
assertEquals("CoolUser", nickname.get());
}
@Test
void givenUnknownUserId_whenFindNickname_thenReturnsEmptyOptional() {
Optional<String> nickname = findNickname("unknownUser");
assertTrue(nickname.isEmpty());
}
@Test
void givenNonNullArgument_whenValidate_thenDoesNotThrowException() {
String result = processNickname("CoolUser");
assertEquals("Processed: CoolUser", result);
}
@Test
void givenNullArgument_whenValidate_thenThrowsNullPointerException() {
assertThrows(NullPointerException.class, () -> processNickname(null));
}
@Test
void givenUnknownUserId_whenFindNicknameOrNull_thenReturnsNull() {
String nickname = findNicknameOrNull("unknownUser");
assertNull(nickname);
}
@Test
void givenNullableMethodResult_whenWrappedInOptional_thenHandledSafely() {
String nickname = findNicknameOrNull("unknownUser");
Optional<String> safeNickname = Optional.ofNullable(nickname);
assertTrue(safeNickname.isEmpty());
}
private Optional<String> findNickname(String userId) {
if ("user123".equals(userId)) {
return Optional.of("CoolUser");
} else {
return Optional.empty();
}
}
@Nullable
private String findNicknameOrNull(String userId) {
if ("user123".equals(userId)) {
return "CoolUser";
} else {
return null;
}
}
private String processNickname(String nickname) {
Objects.requireNonNull(nickname, "Nickname must not be null");
return "Processed: " + nickname;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/test/java/com/baeldung/orika/OrikaUnitTest.java | orika/src/test/java/com/baeldung/orika/OrikaUnitTest.java | package com.baeldung.orika;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import ma.glasnost.orika.BoundMapperFacade;
import ma.glasnost.orika.CustomMapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
public class OrikaUnitTest {
MapperFactory mapperFactory;
CustomMapper<Personne3, Person3> customMapper;
// constant to help us cover time zone differences
private final long GMT_DIFFERENCE = 46800000;
//
@Before
public void before() {
mapperFactory = new DefaultMapperFactory.Builder().build();
customMapper = new PersonCustomMapper();
}
@Test
public void givenSrcAndDest_whenMaps_thenCorrect() {
mapperFactory.classMap(Source.class, Dest.class);
MapperFacade mapper = mapperFactory.getMapperFacade();
Source src = new Source("Baeldung", 10);
Dest dest = mapper.map(src, Dest.class);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDest_whenMapsReverse_thenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).byDefault();
MapperFacade mapper = mapperFactory.getMapperFacade();
Dest src = new Dest("Baeldung", 10);
Source dest = mapper.map(src, Source.class);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDest_whenMapsByObject_thenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).byDefault();
MapperFacade mapper = mapperFactory.getMapperFacade();
Source src = new Source("Baeldung", 10);
Dest dest = new Dest();
mapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDest_whenMapsUsingBoundMapper_thenCorrect() {
BoundMapperFacade<Source, Dest> boundMapper = mapperFactory.getMapperFacade(Source.class, Dest.class);
Source src = new Source("baeldung", 10);
Dest dest = boundMapper.map(src);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDest_whenMapsUsingBoundMapperInReverse_thenCorrect() {
BoundMapperFacade<Source, Dest> boundMapper = mapperFactory.getMapperFacade(Source.class, Dest.class);
Dest src = new Dest("baeldung", 10);
Source dest = boundMapper.mapReverse(src);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDest_whenMapsUsingBoundMapperByObject_thenCorrect() {
BoundMapperFacade<Source, Dest> boundMapper = mapperFactory.getMapperFacade(Source.class, Dest.class);
Source src = new Source("baeldung", 10);
Dest dest = new Dest();
boundMapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDest_whenMapsUsingBoundMapperByObjectInReverse_thenCorrect() {
BoundMapperFacade<Source, Dest> boundMapper = mapperFactory.getMapperFacade(Source.class, Dest.class);
Dest src = new Dest("baeldung", 10);
Source dest = new Source();
boundMapper.mapReverse(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcAndDestWithDifferentFieldNames_whenMaps_thenCorrect() {
mapperFactory.classMap(Personne.class, Person.class).field("nom", "name").field("surnom", "nickname").field("age", "age").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Personne frenchPerson = new Personne("Claire", "cla", 25);
Person englishPerson = mapper.map(frenchPerson, Person.class);
assertEquals(englishPerson.getName(), frenchPerson.getNom());
assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom());
assertEquals(englishPerson.getAge(), frenchPerson.getAge());
}
@Test
public void givenBothDifferentAndSameFieldNames_whenFailsToMapSameNameFieldAutomatically_thenCorrect() {
mapperFactory.classMap(Personne.class, Person.class).field("nom", "name").field("surnom", "nickname").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Personne frenchPerson = new Personne("Claire", "cla", 25);
Person englishPerson = mapper.map(frenchPerson, Person.class);
assertFalse(englishPerson.getAge() == frenchPerson.getAge());
}
@Test
public void givenBothDifferentAndSameFieldNames_whenMapsSameNameFieldByDefault_thenCorrect() {
mapperFactory.classMap(Personne.class, Person.class).field("nom", "name").field("surnom", "nickname").byDefault().register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Personne frenchPerson = new Personne("Claire", "cla", 25);
Person englishPerson = mapper.map(frenchPerson, Person.class);
assertEquals(englishPerson.getName(), frenchPerson.getNom());
assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom());
assertEquals(englishPerson.getAge(), frenchPerson.getAge());
}
@Test
public void givenUnidirectionalMappingSetup_whenMapsUnidirectionally_thenCorrect() {
mapperFactory.classMap(Personne.class, Person.class).fieldAToB("nom", "name").fieldAToB("surnom", "nickname").fieldAToB("age", "age").register();
;
MapperFacade mapper = mapperFactory.getMapperFacade();
Personne frenchPerson = new Personne("Claire", "cla", 25);
Person englishPerson = mapper.map(frenchPerson, Person.class);
assertEquals(englishPerson.getName(), frenchPerson.getNom());
assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom());
assertEquals(englishPerson.getAge(), frenchPerson.getAge());
}
@Test
public void givenSrcAndDest_whenCanExcludeField_thenCorrect() {
mapperFactory.classMap(Personne.class, Person.class).exclude("nom").field("surnom", "nickname").field("age", "age").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Personne frenchPerson = new Personne("Claire", "cla", 25);
Person englishPerson = mapper.map(frenchPerson, Person.class);
assertEquals(null, englishPerson.getName());
assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom());
assertEquals(englishPerson.getAge(), frenchPerson.getAge());
}
@Test
public void givenSpecificConstructorToUse_whenMaps_thenCorrect() {
mapperFactory.classMap(Personne.class, Person.class).constructorB().field("nom", "name").field("surnom", "nickname").field("age", "age").register();
;
MapperFacade mapper = mapperFactory.getMapperFacade();
Personne frenchPerson = new Personne("Claire", "cla", 25);
Person englishPerson = mapper.map(frenchPerson, Person.class);
assertEquals(englishPerson.getName(), frenchPerson.getNom());
assertEquals(englishPerson.getNickname(), frenchPerson.getSurnom());
assertEquals(englishPerson.getAge(), frenchPerson.getAge());
}
@Test
public void givenSrcWithListAndDestWithPrimitiveAttributes_whenMaps_thenCorrect() {
mapperFactory.classMap(PersonNameList.class, PersonNameParts.class).field("nameList[0]", "firstName").field("nameList[1]", "lastName").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
List<String> nameList = Arrays.asList(new String[] { "Sylvester", "Stallone" });
PersonNameList src = new PersonNameList(nameList);
PersonNameParts dest = mapper.map(src, PersonNameParts.class);
assertEquals(dest.getFirstName(), "Sylvester");
assertEquals(dest.getLastName(), "Stallone");
}
@Test
public void givenSrcWithArrayAndDestWithPrimitiveAttributes_whenMaps_thenCorrect() {
mapperFactory.classMap(PersonNameArray.class, PersonNameParts.class).field("nameArray[0]", "firstName").field("nameArray[1]", "lastName").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
String[] nameArray = new String[] { "Vin", "Diesel" };
PersonNameArray src = new PersonNameArray(nameArray);
PersonNameParts dest = mapper.map(src, PersonNameParts.class);
assertEquals(dest.getFirstName(), "Vin");
assertEquals(dest.getLastName(), "Diesel");
}
@Test
public void givenSrcWithMapAndDestWithPrimitiveAttributes_whenMaps_thenCorrect() {
mapperFactory.classMap(PersonNameMap.class, PersonNameParts.class).field("nameMap['first']", "firstName").field("nameMap[\"last\"]", "lastName").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Map<String, String> nameMap = new HashMap<>();
nameMap.put("first", "Leornado");
nameMap.put("last", "DiCaprio");
PersonNameMap src = new PersonNameMap(nameMap);
PersonNameParts dest = mapper.map(src, PersonNameParts.class);
assertEquals(dest.getFirstName(), "Leornado");
assertEquals(dest.getLastName(), "DiCaprio");
}
@Test
public void givenSrcWithNestedFields_whenMaps_thenCorrect() {
mapperFactory.classMap(PersonContainer.class, PersonNameParts.class).field("name.firstName", "firstName").field("name.lastName", "lastName").register();
MapperFacade mapper = mapperFactory.getMapperFacade();
PersonContainer src = new PersonContainer(new Name("Nick", "Canon"));
PersonNameParts dest = mapper.map(src, PersonNameParts.class);
assertEquals(dest.getFirstName(), "Nick");
assertEquals(dest.getLastName(), "Canon");
}
@Test
public void givenSrcWithNullField_whenMapsThenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).byDefault();
MapperFacade mapper = mapperFactory.getMapperFacade();
Source src = new Source(null, 10);
Dest dest = mapper.map(src, Dest.class);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenSrcWithNullAndGlobalConfigForNoNull_whenFailsToMap_ThenCorrect() {
MapperFactory mapperFactory = new DefaultMapperFactory.Builder().mapNulls(false).build();
mapperFactory.classMap(Source.class, Dest.class);
MapperFacade mapper = mapperFactory.getMapperFacade();
Source src = new Source(null, 10);
Dest dest = new Dest("Clinton", 55);
mapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), "Clinton");
}
@Test
public void givenSrcWithNullAndLocalConfigForNoNull_whenFailsToMap_ThenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).field("age", "age").mapNulls(false).field("name", "name").byDefault().register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Source src = new Source(null, 10);
Dest dest = new Dest("Clinton", 55);
mapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), "Clinton");
}
@Test
public void givenDestWithNullReverseMappedToSource_whenMapsByDefault_thenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).byDefault();
MapperFacade mapper = mapperFactory.getMapperFacade();
Dest src = new Dest(null, 10);
Source dest = new Source("Vin", 44);
mapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), src.getName());
}
@Test
public void givenDestWithNullReverseMappedToSourceAndLocalConfigForNoNull_whenFailsToMap_thenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).field("age", "age").mapNullsInReverse(false).field("name", "name").byDefault().register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Dest src = new Dest(null, 10);
Source dest = new Source("Vin", 44);
mapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), "Vin");
}
@Test
public void givenSrcWithNullAndFieldLevelConfigForNoNull_whenFailsToMap_ThenCorrect() {
mapperFactory.classMap(Source.class, Dest.class).field("age", "age").fieldMap("name", "name").mapNulls(false).add().byDefault().register();
MapperFacade mapper = mapperFactory.getMapperFacade();
Source src = new Source(null, 10);
Dest dest = new Dest("Clinton", 55);
mapper.map(src, dest);
assertEquals(dest.getAge(), src.getAge());
assertEquals(dest.getName(), "Clinton");
}
@Test
public void givenSrcAndDest_whenCustomMapperWorks_thenCorrect() {
mapperFactory.classMap(Personne3.class, Person3.class).customize(customMapper).register();
MapperFacade mapper = mapperFactory.getMapperFacade();
long timestamp = Long.valueOf("1182882159000");
Personne3 personne3 = new Personne3("Leornardo", timestamp);
Person3 person3 = mapper.map(personne3, Person3.class);
String timestampTest = person3.getDtob();
// since different timezones will resolve the timestamp to a different
// datetime string, it suffices to check only for format rather than
// specific date
assertTrue(timestampTest.charAt(10) == 'T' && timestampTest.charAt(19) == 'Z');
}
@Test
public void givenSrcAndDest_whenCustomMapperWorksBidirectionally_thenCorrect() {
mapperFactory.classMap(Personne3.class, Person3.class).customize(customMapper).register();
MapperFacade mapper = mapperFactory.getMapperFacade();
String dateTime = "2007-06-26T21:22:39Z";
long timestamp = Long.valueOf("1182882159000");
Person3 person3 = new Person3("Leornardo", dateTime);
Personne3 personne3 = mapper.map(person3, Personne3.class);
long timestampToTest = personne3.getDtob();
/*
* since different timezones will resolve the datetime to a different
* unix timestamp, we must provide a range of tolerance
*/
assertTrue(timestampToTest == timestamp || timestampToTest >= timestamp - GMT_DIFFERENCE || timestampToTest <= timestamp + GMT_DIFFERENCE);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonNameMap.java | orika/src/main/java/com/baeldung/orika/PersonNameMap.java | package com.baeldung.orika;
import java.util.Map;
public class PersonNameMap {
private Map<String, String> nameMap;
public PersonNameMap(Map<String, String> nameMap) {
this.nameMap = nameMap;
}
public Map<String, String> getNameMap() {
return nameMap;
}
public void setNameMap(Map<String, String> nameList) {
this.nameMap = nameList;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Personne.java | orika/src/main/java/com/baeldung/orika/Personne.java | package com.baeldung.orika;
public class Personne {
private String nom;
private String surnom;
private int age;
public Personne(String nom, String surnom, int age) {
this.nom = nom;
this.surnom = surnom;
this.age = age;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getSurnom() {
return surnom;
}
public void setSurnom(String surnom) {
this.surnom = surnom;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Personne [nom=" + nom + ", surnom=" + surnom + ", age=" + age
+ "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonContainer.java | orika/src/main/java/com/baeldung/orika/PersonContainer.java | package com.baeldung.orika;
public class PersonContainer {
private Name name;
public PersonContainer(Name name) {
this.name = name;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Person.java | orika/src/main/java/com/baeldung/orika/Person.java | package com.baeldung.orika;
public class Person {
@Override
public String toString() {
return "Person [name=" + name + ", nickname=" + nickname + ", age="
+ age + "]";
}
private String name;
private String nickname;
private int age;
public Person() {
}
public Person(String name, String nickname, int age) {
this.name = name;
this.nickname = nickname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Dest.java | orika/src/main/java/com/baeldung/orika/Dest.java | package com.baeldung.orika;
public class Dest {
@Override
public String toString() {
return "Dest [name=" + name + ", age=" + age + "]";
}
private String name;
private int age;
public Dest() {
}
public Dest(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonCustomMapper.java | orika/src/main/java/com/baeldung/orika/PersonCustomMapper.java | package com.baeldung.orika;
import ma.glasnost.orika.CustomMapper;
import ma.glasnost.orika.MappingContext;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class PersonCustomMapper extends CustomMapper<Personne3, Person3> {
@Override
public void mapAtoB(Personne3 a, Person3 b, MappingContext context) {
Date date = new Date(a.getDtob());
DateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
String isoDate = format.format(date);
b.setDtob(isoDate);
}
@Override
public void mapBtoA(Person3 b, Personne3 a, MappingContext context) {
DateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = format.parse(b.getDtob());
} catch (ParseException e) {
e.printStackTrace();
}
long timestamp = date.getTime();
a.setDtob(timestamp);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonNameList.java | orika/src/main/java/com/baeldung/orika/PersonNameList.java | package com.baeldung.orika;
import java.util.List;
public class PersonNameList {
private List<String> nameList;
public PersonNameList(List<String> nameList) {
this.nameList = nameList;
}
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Person3.java | orika/src/main/java/com/baeldung/orika/Person3.java | package com.baeldung.orika;
public class Person3 {
private String name;
private String dtob;
public Person3() {
}
public Person3(String name, String dtob) {
this.name = name;
this.dtob = dtob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDtob() {
return dtob;
}
public void setDtob(String dtob) {
this.dtob = dtob;
}
@Override
public String toString() {
return "Person3 [name=" + name + ", dtob=" + dtob + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonListContainer.java | orika/src/main/java/com/baeldung/orika/PersonListContainer.java | package com.baeldung.orika;
import java.util.List;
public class PersonListContainer {
private List<Name> names;
public PersonListContainer(List<Name> names) {
this.names = names;
}
public List<Name> getNames() {
return names;
}
public void setNames(List<Name> names) {
this.names = names;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Name.java | orika/src/main/java/com/baeldung/orika/Name.java | package com.baeldung.orika;
public class Name {
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonNameParts.java | orika/src/main/java/com/baeldung/orika/PersonNameParts.java | package com.baeldung.orika;
public class PersonNameParts {
private String firstName;
private String lastName;
public PersonNameParts(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/PersonNameArray.java | orika/src/main/java/com/baeldung/orika/PersonNameArray.java | package com.baeldung.orika;
public class PersonNameArray {
private String[] nameArray;
public PersonNameArray(String[] nameArray) {
this.nameArray = nameArray;
}
public String[] getNameArray() {
return nameArray;
}
public void setNameArray(String[] nameArray) {
this.nameArray = nameArray;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Personne3.java | orika/src/main/java/com/baeldung/orika/Personne3.java | package com.baeldung.orika;
public class Personne3 {
private String name;
private long dtob;
public Personne3() {
}
public Personne3(String name, long dtob) {
this.name = name;
this.dtob = dtob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getDtob() {
return dtob;
}
public void setDtob(long dtob) {
this.dtob = dtob;
}
@Override
public String toString() {
return "Personne3 [name=" + name + ", dtob=" + dtob + "]";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/orika/src/main/java/com/baeldung/orika/Source.java | orika/src/main/java/com/baeldung/orika/Source.java | package com.baeldung.orika;
public class Source {
@Override
public String toString() {
return "Source [name=" + name + ", age=" + age + "]";
}
private String name;
private int age;
public Source() {
}
public Source(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java | libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/CommonsIOUnitTest.java | package com.baeldung.commons.io;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.PathFileComparator;
import org.apache.commons.io.comparator.SizeFileComparator;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CommonsIOUnitTest {
@Test
public void whenCopyANDReadFileTesttxt_thenMatchExpectedData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
File file = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
File tempDir = FileUtils.getTempDirectory();
FileUtils.copyFileToDirectory(file, tempDir);
File newTempFile = FileUtils.getFile(tempDir, file.getName());
String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
Assert.assertEquals(expectedData, data.trim());
}
@Test
public void whenUsingFileNameUtils_thenshowdifferentFileOperations() throws IOException {
String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
String fullPath = FilenameUtils.getFullPath(path);
String extension = FilenameUtils.getExtension(path);
String baseName = FilenameUtils.getBaseName(path);
log.debug("full path: " + fullPath);
log.debug("Extension: " + extension);
log.debug("Base name: " + baseName);
}
@Test
public void whenUsingFileSystemUtils_thenDriveFreeSpace() throws IOException {
long freeSpace = FileSystemUtils.freeSpaceKb("/");
}
@SuppressWarnings("resource")
@Test
public void whenUsingTeeInputOutputStream_thenWriteto2OutputStreams() throws IOException {
final String str = "Hello World.";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);
Assert.assertEquals(str, String.valueOf(outputStream1));
Assert.assertEquals(str, String.valueOf(outputStream2));
}
@Test
public void whenGetFilewithNameFileFilter_thenFindfileTesttxt() throws IOException {
final String testFile = "fileTest.txt";
String path = getClass().getClassLoader().getResource(testFile).getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
String[] possibleNames = { "NotThisOne", testFile };
Assert.assertEquals(testFile, dir.list(new NameFileFilter(possibleNames, IOCase.INSENSITIVE))[0]);
}
@Test
public void whenGetFilewith_ANDFileFilter_thenFindsampletxt() throws IOException {
String path = getClass().getClassLoader().getResource("fileTest.txt").getPath();
File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));
Assert.assertEquals("sample.txt", dir.list(new AndFileFilter(new WildcardFileFilter("*ple*", IOCase.INSENSITIVE), new SuffixFileFilter("txt")))[0]);
}
@Test
public void whenSortDirWithPathFileComparator_thenFirstFileaaatxt() throws IOException {
PathFileComparator pathFileComparator = new PathFileComparator(IOCase.INSENSITIVE);
String path = FilenameUtils.getFullPath(getClass().getClassLoader().getResource("fileTest.txt").getPath());
File dir = new File(path);
File[] files = dir.listFiles();
pathFileComparator.sort(files);
Assert.assertEquals("aaa.txt", files[0].getName());
}
@Test
public void whenSizeFileComparator_thenLargerFile() throws IOException {
SizeFileComparator sizeFileComparator = new SizeFileComparator();
File largerFile = FileUtils.getFile(getClass().getClassLoader().getResource("fileTest.txt").getPath());
File smallerFile = FileUtils.getFile(getClass().getClassLoader().getResource("sample.txt").getPath());
int i = sizeFileComparator.compare(largerFile, smallerFile);
Assert.assertTrue(i > 0);
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java | libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java | package com.baeldung.commons.io.csv;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
class CSVReaderWriterUnitTest {
public static final Map<String, String> AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap<String, String>() {
{
put("Dan Simmons", "Hyperion");
put("Douglas Adams", "The Hitchhiker's Guide to the Galaxy");
}
});
public static final String[] HEADERS = { "author", "title" };
enum BookHeaders{
author, title
}
public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy";
@Test
void givenCSVFile_whenReadWithArrayHeader_thenContentsAsExpected() throws IOException {
Reader in = new FileReader("src/test/resources/book.csv");
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(HEADERS)
.setSkipHeaderRecord(true)
.build();
Iterable<CSVRecord> records = csvFormat.parse(in);
for (CSVRecord record : records) {
String author = record.get("author");
String title = record.get("title");
assertEquals(AUTHOR_BOOK_MAP.get(author), title);
}
}
@Test
void givenCSVFile_whenReadWithEnumHeader_thenContentsAsExpected() throws IOException {
Reader in = new FileReader("src/test/resources/book.csv");
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(BookHeaders.class)
.setSkipHeaderRecord(true)
.build();
Iterable<CSVRecord> records = csvFormat.parse(in);
for (CSVRecord record : records) {
String author = record.get(BookHeaders.author);
String title = record.get(BookHeaders.title);
assertEquals(AUTHOR_BOOK_MAP.get(author), title);
}
}
@Test
void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException {
StringWriter sw = new StringWriter();
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(BookHeaders.class)
.build();
try (final CSVPrinter printer = new CSVPrinter(sw, csvFormat)) {
AUTHOR_BOOK_MAP.forEach((author, title) -> {
try {
printer.printRecord(author, title);
} catch (IOException e) {
e.printStackTrace();
}
});
}
assertEquals(EXPECTED_FILESTREAM, sw.toString()
.trim());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/libraries-apache-commons-io/src/main/java/com/baeldung/commons/io/FileMonitor.java | libraries-apache-commons-io/src/main/java/com/baeldung/commons/io/FileMonitor.java | package com.baeldung.commons.io;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileMonitor {
public static void main(String[] args) throws Exception {
File folder = FileUtils.getTempDirectory();
startFileMonitor(folder);
}
/**
* @param folder
* @throws Exception
*/
public static void startFileMonitor(File folder) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
// on create action
}
@Override
public void onFileDelete(File file) {
// on delete action
}
};
observer.addListener(fal);
monitor.addObserver(observer);
monitor.start();
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/java-nashorn/src/test/java/com/baeldung/language/interop/javascript/NashornUnitTest.java | java-nashorn/src/test/java/com/baeldung/language/interop/javascript/NashornUnitTest.java | package com.baeldung.language.interop.javascript;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.script.*;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
public class NashornUnitTest {
private ScriptEngine engine;
@Before
public void setUp() {
engine = new ScriptEngineManager().getEngineByName("nashorn");
}
@Test
public void trim() throws ScriptException {
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/trim.js")));
}
@Test
public void locations() throws ScriptException {
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/locations.js")));
}
@Test
public void bindProperties() throws ScriptException {
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/bind.js")));
}
@Test
public void magicMethods() throws ScriptException {
engine.eval("var demo = load('classpath:js/no_such.js');" + "var tmp = demo.doesNotExist;" + "var none = demo.callNonExistingMethod()");
}
@Test
public void typedArrays() throws ScriptException {
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/typed_arrays.js")));
}
@Test
public void basicUsage() throws ScriptException {
Object result = engine.eval("var greeting='hello world';" + "print(greeting);" + "greeting");
Assert.assertEquals("hello world", result);
}
@Test
public void jsonObjectExample() throws ScriptException {
Object obj = engine.eval("Java.asJSONCompatible({ number: 42, greet: 'hello', primes: [2,3,5,7,11,13] })");
Map<String, Object> map = (Map<String, Object>) obj;
Assert.assertEquals("hello", map.get("greet"));
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
}
@Test
public void tryCatchGuard() throws ScriptException {
engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.failFunc();");
}
@Test
public void extensionsExamples() throws ScriptException {
String script = "var list = [1, 2, 3, 4, 5];" + "var result = '';" + "for each (var i in list) {" + "result+=i+'-';" + "};" + "print(result);";
engine.eval(script);
}
@Test
public void bindingsExamples() throws ScriptException {
Bindings bindings = engine.createBindings();
bindings.put("count", 3);
bindings.put("name", "baeldung");
String script = "var greeting='Hello ';" + "for(var i=count;i>0;i--) { " + "greeting+=name + ' '" + "}" + "greeting";
Object bindingsResult = engine.eval(script, bindings);
Assert.assertEquals("Hello baeldung baeldung baeldung ", bindingsResult);
}
@Test
public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException {
engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}");
Invocable invocable = (Invocable) engine;
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
Assert.assertEquals("Hello baeldung", funcResult);
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map");
Assert.assertTrue(Map.class.isAssignableFrom(map.getClass()));
}
@Test
public void loadExamples() throws ScriptException {
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
Assert.assertEquals(6, ((Double) loadResult).intValue());
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
Assert.assertEquals(6.0, math);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/java-nashorn/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java | java-nashorn/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java | package com.baeldung.language.interop.python;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ScriptEngineManagerUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ScriptEngineManagerUtils.class);
private ScriptEngineManagerUtils() {
}
public static void listEngines() {
ScriptEngineManager manager = new ScriptEngineManager();
List<ScriptEngineFactory> engines = manager.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
LOGGER.info("Engine name: {}", engine.getEngineName());
LOGGER.info("Version: {}", engine.getEngineVersion());
LOGGER.info("Language: {}", engine.getLanguageName());
LOGGER.info("Short Names:");
for (String names : engine.getNames()) {
LOGGER.info(names);
}
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-kafka-3/src/test/java/com/baeldung/kafka/KafkaCountPartitionsLiveTest.java | apache-kafka-3/src/test/java/com/baeldung/kafka/KafkaCountPartitionsLiveTest.java | package com.baeldung.kafka;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.DescribeTopicsResult;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
@Testcontainers
public class KafkaCountPartitionsLiveTest {
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
private final static String TOPIC = "baeldung-kafka-github";
private final static Integer PARTITION_NUMBER = 3;
private static KafkaProducer<String, String> producer;
@BeforeAll
static void setup() throws IOException, InterruptedException {
KAFKA_CONTAINER.addExposedPort(9092);
KAFKA_CONTAINER.execInContainer(
"/bin/sh",
"-c",
"/usr/bin/kafka-topics " +
"--bootstrap-server localhost:9092 " +
"--create " +
"--replication-factor 1 " +
"--partitions " + PARTITION_NUMBER + " " +
"--topic " + TOPIC
);
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producer = new KafkaProducer<>(producerProperties);
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void testPartitionsForTopic_isEqualToActualNumberAssignedDuringCreation() {
List<PartitionInfo> info = producer.partitionsFor(TOPIC);
Assertions.assertEquals(PARTITION_NUMBER, info.size());
}
@Test
void testTopicPartitionDescription_isEqualToActualNumberAssignedDuringCreation() {
Properties props = new Properties();
props.put("bootstrap.servers", KAFKA_CONTAINER.getBootstrapServers());
props.put("client.id","java-admin-client");
props.put("request.timeout.ms", 3000);
props.put("connections.max.idle.ms", 5000);
try(AdminClient client = AdminClient.create(props)){
DescribeTopicsResult describeTopicsResult = client.describeTopics(Collections.singletonList(TOPIC));
Map<String, KafkaFuture<TopicDescription>> values = describeTopicsResult.values();
KafkaFuture<TopicDescription> topicDescription = values.get(TOPIC);
Assertions.assertEquals(PARTITION_NUMBER, topicDescription.get().partitions().size());
} catch (ExecutionException | InterruptedException 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-kafka-3/src/test/java/com/baeldung/kafka/KafkaProducerRetriesLiveTest.java | apache-kafka-3/src/test/java/com/baeldung/kafka/KafkaProducerRetriesLiveTest.java | package com.baeldung.kafka;
import static java.util.Collections.singleton;
import static org.apache.kafka.clients.producer.ProducerConfig.BOOTSTRAP_SERVERS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.RETRIES_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.RETRY_BACKOFF_MS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
@Testcontainers
class KafkaProducerRetriesLiveTest {
static AdminClient adminClient;
@Container
static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(
DockerImageName.parse("confluentinc/cp-kafka:latest"));
@BeforeAll
static void beforeAll() {
Properties props = new Properties();
props.put("bootstrap.servers", KAFKA_CONTAINER.getBootstrapServers());
adminClient = AdminClient.create(props);
}
@Test
void givenDefaultConfig_whenMessageCannotBeSent_thenKafkaProducerRetries() throws Exception {
NewTopic newTopic = new NewTopic("test-topic-1", 1, (short) 1)
.configs(mapOf("min.insync.replicas", "2"));
adminClient.createTopics(singleton(newTopic)).all().get();
Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
props.put(KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
ProducerRecord<String, String> record = new ProducerRecord<>("test-topic-1", "test-value");
assertThatThrownBy(() -> producer.send(record)
.get()).isInstanceOf(ExecutionException.class)
.hasCauseInstanceOf(org.apache.kafka.common.errors.TimeoutException.class)
.hasMessageContaining("Expiring 1 record(s) for test-topic-1-0");
}
@Test
void givenCustomConfig_whenMessageCannotBeSent_thenKafkaProducerRetries() throws Exception {
NewTopic newTopic = new NewTopic("test-topic-2", 1, (short) 1)
.configs(mapOf("min.insync.replicas", "2"));
adminClient.createTopics(singleton(newTopic)).all().get();
Properties props = new Properties();
props.put(BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
props.put(KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(REQUEST_TIMEOUT_MS_CONFIG, "5000");
props.put(RETRIES_CONFIG, 20);
props.put(RETRY_BACKOFF_MS_CONFIG, "500");
props.put(DELIVERY_TIMEOUT_MS_CONFIG, "5000");
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
ProducerRecord<String, String> record = new ProducerRecord<>("test-topic-2", "test-value");
assertThatThrownBy(() -> producer.send(record).get())
.isInstanceOf(ExecutionException.class)
.hasCauseInstanceOf(org.apache.kafka.common.errors.TimeoutException.class)
.hasMessageContaining("Expiring 1 record(s) for test-topic-2-0");
}
static Map<String, String> mapOf(String key, String value) {
return new HashMap<String, String>() {{
put(key, value);
}};
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-kafka-3/src/test/java/com/baeldung/kafka/KafaProducerConsumerAckOptsLiveTest.java | apache-kafka-3/src/test/java/com/baeldung/kafka/KafaProducerConsumerAckOptsLiveTest.java | package com.baeldung.kafka;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
@Testcontainers
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class KafaProducerConsumerAckOptsLiveTest {
private static final String CONSUMER_GROUP_ID = "ConsumerGroup1";
private static final long INVALID_OFFSET = -1;
private static final String TOPIC = "baeldung-kafka-github";
private static final String MESSAGE_KEY = "message";
private static final String TEST_MESSAGE = "Kafka Test Message";
private static final Integer PARTITION_NUMBER = 3;
static KafkaProducer<String, String> producerack0;
static KafkaProducer<String, String> producerack1;
static KafkaProducer<String, String> producerackAll;
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka"));
@BeforeAll
static void setUp() throws IOException, InterruptedException {
KAFKA_CONTAINER.addExposedPort(9092);
KAFKA_CONTAINER.execInContainer("/bin/sh", "-c", "/usr/bin/kafka-topics " + "--bootstrap-server localhost:9092 " + "--create " +
"--replication-factor 1 " + "--partitions " + PARTITION_NUMBER + " " + "--topic " + TOPIC);
KAFKA_CONTAINER.start();
Properties producerProperties = getProducerProperties();
producerProperties.put(ProducerConfig.ACKS_CONFIG, "0");
producerack0 = new KafkaProducer<>(producerProperties);
Properties producerack1Prop = getProducerProperties();
producerack1Prop.put(ProducerConfig.ACKS_CONFIG, "1");
producerack1 = new KafkaProducer<>(producerack1Prop);
Properties producerackAllProp = getProducerProperties();
producerackAllProp.put(ProducerConfig.ACKS_CONFIG, "all");
producerackAll = new KafkaProducer<>(producerackAllProp);
}
static Properties getProducerProperties() {
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.RETRIES_CONFIG, 0);
producerProperties.put(ProducerConfig.BATCH_SIZE_CONFIG, 1000);
producerProperties.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 10000);
producerProperties.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 300);
producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, 10);
producerProperties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
producerProperties.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 5000);
return producerProperties;
}
static Properties getConsumerProperties() {
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_GROUP_ID);
return consumerProperties;
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
@Order(1)
void givenProducerAck0_whenProducerSendsRecord_thenDoesNotReturnOffset() throws ExecutionException, InterruptedException {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 0, MESSAGE_KEY, TEST_MESSAGE + "_0");
for (int i = 0; i < 50; i++) {
RecordMetadata metadata = producerack0.send(record)
.get();
assertEquals(INVALID_OFFSET, metadata.offset());
}
}
@Test
@Order(2)
void givenProducerAck1_whenProducerSendsRecord_thenReturnsValidOffset() throws ExecutionException, InterruptedException {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 1, MESSAGE_KEY, TEST_MESSAGE + "_1");
for (int i = 0; i < 50; i++) {
RecordMetadata metadata = producerack1.send(record)
.get();
assertNotEquals(INVALID_OFFSET, metadata.offset());
}
}
@Test
@Order(3)
void givenProducerAckAll_whenProducerSendsRecord_thenReturnsValidOffset() throws ExecutionException, InterruptedException {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 2, MESSAGE_KEY, TEST_MESSAGE + "_ALL");
for (int i = 0; i < 50; i++) {
RecordMetadata metadata = producerackAll.send(record)
.get();
assertNotEquals(INVALID_OFFSET, metadata.offset());
}
}
@Test
@Order(4)
void whenSeekingKafkaResetConfigLatest_thenConsumerOffsetSetToLatestRecordOffset() {
Properties consumerProperties = getConsumerProperties();
consumerProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
long expectedStartOffset = 50;
long actualStartOffset;
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerProperties)) {
TopicPartition partition1 = new TopicPartition(TOPIC, 1);
List<TopicPartition> partitions = new ArrayList<>();
partitions.add(partition1);
consumer.assign(partitions);
actualStartOffset = consumer.position(partition1);
}
assertEquals(expectedStartOffset, actualStartOffset);
}
@Test
@Order(5)
void whenSeekingKafkaResetConfigEarliest_thenConsumerOffsetSetToZero() {
Properties consumerProperties = getConsumerProperties();
consumerProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
long expectedStartOffset = 0;
long actualStartOffset;
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerProperties)) {
TopicPartition partition2 = new TopicPartition(TOPIC, 2);
List<TopicPartition> partitions = new ArrayList<>();
partitions.add(partition2);
consumer.assign(partitions);
actualStartOffset = consumer.position(partition2);
}
assertEquals(expectedStartOffset, actualStartOffset);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-kafka-3/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java | apache-kafka-3/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java | package com.baeldung.kafka;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Testcontainers
public class KafaConsumeLastNMessagesLiveTest {
private static String TOPIC1 = "baeldung-github";
private static String TOPIC2 = "baeldung-blog";
private static String MESSAGE_KEY = "message";
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
private static KafkaProducer<String, String> transactionalProducer;
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
@BeforeAll
static void setup() {
KAFKA_CONTAINER.addExposedPort(9092);
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
Properties transactionalProducerProprieties = new Properties();
transactionalProducerProprieties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
transactionalProducerProprieties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
transactionalProducerProprieties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
transactionalProducerProprieties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
transactionalProducerProprieties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-0");
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
transactionalProducer = new KafkaProducer<>(transactionalProducerProprieties);
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void whenSeekingKafkaTopicCursorToEnd_consumerRetrievesOnlyDesiredNumberOfMessages() throws ExecutionException, InterruptedException {
int messagesInTopic = 100;
int messagesToRetrieve = 20;
for (int i = 0; i < messagesInTopic; i++) {
producer.send(new ProducerRecord<>(TOPIC1, null, MESSAGE_KEY, String.valueOf(i)))
.get();
}
TopicPartition partition = new TopicPartition(TOPIC1, 0);
List<TopicPartition> partitions = new ArrayList<>();
partitions.add(partition);
consumer.assign(partitions);
consumer.seekToEnd(partitions);
long startIndex = consumer.position(partition) - messagesToRetrieve;
consumer.seek(partition, startIndex);
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
int recordsReceived = 0;
for (ConsumerRecord<String, String> record : records) {
assertEquals(MESSAGE_KEY, record.key());
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
recordsReceived++;
}
assertEquals(messagesToRetrieve, recordsReceived);
}
@Test
void havingTransactionalProducer_whenSeekingKafkaTopicCursorToEnd_consumerRetrievesLessMessages() throws ExecutionException, InterruptedException {
int messagesInTopic = 100;
int messagesToRetrieve = 20;
transactionalProducer.initTransactions();
for (int i = 0; i < messagesInTopic; i++) {
transactionalProducer.beginTransaction();
transactionalProducer.send(new ProducerRecord<>(TOPIC2, null, MESSAGE_KEY, String.valueOf(i)))
.get();
transactionalProducer.commitTransaction();
}
TopicPartition partition = new TopicPartition(TOPIC2, 0);
List<TopicPartition> partitions = new ArrayList<>();
partitions.add(partition);
consumer.assign(partitions);
consumer.seekToEnd(partitions);
long startIndex = consumer.position(partition) - messagesToRetrieve;
consumer.seek(partition, startIndex);
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
int recordsReceived = 0;
for (ConsumerRecord<String, String> record : records) {
assertEquals(MESSAGE_KEY, record.key());
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
recordsReceived++;
}
assertTrue(messagesToRetrieve > recordsReceived);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-kafka-3/src/test/java/com/baeldung/kafka/KafkaProducerTimeOutExceptionTest.java | apache-kafka-3/src/test/java/com/baeldung/kafka/KafkaProducerTimeOutExceptionTest.java | package com.baeldung.kafka;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.FixMethodOrder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.runners.MethodSorters;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
@Testcontainers
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class KafkaProducerTimeOutExceptionTest {
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
private final static String TIMEOUT_EXCEPTION_CLASS = "org.apache.kafka.common.errors.TimeoutException";
private final static String TOPIC = "baeldung-kafka-github";
private static String MESSAGE_KEY = "message";
private final static String TEST_MESSAGE = "Kafka Test Message";
private final static Integer PARTITION_NUMBER = 3;
@BeforeAll
static void setup() throws IOException, InterruptedException {
KAFKA_CONTAINER.addExposedPort(9092);
KAFKA_CONTAINER.execInContainer("/bin/sh", "-c", "/usr/bin/kafka-topics " + "--bootstrap-server localhost:9092 " + "--create " +
"--replication-factor 1 " + "--partitions " + PARTITION_NUMBER + " " + "--topic " + TOPIC);
}
static Properties getProducerProperties() {
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.RETRIES_CONFIG, 0);
producerProperties.put(ProducerConfig.BATCH_SIZE_CONFIG, 1000);
producerProperties.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 400);
producerProperties.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 300);
producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, 10);
producerProperties.put(ProducerConfig.ACKS_CONFIG, "all");
producerProperties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
producerProperties.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 5000);
return producerProperties;
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void givenProducerConfigured_whenRecordSent_thenNoExceptionOccurs() throws InterruptedException, ExecutionException {
Properties producerProperties = getProducerProperties();
KafkaProducer<String, String> producer = new KafkaProducer<>(producerProperties);
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 1, MESSAGE_KEY, TEST_MESSAGE);
assertDoesNotThrow(() -> {
producer.send(record)
.get();
});
}
@Test
void givenProducerRequestTimeOutLow_whenRecordSent_thenTimeOutExceptionOccurs() throws InterruptedException, ExecutionException {
Properties producerProperties = getProducerProperties();
producerProperties.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 5);
producerProperties.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 1000);
KafkaProducer<String, String> producer = new KafkaProducer<>(producerProperties);
String exceptionName = "";
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 2, MESSAGE_KEY, TEST_MESSAGE);
Exception exception = assertThrows(Exception.class, () -> {
producer.send(record)
.get();
});
if (exception != null) {
exceptionName = exception.getCause()
.getClass()
.getCanonicalName();
}
producer.close();
assertThat(exceptionName)
.isEqualTo(TIMEOUT_EXCEPTION_CLASS);
}
@Test
void givenProducerLingerTimeIsLow_whenRecordSent_thenTimeOutExceptionOccurs() throws InterruptedException, ExecutionException {
Properties producerProperties = getProducerProperties();
producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, 0);
producerProperties.put(ProducerConfig.BATCH_SIZE_CONFIG, 1);
KafkaProducer<String, String> producer = new KafkaProducer<>(producerProperties);
String exceptionName = "";
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 3, MESSAGE_KEY, TEST_MESSAGE);
Exception exception = assertThrows(Exception.class, () -> {
producer.send(record)
.get();
});
if (exception != null) {
exceptionName = exception.getCause()
.getClass()
.getCanonicalName();
}
producer.close();
assertThat(exceptionName)
.isEqualTo(TIMEOUT_EXCEPTION_CLASS);
}
@Test
void givenProducerLargeBatchSize_whenRecordSent_thenTimeOutExceptionOccurs() throws InterruptedException, ExecutionException {
Properties producerProperties = getProducerProperties();
producerProperties.put(ProducerConfig.LINGER_MS_CONFIG, 5000);
producerProperties.put(ProducerConfig.BATCH_SIZE_CONFIG, 10000000);
producerProperties.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 5000);
producerProperties.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 10000);
KafkaProducer<String, String> producer = new KafkaProducer<>(producerProperties);
String exceptionName = "";
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC, 3, MESSAGE_KEY, TEST_MESSAGE);
Exception exception = assertThrows(Exception.class, () -> {
producer.send(record)
.get();
});
if (exception != null) {
exceptionName = exception.getCause()
.getClass()
.getCanonicalName();
}
producer.close();
assertThat(exceptionName)
.isEqualTo(TIMEOUT_EXCEPTION_CLASS);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaAddPartitionExample.java | apache-kafka-3/src/main/java/com/baeldung/kafka/KafkaAddPartitionExample.java | package com.baeldung.kafka;
import java.util.Collections;
import java.util.Properties;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewPartitions;
public class KafkaAddPartitionExample {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
try (AdminClient adminClient = AdminClient.create(props)) {
adminClient.createPartitions(Collections.singletonMap("my-topic", NewPartitions.increaseTo(3)))
.all()
.get();
} catch (Exception 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-kafka-3/src/main/java/com/baeldung/kafka/partitions/KafkaMultiplePartitionsDemo.java | apache-kafka-3/src/main/java/com/baeldung/kafka/partitions/KafkaMultiplePartitionsDemo.java | package com.baeldung.kafka.partitions;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KafkaMultiplePartitionsDemo {
private static final Logger logger = LoggerFactory.getLogger(KafkaMultiplePartitionsDemo.class);
private final KafkaProducer<String, String> producer;
private final String bootstrapServers;
public KafkaMultiplePartitionsDemo(String bootstrapServers) {
this.bootstrapServers = bootstrapServers;
this.producer = createProducer();
}
private KafkaProducer<String, String> createProducer() {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.ACKS_CONFIG, "all");
return new KafkaProducer<>(props);
}
public void sendMessagesWithKey() {
String key = "user-123";
for (int i = 0; i < 5; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>("user-events", key, "Event " + i);
producer.send(record, (metadata, exception) -> {
if (exception == null) {
logger.info("Key: {}, Partition: {}, Offset: {}", key, metadata.partition(), metadata.offset());
}
});
}
producer.flush();
}
public Map<Integer, Integer> sendMessagesWithoutKey() {
Map<Integer, Integer> partitionCounts = new HashMap<>();
for (int i = 0; i < 100; i++) {
ProducerRecord<String, String> record = new ProducerRecord<>("events", null, // no key
"Message " + i);
producer.send(record, (metadata, exception) -> {
if (exception == null) {
synchronized (partitionCounts) {
partitionCounts.merge(metadata.partition(), 1, Integer::sum);
}
}
});
}
producer.flush();
logger.info("Distribution across partitions: {}", partitionCounts);
return partitionCounts;
}
public void demonstratePartitionOrdering() throws InterruptedException {
String orderId = "order-789";
String[] events = { "created", "validated", "paid", "shipped", "delivered" };
for (String event : events) {
ProducerRecord<String, String> record = new ProducerRecord<>("orders", orderId, event);
producer.send(record, (metadata, exception) -> {
if (exception == null) {
logger.info("Event: {} -> Partition: {}, Offset: {}", event, metadata.partition(), metadata.offset());
}
});
// small delay to demonstrate sequential processing
Thread.sleep(100);
}
producer.flush();
}
public void demonstrateCrossPartitionBehavior() {
long startTime = System.currentTimeMillis();
// these will likely go to different partitions
producer.send(new ProducerRecord<>("events", "key-A", "First at " + (System.currentTimeMillis() - startTime) + "ms"));
producer.send(new ProducerRecord<>("events", "key-B", "Second at " + (System.currentTimeMillis() - startTime) + "ms"));
producer.send(new ProducerRecord<>("events", "key-C", "Third at " + (System.currentTimeMillis() - startTime) + "ms"));
producer.flush();
}
public void close() {
if (producer != null) {
producer.close();
}
}
public void createConsumerGroup() {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("group.id", "order-processors");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("auto.offset.reset", "earliest");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("orders"));
int recordCount = 0;
while (recordCount < 10) { // process limited records for demo
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
logger.info("Consumer: {}, Partition: {}, Offset: {}, Value: {}", Thread.currentThread()
.getName(), record.partition(), record.offset(), record.value());
recordCount++;
}
consumer.commitSync();
}
consumer.close();
}
public void startMultipleGroups() {
String[] groupIds = { "analytics-group", "audit-group", "notification-group" };
CountDownLatch latch = new CountDownLatch(groupIds.length);
for (String groupId : groupIds) {
startConsumerGroup(groupId, latch);
}
try {
latch.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
}
}
private void startConsumerGroup(String groupId, CountDownLatch latch) {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("group.id", groupId);
props.put("auto.offset.reset", "earliest");
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
new Thread(() -> {
try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
consumer.subscribe(Arrays.asList("orders"));
int recordCount = 0;
while (recordCount < 5) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
recordCount += processRecordsForGroup(groupId, records);
}
} finally {
latch.countDown();
}
}).start();
}
private int processRecordsForGroup(String groupId, ConsumerRecords<String, String> records) {
int count = 0;
for (ConsumerRecord<String, String> record : records) {
logger.info("[{}] Processing: {}", groupId, record.value());
count++;
}
return count;
}
public void configureCooperativeRebalancing() {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("group.id", "cooperative-group");
props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
props.put("auto.offset.reset", "earliest");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("orders"), new ConsumerRebalanceListener() {
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
logger.info("Revoked partitions: {}", partitions);
// complete processing of current records
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
logger.info("Assigned partitions: {}", partitions);
// initialize any partition-specific state
}
});
// process a few records to demonstrate
int recordCount = 0;
while (recordCount < 5) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
recordCount += records.count();
}
consumer.close();
}
public void processWithManualCommit() {
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("group.id", "manual-commit-group");
props.put("enable.auto.commit", "false");
props.put("max.poll.records", "10");
props.put("key.deserializer", StringDeserializer.class.getName());
props.put("value.deserializer", StringDeserializer.class.getName());
props.put("auto.offset.reset", "earliest");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("orders"));
int totalProcessed = 0;
while (totalProcessed < 10) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
try {
processOrder(record);
totalProcessed++;
} catch (Exception e) {
logger.error("Processing failed for offset: {}", record.offset(), e);
break;
}
}
if (!records.isEmpty()) {
consumer.commitSync();
logger.info("Committed {} records", records.count());
}
}
consumer.close();
}
private void processOrder(ConsumerRecord<String, String> record) {
// simulate order processing
logger.info("Processing order: {}", record.value());
// this section is mostly your part of implementation, which is out of bounds of the article topic coverage
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/image/resize/imgscalr/ImgscalrExampleIntegrationTest.java | image-processing/src/test/java/com/baeldung/image/resize/imgscalr/ImgscalrExampleIntegrationTest.java | package com.baeldung.image.resize.imgscalr;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ImgscalrExampleIntegrationTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Test.None.class)
public void whenTargetWidthIsZero_thenImageIsCreated() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenTargetHeightIsZero_thenImageIsCreated() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImgscalrExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = ImgscalrExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/image/resize/imagetobufferedimage/ImageToBufferedImageIntegrationTest.java | image-processing/src/test/java/com/baeldung/image/resize/imagetobufferedimage/ImageToBufferedImageIntegrationTest.java | package com.baeldung.image.resize.imagetobufferedimage;
import com.baeldung.imageprocessing.imagetobufferedimage.ImageToBufferedImage;
import org.junit.Test;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ImageToBufferedImageIntegrationTest {
Image image = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
public ImageToBufferedImageIntegrationTest() throws IOException {
}
@Test
public void whenConvertUsingConstructorWithValidDimensions_thenImageGeneratedWithoutError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingConstructor(image);
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertUsingConstructorWithInvalidDimensions_thenImageGeneratedWithError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
converter.convertUsingConstructor(new BufferedImage(-100, -100, BufferedImage.TYPE_INT_ARGB));
}
@Test
public void whenConvertUsingCastingWithCompatibleImageType_thenImageGeneratedWithoutError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingCasting(image);
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = ClassCastException.class)
public void whenConvertUsingCastingWithIncompatibleImageType_thenImageGeneratedWithError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
// PNG format is not directly supported by BufferedImage
Image image = new ImageIcon("src/main/resources/images/baeldung.png").getImage();
converter.convertUsingCasting(image);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/image/resize/thumbnailator/ThumbnailatorExampleIntegrationTest.java | image-processing/src/test/java/com/baeldung/image/resize/thumbnailator/ThumbnailatorExampleIntegrationTest.java | package com.baeldung.image.resize.thumbnailator;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ThumbnailatorExampleIntegrationTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ThumbnailatorExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = ThumbnailatorExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/image/resize/core/ImageScaledInstanceExampleIntegrationTest.java | image-processing/src/test/java/com/baeldung/image/resize/core/ImageScaledInstanceExampleIntegrationTest.java | package com.baeldung.image.resize.core;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class ImageScaledInstanceExampleIntegrationTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = ImageScaledInstanceExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/image/resize/core/Graphics2DExampleIntegrationTest.java | image-processing/src/test/java/com/baeldung/image/resize/core/Graphics2DExampleIntegrationTest.java | package com.baeldung.image.resize.core;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class Graphics2DExampleIntegrationTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = Graphics2DExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageDoesNotExist_thenErrorIsNotThrownAndImageIsGenerated() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = Graphics2DExample.resizeImage(null, targetWidth, targetHeight);
assertNotNull(outputImage);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/image/resize/marvin/MarvinExampleIntegrationTest.java | image-processing/src/test/java/com/baeldung/image/resize/marvin/MarvinExampleIntegrationTest.java | package com.baeldung.image.resize.marvin;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.junit.Test;
public class MarvinExampleIntegrationTest {
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenImageGeneratedWithoutError() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNotNull(outputImage);
}
@Test(expected = Test.None.class)
public void whenOriginalImageExistsAndTargetSizesAreNotZero_thenOutputImageSizeIsValid() throws IOException {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
assertNotEquals(originalImage.getWidth(), targetWidth);
assertNotEquals(originalImage.getHeight(), targetHeight);
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertEquals(outputImage.getWidth(), targetWidth);
assertEquals(outputImage.getHeight(), targetHeight);
}
@Test(expected = Exception.class)
public void whenTargetWidthIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 0;
int targetHeight = 200;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenTargetHeightIsZero_thenErrorIsThrown() throws IOException {
int targetWidth = 200;
int targetHeight = 0;
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = MarvinExample.resizeImage(originalImage, targetWidth, targetHeight);
assertNull(outputImage);
}
@Test(expected = Exception.class)
public void whenOriginalImageDoesNotExist_thenErrorIsThrown() {
int targetWidth = 200;
int targetHeight = 200;
BufferedImage outputImage = MarvinExample.resizeImage(null, targetWidth, targetHeight);
assertNull(outputImage);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/test/java/com/baeldung/rgb/setcolor/GraphicsRGBSetColorUnitTest.java | image-processing/src/test/java/com/baeldung/rgb/setcolor/GraphicsRGBSetColorUnitTest.java | package com.baeldung.rgb.setcolor;
import org.junit.Before;
import org.junit.Test;
import java.awt.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class GraphicsRGBSetColorUnitTest {
private Graphics graphics;
@Before
public void setUp() {
// Create a mock Graphics object
graphics = mock(Graphics.class);
}
@Test
public void whenSetColorWhite_thenColorIsSetCorrectly() {
// Create a white color
Color myWhite = new Color(255, 255, 255);
// Apply the color using setColor()
graphics.setColor(myWhite);
// Verify that setColor was called with the correct color
verify(graphics).setColor(myWhite);
}
@Test
public void whenSetColorPurple_thenColorIsSetCorrectly() {
// Create a purple color
Color myPurple = new Color(128, 0, 128);
// Apply the color using setColor()
graphics.setColor(myPurple);
// Verify that setColor was called with the correct color
verify(graphics).setColor(myPurple);
}
@Test
public void whenSetColorRed_thenRectangleIsDrawnWithRed() {
// Create a red color
Color redColor = new Color(255, 0, 0);
// Apply the red color and draw a rectangle
graphics.setColor(redColor);
graphics.fillRect(10, 10, 100, 100);
// Verify that setColor was called with the correct color
verify(graphics).setColor(redColor);
// Verify that the rectangle was drawn with the correct parameters
verify(graphics).fillRect(10, 10, 100, 100);
}
@Test
public void whenSetMultipleColors_thenRectanglesAreDrawnWithCorrectColors() {
// Create red and blue colors
Color redColor = new Color(255, 0, 0);
Color blueColor = new Color(0, 0, 255);
// Apply the red color and draw the first rectangle
graphics.setColor(redColor);
graphics.fillRect(10, 10, 100, 100);
// Apply the blue color and draw the second rectangle
graphics.setColor(blueColor);
graphics.fillRect(120, 10, 100, 100);
// Verify that setColor was called with the correct colors in the right order
verify(graphics).setColor(redColor);
verify(graphics).setColor(blueColor);
// Verify that the rectangles were drawn with the correct parameters
verify(graphics).fillRect(10, 10, 100, 100);
verify(graphics).fillRect(120, 10, 100, 100);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imagecollision/Game.java | image-processing/src/main/java/com/baeldung/imagecollision/Game.java | package com.baeldung.imagecollision;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Game extends JPanel implements Runnable {
GameObject vader, luke;
BufferedImage vaderImage, lukeImage;
Thread gameThread;
boolean collided = false;
enum CollisionType {
BOUNDING_BOX,
AREA_CIRCLE,
CIRCLE_DISTANCE,
POLYGON,
PIXEL_PERFECT
}
CollisionType collisionType = CollisionType.PIXEL_PERFECT;
public Game() {
try {
vaderImage = ImageIO.read(new File("src/main/resources/images/vader.png"));
lukeImage = ImageIO.read(new File("src/main/resources/images/luke.png"));
vader = new GameObject(170, 370, vaderImage);
luke = new GameObject(1600, 370, lukeImage);
} catch (IOException e) {
System.err.println("Error loading images");
e.printStackTrace();
}
setBackground(Color.white);
gameThread = new Thread(this);
gameThread.start();
}
public void run() {
while (!collided) {
vader.move(2, 0);
luke.move(-2, 0);
switch (collisionType) {
case BOUNDING_BOX:
if (vader.getRectangleBounds().intersects(luke.getRectangleBounds())) {
collided = true;
}
break;
case AREA_CIRCLE:
Area ellipseAreaVader = vader.getEllipseAreaBounds();
Area ellipseAreaLuke = luke.getEllipseAreaBounds();
ellipseAreaVader.intersect(ellipseAreaLuke);
if (!ellipseAreaVader.isEmpty()) {
collided = true;
}
break;
case CIRCLE_DISTANCE:
Ellipse2D circleVader = vader.getCircleBounds();
Ellipse2D circleLuke = luke.getCircleBounds();
double dx = circleVader.getCenterX() - circleLuke.getCenterX();
double dy = circleVader.getCenterY() - circleLuke.getCenterY();
double distance = Math.sqrt(dx * dx + dy * dy);
double radiusVader = circleVader.getWidth() / 2.0;
double radiusLuke = circleLuke.getWidth() / 2.0;
if (distance < radiusVader + radiusLuke) {
collided = true;
}
break;
case POLYGON:
Area polygonAreaVader = vader.getPolygonBounds();
Area polygonAreaLuke = luke.getPolygonBounds();
polygonAreaVader.intersect(polygonAreaLuke);
if (!polygonAreaVader.isEmpty()) {
collided = true;
}
break;
case PIXEL_PERFECT:
if (vader.collidesWith(luke)) {
collided = true;
}
break;
}
repaint();
try {
Thread.sleep(16);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
vader.draw(g);
luke.draw(g);
if (collided) {
g.setColor(Color.RED);
g.setFont(new Font("SansSerif", Font.BOLD, 50));
g.drawString("COLLISION!", getWidth() / 2 - 100, getHeight() / 2);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Epic Duel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.add(new Game());
frame.setVisible(true);
});
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imagecollision/GameObject.java | image-processing/src/main/java/com/baeldung/imagecollision/GameObject.java | package com.baeldung.imagecollision;
import java.awt.*;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
public class GameObject {
public int x, y;
public int width, height;
public BufferedImage image;
int[] xPoints = new int[4];
int[] yPoints = new int[4];
int[] xOffsets = {100, 200, 100, 0};
int[] yOffsets = {0, 170, 340, 170};
public GameObject(int x, int y, BufferedImage image) {
this.x = x;
this.y = y;
this.image = image;
this.width = image.getWidth();
this.height = image.getHeight();
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public void draw(Graphics g) {
g.drawImage(image, x, y, null);
}
public Rectangle getRectangleBounds() {
return new Rectangle(x, y, width, height);
}
public Area getEllipseAreaBounds() {
Ellipse2D.Double coll = new Ellipse2D.Double(x, y, width, height);
return new Area(coll);
}
public Ellipse2D getCircleBounds() {
return new Ellipse2D.Double(x, y, 200, 200);
}
public Area getPolygonBounds() {
for (int i = 0; i < xOffsets.length; i++) {
this.xPoints[i] = x + xOffsets[i];
this.yPoints[i] = y + yOffsets[i];
}
Polygon p = new Polygon(xPoints, yPoints, xOffsets.length);
return new Area(p);
}
public boolean collidesWith(GameObject other) {
int top = Math.max(y, other.y);
int bottom = Math.min(y + height, other.y + other.height);
int left = Math.max(x, other.x);
int right = Math.min(x + width, other.x + other.height);
if (right <= left || bottom <= top) return false;
for (int i = top; i < bottom; i++) {
for (int j = left; j < right; j++) {
int pixel1 = image.getRGB(j - x, i - y);
int pixel2 = other.image.getRGB(j - other.x, i - other.y);
if (((pixel1 >> 24) & 0xff) > 0 && ((pixel2 >> 24) & 0xff) > 0) {
return true;
}
}
}
return false;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/image/resize/imgscalr/ImgscalrExample.java | image-processing/src/main/java/com/baeldung/image/resize/imgscalr/ImgscalrExample.java | package com.baeldung.image.resize.imgscalr;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class ImgscalrExample {
public static BufferedImage simpleResizeImage(BufferedImage originalImage, int targetWidth) {
return Scalr.resize(originalImage, targetWidth);
}
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
return Scalr.resize(originalImage, Scalr.Method.AUTOMATIC, Scalr.Mode.AUTOMATIC, targetWidth, targetHeight, Scalr.OP_ANTIALIAS);
}
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-imgscalr.jpg"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/image/resize/thumbnailator/ThumbnailatorExample.java | image-processing/src/main/java/com/baeldung/image/resize/thumbnailator/ThumbnailatorExample.java | package com.baeldung.image.resize.thumbnailator;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
public class ThumbnailatorExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Thumbnails.of(originalImage)
.size(targetWidth, targetHeight)
.outputFormat("JPEG")
.outputQuality(0.90)
.toOutputStream(outputStream);
byte[] data = outputStream.toByteArray();
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
return ImageIO.read(inputStream);
}
public static void main(String[] args) throws Exception {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-thumbnailator.jpg"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/image/resize/core/Graphics2DExample.java | image-processing/src/main/java/com/baeldung/image/resize/core/Graphics2DExample.java | package com.baeldung.image.resize.core;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Graphics2DExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
return resizedImage;
}
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-graphics2d.jpg"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/image/resize/core/ImageScaledInstanceExample.java | image-processing/src/main/java/com/baeldung/image/resize/core/ImageScaledInstanceExample.java | package com.baeldung.image.resize.core;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageScaledInstanceExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_DEFAULT);
BufferedImage bufferedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics()
.drawImage(resultingImage, 0, 0, null);
return bufferedImage;
}
public static void main(String[] args) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-scaledinstance.jpg"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/image/resize/marvin/MarvinExample.java | image-processing/src/main/java/com/baeldung/image/resize/marvin/MarvinExample.java | package com.baeldung.image.resize.marvin;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.marvinproject.image.transform.scale.Scale;
import marvin.image.MarvinImage;
public class MarvinExample {
static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
MarvinImage image = new MarvinImage(originalImage);
Scale scale = new Scale();
scale.load();
scale.setAttribute("newWidth", targetWidth);
scale.setAttribute("newHeight", targetHeight);
scale.process(image.clone(), image, null, null, false);
return image.getBufferedImageNoAlpha();
}
public static void main(String args[]) throws IOException {
BufferedImage originalImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
BufferedImage outputImage = resizeImage(originalImage, 200, 200);
ImageIO.write(outputImage, "jpg", new File("src/main/resources/images/sampleImage-resized-marvin.jpg"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/tesseract/TesseractPlatformExample.java | image-processing/src/main/java/com/baeldung/tesseract/TesseractPlatformExample.java | package com.baeldung.tesseract;
import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.leptonica.PIX;
import org.bytedeco.tesseract.TessBaseAPI;
public class TesseractPlatformExample {
@SuppressWarnings("resource")
public static void main(String[] args) {
try {
TessBaseAPI tessApi = new TessBaseAPI();
tessApi.Init("src/main/resources/tessdata", "eng", 3);
tessApi.SetPageSegMode(1);
PIX image = org.bytedeco.leptonica.global.lept.pixRead("src/main/resources/images/baeldung.png");
tessApi.SetImage(image);
BytePointer outText = tessApi.GetUTF8Text();
System.out.println(outText.getString());
tessApi.End();
} catch(Exception e) {
e.printStackTrace();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/tesseract/Tess4JExample.java | image-processing/src/main/java/com/baeldung/tesseract/Tess4JExample.java | package com.baeldung.tesseract;
import java.awt.Rectangle;
import java.io.File;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Tess4JExample {
public static void main(String[] args) {
String result = null;
try {
File image = new File("src/main/resources/images/baeldung.png");
Tesseract tesseract = new Tesseract();
tesseract.setLanguage("spa");
tesseract.setPageSegMode(1);
tesseract.setOcrEngineMode(1);
tesseract.setHocr(true);
tesseract.setDatapath("src/main/resources/tessdata");
result = tesseract.doOCR(image, new Rectangle(1200, 200));
} catch (TesseractException e) {
e.printStackTrace();
}
System.out.println(result);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/bufferedimageresize/Application.java | image-processing/src/main/java/com/baeldung/imageprocessing/bufferedimageresize/Application.java | package com.baeldung.image;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
public class Application {
public static void main(String[] args) throws Exception {
BufferedImage srcImg = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
float scaleW = 2.0f, scaleH = 2.0f;
int w = srcImg.getWidth() * (int) scaleW;
int h = srcImg.getHeight() * (int) scaleH;
BufferedImage dstImg = new BufferedImage(w, h, srcImg.getType());
AffineTransform scalingTransform = new AffineTransform();
scalingTransform.scale(scaleW, scaleH);
AffineTransformOp scaleOp = new AffineTransformOp(scalingTransform, AffineTransformOp.TYPE_BILINEAR);
dstImg = scaleOp.filter(srcImg, dstImg);
ImageIO.write(dstImg, "jpg", new File("src/main/resources/images/resized.jpg"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/imagej/ImageJRectExample.java | image-processing/src/main/java/com/baeldung/imageprocessing/imagej/ImageJRectExample.java | package com.baeldung.imageprocessing.imagej;
import ij.IJ;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import java.awt.*;
public class ImageJRectExample {
public static void main(String[] args) {
ImagePlus imp = IJ.openImage(ImageJRectExample.class.getClassLoader().getResource("lena.jpg").getPath());
drawRect(imp);
imp.show();
}
private static void drawRect(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
ip.setColor(Color.BLUE);
ip.setLineWidth(4);
ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/openimaj/OpenIMAJRectExample.java | image-processing/src/main/java/com/baeldung/imageprocessing/openimaj/OpenIMAJRectExample.java | package com.baeldung.imageprocessing.openimaj;
import org.openimaj.image.DisplayUtilities;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.math.geometry.point.Point2d;
import org.openimaj.math.geometry.point.Point2dImpl;
import org.openimaj.math.geometry.shape.Polygon;
import java.io.IOException;
import java.util.Arrays;
public class OpenIMAJRectExample {
public static void main(String[] args) throws IOException {
MBFImage image = ImageUtilities.readMBF(OpenIMAJRectExample.class.getClassLoader().getResource("lena.jpg"));
drawRectangle(image);
DisplayUtilities.display(image);
}
private static void drawRectangle(MBFImage image) {
Point2d tl = new Point2dImpl(10, 10);
Point2d bl = new Point2dImpl(10, image.getHeight() - 10);
Point2d br = new Point2dImpl(image.getWidth() - 10, image.getHeight() - 10);
Point2d tr = new Point2dImpl(image.getWidth() - 10, 10);
Polygon polygon = new Polygon(Arrays.asList(tl, bl, br, tr));
image.drawPolygon(polygon, 4, new Float[] { 0f, 0f, 255.0f });
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/CameraStream.java | image-processing/src/main/java/com/baeldung/imageprocessing/opencv/CameraStream.java | package com.baeldung.imageprocessing.opencv;
import java.io.ByteArrayInputStream;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import org.opencv.videoio.VideoCapture;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import nu.pattern.OpenCV;
public class CameraStream extends Application {
private VideoCapture capture;
public void start(Stage stage) throws Exception {
OpenCV.loadShared();
capture = new VideoCapture(0); // The number is the ID of the camera
ImageView imageView = new ImageView();
HBox hbox = new HBox(imageView);
Scene scene = new Scene(hbox);
stage.setScene(scene);
stage.show();
new AnimationTimer() {
@Override
public void handle(long l) {
imageView.setImage(getCapture());
}
}.start();
}
public Image getCapture() {
Mat mat = new Mat();
capture.read(mat);
return mat2Img(mat);
}
public Image getCaptureWithFaceDetection() {
Mat mat = new Mat();
capture.read(mat);
Mat haarClassifiedImg = detectFace(mat);
return mat2Img(haarClassifiedImg);
}
public Image mat2Img(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode("img", mat, bytes);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray());
Image img = new Image(inputStream);
return img;
}
public static void main(String[] args) {
Application.launch(args);
}
public static Mat detectFace(Mat inputImage) {
MatOfRect facesDetected = new MatOfRect();
CascadeClassifier cascadeClassifier = new CascadeClassifier();
int minFaceSize = Math.round(inputImage.rows() * 0.1f);
cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
cascadeClassifier.detectMultiScale(inputImage, facesDetected, 1.1, 3, Objdetect.CASCADE_SCALE_IMAGE, new Size(minFaceSize, minFaceSize), new Size());
Rect[] facesArray = facesDetected.toArray();
for (Rect face : facesArray) {
Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3);
}
return inputImage;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/opencv/FaceDetection.java | image-processing/src/main/java/com/baeldung/imageprocessing/opencv/FaceDetection.java | package com.baeldung.imageprocessing.opencv;
import java.io.ByteArrayInputStream;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.Objdetect;
import javafx.scene.image.Image;
public class FaceDetection {
public static void main(String[] args) {
// Load the native library.
System.load("/opencv/build/lib/libopencv_java4100.dylib");
detectFace(FaceDetection.class.getClassLoader().getResource("portrait.jpg").getPath(),
"./processed.jpg");
}
public static Mat loadImage(String imagePath) {
return Imgcodecs.imread(imagePath);
}
public static void saveImage(Mat imageMatrix, String targetPath) {
Imgcodecs.imwrite(targetPath, imageMatrix);
}
public static void detectFace(String sourceImagePath, String targetImagePath) {
Mat loadedImage = loadImage(sourceImagePath);
MatOfRect facesDetected = new MatOfRect();
CascadeClassifier cascadeClassifier = new CascadeClassifier();
int minFaceSize = Math.round(loadedImage.rows() * 0.1f);
String filename = FaceDetection.class.getClassLoader().getResource("haarcascades/haarcascade_frontalface_alt.xml").getFile();
cascadeClassifier.load(filename);
cascadeClassifier.detectMultiScale(loadedImage,
facesDetected,
1.1,
3,
Objdetect.CASCADE_SCALE_IMAGE,
new Size(minFaceSize, minFaceSize),
new Size());
Rect[] facesArray = facesDetected.toArray();
for(Rect face : facesArray) {
Imgproc.rectangle(loadedImage, face.tl(), face.br(), new Scalar(0, 0, 255), 10);
}
saveImage(loadedImage, targetImagePath);
}
public Image mat2Img(Mat mat) {
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode("img", mat, bytes);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes.toArray());
Image img = new Image(inputStream); return img;
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/twelvemonkeys/TwelveMonkeysExample.java | image-processing/src/main/java/com/baeldung/imageprocessing/twelvemonkeys/TwelveMonkeysExample.java | package com.baeldung.imageprocessing.twelvemonkeys;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TwelveMonkeysExample {
public static void main(String[] args) throws IOException {
BufferedImage image = loadImage();
drawRectangle(image);
displayImage(image);
}
private static BufferedImage loadImage() throws IOException {
String imagePath = TwelveMonkeysExample.class.getClassLoader().getResource("Penguin.ico").getPath();
return ImageIO.read(new File(imagePath));
}
private static void drawRectangle(BufferedImage image) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, image.getWidth() - 20, image.getHeight() - 20);
}
private static void displayImage(BufferedImage image) {
JLabel picLabel = new JLabel(new ImageIcon(image));
JPanel jPanel = new JPanel();
jPanel.add(picLabel);
JFrame f = new JFrame();
f.setSize(new Dimension(200, 200));
f.add(jPanel);
f.setVisible(true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/imagetobufferedimage/ImageToBufferedImage.java | image-processing/src/main/java/com/baeldung/imageprocessing/imagetobufferedimage/ImageToBufferedImage.java | package com.baeldung.imageprocessing.imagetobufferedimage;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ImageToBufferedImage {
// Method 1: Using BufferedImage Constructor
public BufferedImage convertUsingConstructor(Image image) throws IllegalArgumentException {
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Image dimensions are invalid");
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage.getGraphics().drawImage(image, 0, 0, null);
return bufferedImage;
}
// Method 2: Casting Image to BufferedImage
public BufferedImage convertUsingCasting(Image image) throws ClassCastException {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
} else {
throw new ClassCastException("Image type is not compatible with BufferedImage.");
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/addingtext/AddText.java | image-processing/src/main/java/com/baeldung/imageprocessing/addingtext/AddText.java | package com.baeldung.imageprocessing.addingtext;
import ij.IJ;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import java.awt.*;
import java.awt.font.GlyphVector;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.AttributedString;
import javax.imageio.ImageIO;
public class AddText {
public static void main(String[] args) throws IOException {
String imagePath = AddText.class.getClassLoader().getResource("lena.jpg").getPath();
ImagePlus resultPlus= signImageImageProcessor("www.baeldung.com", imagePath);
resultPlus.show();
ImagePlus resultGraphics = new ImagePlus("", signImageGraphics("www.baeldung.com", imagePath));
resultGraphics.show();
ImagePlus resultGraphicsWithIterator = new ImagePlus("", signImageGraphicsWithIterator("www.baeldung.com", imagePath));
resultGraphicsWithIterator.show();
ImagePlus resultGraphicsCentered = new ImagePlus("", signImageCenter("www.baeldung.com", imagePath));
resultGraphicsCentered.show();
ImagePlus resultGraphicsBottomRight = new ImagePlus("", signImageBottomRight("www.baeldung.com", imagePath));
resultGraphicsBottomRight.show();
ImagePlus resultGraphicsTopLeft= new ImagePlus("", signImageTopLeft("www.baeldung.com", imagePath));
resultGraphicsTopLeft.show();
ImagePlus resultGraphicsAdaptBasedOnImage= new ImagePlus("", signImageAdaptBasedOnImage("www.baeldung.com", imagePath));
resultGraphicsAdaptBasedOnImage.show();
}
private static ImagePlus signImageImageProcessor(String text, String path) {
ImagePlus image = IJ.openImage(path);
Font font = new Font("Arial", Font.BOLD, 18);
ImageProcessor ip = image.getProcessor();
ip.setColor(Color.GREEN);
ip.setFont(font);
ip.drawString(text, 0, 20);
return image;
}
private static BufferedImage signImageGraphics(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
Graphics g = image.getGraphics();
g.setFont(font);
g.setColor(Color.GREEN);
g.drawString(text, 0, 20);
return image;
}
private static BufferedImage signImageGraphicsWithIterator(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
g.drawString(attributedText.getIterator(), 0, 20);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageCenter(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text)) / 2;
int positionY = (image.getHeight() - metrics.getHeight()) / 2 + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageBottomRight(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text));
int positionY = (image.getHeight() - metrics.getHeight()) + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageTopLeft(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = new Font("Arial", Font.BOLD, 18);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = 0;
int positionY = metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
/**
* Draw a String centered in the middle of a Rectangle.
*
* @param g The Graphics instance.
* @param text The String to draw.
* @param rect The Rectangle to center the text in.
* @throws IOException
*/
public static BufferedImage signImageAdaptBasedOnImage(String text, String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
Font font = createFontToFit(new Font("Arial", Font.BOLD, 80), text, image);
AttributedString attributedText = new AttributedString(text);
attributedText.addAttribute(TextAttribute.FONT, font);
attributedText.addAttribute(TextAttribute.FOREGROUND, Color.GREEN);
Graphics g = image.getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int positionX = (image.getWidth() - metrics.stringWidth(text));
int positionY = (image.getHeight() - metrics.getHeight()) + metrics.getAscent();
g.drawString(attributedText.getIterator(), positionX, positionY);
return image;
}
public static Font createFontToFit(Font baseFont, String text, BufferedImage image) throws IOException
{
Font newFont = baseFont;
FontMetrics ruler = image.getGraphics().getFontMetrics(baseFont);
GlyphVector vector = baseFont.createGlyphVector(ruler.getFontRenderContext(), text);
Shape outline = vector.getOutline(0, 0);
double expectedWidth = outline.getBounds().getWidth();
double expectedHeight = outline.getBounds().getHeight();
boolean textFits = image.getWidth() >= expectedWidth && image.getHeight() >= expectedHeight;
if(!textFits) {
double widthBasedFontSize = (baseFont.getSize2D()*image.getWidth())/expectedWidth;
double heightBasedFontSize = (baseFont.getSize2D()*image.getHeight())/expectedHeight;
double newFontSize = widthBasedFontSize < heightBasedFontSize ? widthBasedFontSize : heightBasedFontSize;
newFont = baseFont.deriveFont(baseFont.getStyle(), (float)newFontSize);
}
return newFont;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imageprocessing/swing/SwingRectExample.java | image-processing/src/main/java/com/baeldung/imageprocessing/swing/SwingRectExample.java | package com.baeldung.imageprocessing.swing;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class SwingRectExample {
public static void main(String[] args) throws IOException {
BufferedImage image = loadImage();
drawRectangle(image);
displayImage(image);
}
private static BufferedImage loadImage() throws IOException {
String imagePath = SwingRectExample.class.getClassLoader().getResource("lena.jpg").getPath();
return ImageIO.read(new File(imagePath));
}
private static void drawRectangle(BufferedImage image) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, image.getWidth() - 20, image.getHeight() - 20);
}
private static void displayImage(BufferedImage image) {
JLabel picLabel = new JLabel(new ImageIcon(image));
JPanel jPanel = new JPanel();
jPanel.add(picLabel);
JFrame f = new JFrame();
f.setSize(new Dimension(image.getWidth(), image.getHeight()));
f.add(jPanel);
f.setVisible(true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/drawcircle/DrawCircle.java | image-processing/src/main/java/com/baeldung/drawcircle/DrawCircle.java | package com.baeldung.drawcircle;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class DrawCircle extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
float stroke = 2f;
double diameter = Math.min(getWidth(), getHeight()) - 12; // padding
double x = (getWidth() - diameter) / 2.0;
double y = (getHeight() - diameter) / 2.0;
Ellipse2D circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2.setColor(new Color(0xBBDEFB));
g2.fill(circle);
g2.setColor(new Color(0x0D47A1));
g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(circle);
} finally {
g2.dispose();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Circle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawCircle());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/drawcircle/DrawSupersampledCircle.java | image-processing/src/main/java/com/baeldung/drawcircle/DrawSupersampledCircle.java | package com.baeldung.drawcircle;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
public class DrawSupersampledCircle {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("SupersampledCircle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new CirclePanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
static class CirclePanel extends JPanel {
private final BufferedImage hiResImage;
private final int finalSize = 6;
public CirclePanel() {
int scale = 3;
float stroke = 6f;
hiResImage = makeSupersampledCircle(scale, stroke);
setPreferredSize(new Dimension(finalSize + 32, finalSize + 32));
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
try {
int x = (getWidth() - finalSize) / 2;
int y = (getHeight() - finalSize) / 2;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(hiResImage, x, y, finalSize, finalSize, null);
} finally {
g2.dispose();
}
}
private BufferedImage makeSupersampledCircle(int scale, float stroke) {
int hi = finalSize * scale;
BufferedImage img = new BufferedImage(hi, hi, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
double d = hi - stroke;
Shape circle = new Ellipse2D.Double(stroke / 2.0, stroke / 2.0, d, d);
g2.setPaint(new Color(0xBBDEFB));
g2.fill(circle);
g2.setPaint(new Color(0x0D47A1));
g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(circle);
} finally {
g2.dispose();
}
return img;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/drawcircle/DrawBufferedCircle.java | image-processing/src/main/java/com/baeldung/drawcircle/DrawBufferedCircle.java | package com.baeldung.drawcircle;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
public class DrawBufferedCircle {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Circle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new CircleImagePanel(64, 3)); // final size: 64x64, supersample: 3x
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
static class CircleImagePanel extends JPanel {
private final int finalSize;
private final BufferedImage circleImage;
public CircleImagePanel(int finalSize, int scale) {
this.finalSize = finalSize;
this.circleImage = makeCircleImage(finalSize, scale);
setPreferredSize(new Dimension(finalSize + 16, finalSize + 16));
setBackground(Color.WHITE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
try {
int x = (getWidth() - finalSize) / 2;
int y = (getHeight() - finalSize) / 2;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(circleImage, x, y, finalSize, finalSize, null);
} finally {
g2.dispose();
}
}
private BufferedImage makeCircleImage(int finalSize, int scale) {
int hi = finalSize * scale;
BufferedImage img = new BufferedImage(hi, hi, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_PURE);
g2.setComposite(AlphaComposite.Src);
float stroke = 6f * scale / 3f;
double diameter = hi - stroke - (4 * scale);
double x = (hi - diameter) / 2.0;
double y = (hi - diameter) / 2.0;
Shape circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2.setPaint(new Color(0xBBDEFB));
g2.fill(circle);
g2.setPaint(new Color(0x0D47A1));
g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(circle);
} finally {
g2.dispose();
}
return img;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imagefromwebcam/WebcamCaptureExample.java | image-processing/src/main/java/com/baeldung/imagefromwebcam/WebcamCaptureExample.java | package com.baeldung.imagefromwebcam;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.util.ImageUtils;
public class WebcamCaptureExample {
public static void main(String[] args) throws IOException, Exception {
Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, ImageUtils.FORMAT_JPG, new File("selfie.jpg"));
}
public void captureWithPanel() {
Webcam webcam = Webcam.getDefault();
webcam.setViewSize(WebcamResolution.VGA.getSize());
WebcamPanel panel = new WebcamPanel(webcam);
panel.setImageSizeDisplayed(true);
JFrame window = new JFrame("Webcam");
window.add(panel);
window.setResizable(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imagefromwebcam/MarvinExample.java | image-processing/src/main/java/com/baeldung/imagefromwebcam/MarvinExample.java | package com.baeldung.imagefromwebcam;
import marvin.gui.MarvinImagePanel;
import marvin.image.MarvinImage;
import marvin.io.MarvinImageIO;
import marvin.video.MarvinJavaCVAdapter;
import marvin.video.MarvinVideoInterface;
import marvin.video.MarvinVideoInterfaceException;
public class MarvinExample {
public static void main(String[] args) throws MarvinVideoInterfaceException {
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImageIO.saveImage(image, "selfie.jpg");
}
public void captureWithPanel() throws MarvinVideoInterfaceException {
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImagePanel imagePanel = new MarvinImagePanel();
imagePanel.setImage(image);
imagePanel.setSize(800,600);
imagePanel.setVisible(true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/image-processing/src/main/java/com/baeldung/imagefromwebcam/OpenCVExample.java | image-processing/src/main/java/com/baeldung/imagefromwebcam/OpenCVExample.java | package com.baeldung.imagefromwebcam;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;
public class OpenCVExample {
public static void main(String[] args) throws Exception {
CanvasFrame canvas = new CanvasFrame("Web Cam");
canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FrameGrabber grabber = new OpenCVFrameGrabber(0);
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
grabber.start();
Frame frame = grabber.grab();
IplImage img = converter.convert(frame);
cvSaveImage("selfie.jpg", img);
canvas.showImage(frame);
Thread.sleep(2000);
canvas.dispatchEvent(new WindowEvent(canvas, WindowEvent.WINDOW_CLOSING));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-2/src/test/java/com/baeldung/staticvalueinjection/StaticPropertyHolderUnitTest.java | spring-di-2/src/test/java/com/baeldung/staticvalueinjection/StaticPropertyHolderUnitTest.java | package com.baeldung.staticvalueinjection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = StaticPropertyHolder.class)
public class StaticPropertyHolderUnitTest {
@Test
public void givenStaticPropertyInSpringBean_WhenUsingValueOnSetter_ThenValueInjected() {
assertNull(StaticPropertyHolder.getStaticNameInjectedOnField());
assertEquals("Inject a value to a static field", StaticPropertyHolder.getStaticName());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-2/src/test/java/com/baeldung/di/aspectj/PersonUnitTest.java | spring-di-2/src/test/java/com/baeldung/di/aspectj/PersonUnitTest.java | package com.baeldung.di.aspectj;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AspectJConfig.class)
public class PersonUnitTest {
@Test
public void givenUnmanagedObjects_whenInjectingIdService_thenIdValueIsCorrectlySet() {
PersonObject personObject = new PersonObject("Baeldung");
personObject.generateId();
assertEquals(1, personObject.getId());
assertEquals("Baeldung", personObject.getName());
PersonEntity personEntity = new PersonEntity("Baeldung");
assertEquals(2, personEntity.getId());
assertEquals("Baeldung", personEntity.getName());
}
} | java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-2/src/test/java/com/baeldung/di/spring/SpringUnitTest.java | spring-di-2/src/test/java/com/baeldung/di/spring/SpringUnitTest.java | package com.baeldung.di.spring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { SpringMainConfig.class })
public class SpringUnitTest {
@Autowired
ApplicationContext context;
@Test
public void givenAccountServiceAutowiredToUserService_WhenGetAccountServiceInvoked_ThenReturnValueIsNotNull() {
UserService userService = context.getBean(UserService.class);
assertNotNull(userService.getAccountService());
}
@Test
public void givenBookServiceIsRegisteredAsBeanInContext_WhenBookServiceIsRetrievedFromContext_ThenReturnValueIsNotNull() {
BookService bookService = context.getBean(BookService.class);
assertNotNull(bookService);
}
@Test
public void givenBookServiceIsRegisteredAsBeanInContextByOverridingAudioBookService_WhenAudioBookServiceIsRetrievedFromContext_ThenNoSuchBeanDefinitionExceptionIsThrown() {
BookService bookService = context.getBean(BookService.class);
assertNotNull(bookService);
AudioBookService audioBookService = context.getBean(AudioBookService.class);
assertNotNull(audioBookService);
}
@Test
public void givenAuthorServiceAutowiredToBookServiceAsOptionalDependency_WhenBookServiceIsRetrievedFromContext_ThenNoSuchBeanDefinitionExceptionIsNotThrown() {
BookService bookService = context.getBean(BookService.class);
assertNotNull(bookService);
}
@Test
public void givenSpringPersonServiceConstructorAnnotatedByAutowired_WhenSpringPersonServiceIsRetrievedFromContext_ThenInstanceWillBeCreatedFromTheConstructor() {
SpringPersonService personService = context.getBean(SpringPersonService.class);
assertNotNull(personService);
}
@Test
public void givenPersonDaoAutowiredToSpringPersonServiceBySetterInjection_WhenSpringPersonServiceRetrievedFromContext_ThenPersonDaoInitializedByTheSetter() {
SpringPersonService personService = context.getBean(SpringPersonService.class);
assertNotNull(personService);
assertNotNull(personService.getPersonDao());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/spring-di-2/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java | spring-di-2/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java | package com.baeldung.di.spring;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class BeanInjectionIntegrationTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("com.baeldung.di.spring.xml");
}
@Test
public void singletonBean_getBean_returnsSingleInstance() {
final IndexApp indexApp1 = applicationContext.getBean("indexApp", IndexApp.class);
final IndexApp indexApp2 = applicationContext.getBean("indexApp", IndexApp.class);
assertEquals(indexApp1, indexApp2);
}
@Test
public void getBean_returnsInstance() {
final IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class);
assertNotNull(indexApp);
}
}
| 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.