This commit is contained in:
Palaniappan Arunachalam 2022-02-09 13:24:32 +05:30
commit 3d6e3af927
221 changed files with 3469 additions and 1041 deletions

View File

@ -27,3 +27,4 @@ HELP.md
### VS Code ###
.vscode/

View File

@ -4,15 +4,15 @@ This following table contains test URLs that can be used with the Olingo V2 demo
| URL | Description |
|------------------------------------------|-------------------------------------------------|
| `http://localhost:8180/odata/$metadata` | fetch OData metadata document |
| `http://localhost:8180/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 |
| `http://localhost:8180/odata/CarMakers?$count` | Return total count of entities in this set |
| `http://localhost:8180/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' |
| `http://localhost:8180/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' |
| `http://localhost:8180/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker|
| `http://localhost:8180/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties |
| `http://localhost:8180/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties |
| `http://localhost:8180/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation|
| `http://localhost:8080/odata/$metadata` | fetch OData metadata document |
| `http://localhost:8080/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 |
| `http://localhost:8080/odata/CarMakers?$count` | Return total count of entities in this set |
| `http://localhost:8080/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' |
| `http://localhost:8080/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' |
| `http://localhost:8080/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker|
| `http://localhost:8080/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties |
| `http://localhost:8080/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties |
| `http://localhost:8080/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation|

View File

@ -3,16 +3,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.examples.olingo2</groupId>
<artifactId>olingo2</artifactId>
<name>olingo2</name>
<description>Sample Olingo 2 Project</description>
<groupId>com.baeldung.examples.olingo</groupId>
<artifactId>apache-olingo</artifactId>
<name>apache-olingo</name>
<description>Sample Apache Olingo Project</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
@ -43,7 +43,7 @@
<dependency>
<groupId>org.apache.olingo</groupId>
<artifactId>olingo-odata2-core</artifactId>
<version>${olingo2.version}</version>
<version>${olingo.version}</version>
<!-- Avoid jax-rs version conflict by excluding Olingo's version -->
<exclusions>
<exclusion>
@ -55,12 +55,12 @@
<dependency>
<groupId>org.apache.olingo</groupId>
<artifactId>olingo-odata2-jpa-processor-core</artifactId>
<version>${olingo2.version}</version>
<version>${olingo.version}</version>
</dependency>
<dependency>
<groupId>org.apache.olingo</groupId>
<artifactId>olingo-odata2-jpa-processor-ref</artifactId>
<version>${olingo2.version}</version>
<version>${olingo.version}</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
@ -80,7 +80,7 @@
</build>
<properties>
<olingo2.version>2.0.11</olingo2.version>
<olingo.version>2.0.11</olingo.version>
</properties>
</project>
</project>

View File

@ -27,11 +27,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* ODataJPAServiceFactory implementation for our sample domain
* @author Philippe
*
*/
@Component
public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
@ -44,7 +39,7 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
/**
* This method will be called by Olingo on every request to
* initialize the ODataJPAContext that will be used.
* initialize the ODataJPAContext that will be used.
*/
@Override
public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
@ -54,14 +49,14 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
ODataContext octx = ctx.getODataContext();
HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
EntityManager em = (EntityManager)request.getAttribute(JerseyConfig.EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
// Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig)
ctx.setEntityManager(new EntityManagerWrapper(em));
ctx.setPersistenceUnitName("default");
// We're managing the EM's lifecycle, so we must inform Olingo that it should not
// try to manage transactions and/or persistence sessions
ctx.setContainerManaged(true);
ctx.setContainerManaged(true);
return ctx;
}

View File

@ -1,6 +1,12 @@
package com.baeldung.examples.olingo2;
package com.baeldung.examples.olingo2;
import java.io.IOException;
import org.apache.olingo.odata2.api.ODataServiceFactory;
import org.apache.olingo.odata2.core.rest.ODataRootLocator;
import org.apache.olingo.odata2.core.rest.app.ODataApplication;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
@ -15,28 +21,15 @@ import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.apache.olingo.odata2.api.ODataServiceFactory;
import org.apache.olingo.odata2.core.rest.ODataRootLocator;
import org.apache.olingo.odata2.core.rest.app.ODataApplication;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Jersey JAX-RS configuration
* @author Philippe
*
*/
@Component
@ApplicationPath("/odata")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) {
public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) {
ODataApplication app = new ODataApplication();
app
.getClasses()
.forEach( c -> {
@ -46,11 +39,11 @@ public class JerseyConfig extends ResourceConfig {
register(c);
}
});
register(new CarsRootLocator(serviceFactory));
register(new CarsRootLocator(serviceFactory));
register( new EntityManagerFilter(emf));
}
/**
* This filter handles the EntityManager transaction lifecycle.
* @author Philippe
@ -72,7 +65,7 @@ public class JerseyConfig extends ResourceConfig {
}
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
public void filter(ContainerRequestContext ctx) {
log.info("[I60] >>> filter");
EntityManager em = this.emf.createEntityManager();
httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, em);
@ -85,7 +78,7 @@ public class JerseyConfig extends ResourceConfig {
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
log.info("[I68] <<< filter");
EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE);

View File

@ -7,7 +7,7 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
@SpringBootApplication
public class Olingo2SampleApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
public static void main(String[] args) {
SpringApplication.run(Olingo2SampleApplication.class);
}
}

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Olingo2SampleApplicationUnitTest {
public class Olingo2SampleApplicationIntegrationTest {
@Test
public void contextLoads() {

View File

@ -1,3 +1,5 @@
*.docx
temp.xls
temp.xlsx
CellStyleTest_output.xlsx

View File

@ -14,4 +14,5 @@ This module contains articles about Apache POI.
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
- [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders)
- [Reading Values From Excel in Java](https://www.baeldung.com/java-read-dates-excel)
- [Change Cell Font Style with Apache POI](https://www.baeldung.com/apache-poi-change-cell-font)
- More articles: [[next -->]](../apache-poi-2)

View File

@ -33,7 +33,7 @@
</dependencies>
<properties>
<poi.version>4.1.1</poi.version>
<poi.version>5.2.0</poi.version>
<jexcel.version>1.0.6</jexcel.version>
</properties>

View File

@ -1,25 +1,24 @@
package com.baeldung.poi.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelPOIHelper {
@ -33,7 +32,7 @@ public class ExcelPOIHelper {
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
switch (cell.getCellType()) {
case STRING:
data.get(i)
.add(cell.getRichStringCellValue()

View File

@ -44,6 +44,7 @@ public class ExcelUtility {
}
}
inputStream.close();
baeuldungWorkBook.close();
} catch (IOException e) {
throw e;

View File

@ -0,0 +1,25 @@
package com.baeldung.poi.excel.cellstyle;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
public class CellStyler {
public CellStyle createWarningColor(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("Courier New");
font.setBold(true);
font.setUnderline(Font.U_SINGLE);
font.setColor(HSSFColorPredefined.DARK_RED.getIndex());
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}

View File

@ -1,25 +1,18 @@
package com.baeldung.jexcel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import jxl.read.biff.BiffException;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jexcel.JExcelHelper;
import jxl.write.WriteException;
import jxl.read.biff.BiffException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.Before;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
public class JExcelIntegrationTest {

View File

@ -1,22 +1,15 @@
package com.baeldung.poi.excel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import jxl.read.biff.BiffException;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.poi.excel.ExcelPOIHelper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.Before;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ExcelIntegrationTest {

View File

@ -1,17 +1,19 @@
package com.baeldung.poi.excel.cellstyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
public class CellStyleHandlerUnitTest {
private static final String FILE_NAME = "cellstyle/CellStyleHandlerTest.xlsx";

View File

@ -0,0 +1,52 @@
package com.baeldung.poi.excel.cellstyle;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
public class CellStylerUnitTest {
private static String FILE_NAME = "com/baeldung/poi/excel/cellstyle/CellStyle.xlsx";
private static final String NEW_FILE_NAME = "CellStyleTest_output.xlsx";
private String fileLocation;
@Before
public void setup() throws IOException, URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME)
.toURI())
.toString();
}
@Test
public void testApplyWarningColor() throws IOException {
Workbook workbook = new XSSFWorkbook(fileLocation);
Sheet sheet = workbook.getSheetAt(0);
Row row1 = sheet.createRow(0);
row1.setHeightInPoints((short) 40);
CellStyler styler = new CellStyler();
CellStyle style = styler.createWarningColor(workbook);
Cell cell1 = row1.createCell(0);
cell1.setCellStyle(style);
cell1.setCellValue("Hello");
Cell cell2 = row1.createCell(1);
cell2.setCellStyle(style);
cell2.setCellValue("world!");
FileOutputStream outputStream = new FileOutputStream(NEW_FILE_NAME);
workbook.write(outputStream);
outputStream.close();
workbook.close();
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung.differences.rdd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
@ -12,12 +12,15 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
public class TransformationsUnitTest {
public static final String COMMA_DELIMITER = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
private static JavaSparkContext sc;
private static JavaRDD<String> tourists;
@BeforeClass
public static void init() {
SparkConf conf = new SparkConf().setAppName("uppercaseCountries")
@ -25,8 +28,11 @@ public class TransformationsUnitTest {
sc = new JavaSparkContext(conf);
tourists = sc.textFile("data/Tourist.csv")
.filter(line -> !line.startsWith("Region")); //filter header row
// delete previous output dir and files
FileUtils.deleteQuietly(new File("data/output"));
}
@AfterClass
public static void cleanup() {
sc.close();
@ -39,9 +45,9 @@ public class TransformationsUnitTest {
return columns[1].toUpperCase();
})
.distinct();
upperCaseCountries.saveAsTextFile("data/output/uppercase.txt");
upperCaseCountries.foreach(country -> {
//replace non alphanumerical characters
country = country.replaceAll("[^a-zA-Z]", "");
@ -52,9 +58,9 @@ public class TransformationsUnitTest {
@Test
public void whenFilterByCountry_thenShowRequestedCountryRecords() {
JavaRDD<String> touristsInMexico = tourists.filter(line -> line.split(COMMA_DELIMITER)[1].equals("Mexico"));
touristsInMexico.saveAsTextFile("data/output/touristInMexico.txt");
touristsInMexico.foreach(record -> {
assertEquals("Mexico", record.split(COMMA_DELIMITER)[1]);
});

0
book
View File

View File

@ -4,4 +4,5 @@ This module contains articles about Java 15.
### Relevant articles
- [Hidden Classes in Java 15](https://www.baeldung.com/java-hidden-classes)
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)

View File

@ -1,5 +1,6 @@
### Relevant articles:
- [An Introduction to InstantSource in Java 17](https://www.baeldung.com/java-instantsource)
- [Pattern Matching for Switch](https://www.baeldung.com/java-switch-pattern-matching)
- [Introduction to HexFormat in Java 17](https://www.baeldung.com/java-hexformat)
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)

View File

@ -1,17 +1,16 @@
package com.baeldung.collections.iterators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
* Source code https://github.com/eugenp/tutorials
*
* @author Santosh Thakur
*/
public class Iterators {
private static final Logger LOG = LoggerFactory.getLogger(Iterators.class);
public static int failFast1() {
ArrayList<Integer> numbers = new ArrayList<>();
@ -44,7 +43,7 @@ public class Iterators {
}
}
System.out.println("using iterator's remove method = " + numbers);
LOG.debug("using iterator's remove method = {}", numbers);
iterator = numbers.iterator();
while (iterator.hasNext()) {

View File

@ -3,6 +3,8 @@ package com.baeldung.collections.bitset;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.BitSet;
@ -10,18 +12,20 @@ import static org.assertj.core.api.Assertions.assertThat;
public class BitSetUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(BitSetUnitTest.class);
@Test
public void givenBoolArray_whenMemoryLayout_thenConsumeMoreThanOneBit() {
boolean[] bits = new boolean[1024 * 1024];
System.out.println(ClassLayout.parseInstance(bits).toPrintable());
LOG.debug(ClassLayout.parseInstance(bits).toPrintable());
}
@Test
public void givenBitSet_whenMemoryLayout_thenConsumeOneBitPerFlag() {
BitSet bitSet = new BitSet(1024 * 1024);
System.out.println(GraphLayout.parseInstance(bitSet).toPrintable());
LOG.debug(GraphLayout.parseInstance(bitSet).toPrintable());
}
@Test
@ -157,7 +161,7 @@ public class BitSetUnitTest {
BitSet bitSet = new BitSet();
bitSet.set(15, 25);
bitSet.stream().forEach(System.out::println);
bitSet.stream().forEach(bit -> LOG.debug(String.valueOf(bit)));
assertThat(bitSet.stream().count()).isEqualTo(10);
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,9 +1,15 @@
package com.baeldung.concurrent.prioritytaskexecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Job implements Runnable {
private String jobName;
private JobPriority jobPriority;
private static final Logger LOGGER = LoggerFactory.getLogger(Job.class);
private final String jobName;
private final JobPriority jobPriority;
public Job(String jobName, JobPriority jobPriority) {
this.jobName = jobName;
this.jobPriority = jobPriority != null ? jobPriority : JobPriority.MEDIUM;
@ -16,8 +22,7 @@ public class Job implements Runnable {
@Override
public void run() {
try {
System.out.println("Job:" + jobName +
" Priority:" + jobPriority);
LOGGER.debug("Job:{} Priority:{}", jobName, jobPriority);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}

View File

@ -1,19 +1,21 @@
package com.baeldung.forkjoin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
import java.util.logging.Logger;
public class CustomRecursiveAction extends RecursiveAction {
final Logger logger = LoggerFactory.getLogger(CustomRecursiveAction.class);
private String workLoad = "";
private static final int THRESHOLD = 4;
private static Logger logger = Logger.getAnonymousLogger();
public CustomRecursiveAction(String workLoad) {
this.workLoad = workLoad;
}
@ -43,7 +45,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private void processing(String work) {
String result = work.toUpperCase();
logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread()
logger.debug("This result - (" + result + ") - was processed by " + Thread.currentThread()
.getName());
}
}

View File

@ -3,9 +3,9 @@ package com.baeldung.concurrent.prioritytaskexecution;
import org.junit.Test;
public class PriorityJobSchedulerUnitTest {
private static int POOL_SIZE = 1;
private static int QUEUE_SIZE = 10;
private static final int POOL_SIZE = 1;
private static final int QUEUE_SIZE = 10;
@Test
public void whenMultiplePriorityJobsQueued_thenHighestPriorityJobIsPicked() {
Job job1 = new Job("Job1", JobPriority.LOW);
@ -14,19 +14,19 @@ public class PriorityJobSchedulerUnitTest {
Job job4 = new Job("Job4", JobPriority.MEDIUM);
Job job5 = new Job("Job5", JobPriority.LOW);
Job job6 = new Job("Job6", JobPriority.HIGH);
PriorityJobScheduler pjs = new PriorityJobScheduler(POOL_SIZE, QUEUE_SIZE);
pjs.scheduleJob(job1);
pjs.scheduleJob(job2);
pjs.scheduleJob(job3);
pjs.scheduleJob(job4);
pjs.scheduleJob(job5);
pjs.scheduleJob(job6);
// ensure no tasks is pending before closing the scheduler
while (pjs.getQueuedTaskCount() != 0);
// delay to avoid job sleep (added for demo) being interrupted
try {
Thread.sleep(2000);
@ -34,7 +34,7 @@ public class PriorityJobSchedulerUnitTest {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
pjs.closeScheduler();
}
}

View File

@ -1,18 +1,15 @@
package com.baeldung.forkjoin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.baeldung.forkjoin.util.PoolUtil;
import org.junit.Before;
import org.junit.Test;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.forkjoin.CustomRecursiveAction;
import com.baeldung.forkjoin.CustomRecursiveTask;
import com.baeldung.forkjoin.util.PoolUtil;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class Java8ForkJoinIntegrationTest {
@ -63,11 +60,11 @@ public class Java8ForkJoinIntegrationTest {
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.execute(customRecursiveTask);
int result = customRecursiveTask.join();
customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
forkJoinPool.submit(customRecursiveTask);
int resultTwo = customRecursiveTask.join();
customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
}

View File

@ -1,12 +1,12 @@
package com.baeldung.thread.join;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Demonstrates Thread.join behavior.
@ -14,55 +14,55 @@ import org.junit.Test;
*/
public class ThreadJoinUnitTest {
final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadJoinUnitTest.class);
class SampleThread extends Thread {
public int processingCount = 0;
static class SampleThread extends Thread {
public int processingCount;
SampleThread(int processingCount) {
this.processingCount = processingCount;
LOGGER.info("Thread " + this.getName() + " created");
LOGGER.debug("Thread " + this.getName() + " created");
}
@Override
public void run() {
LOGGER.info("Thread " + this.getName() + " started");
LOGGER.debug("Thread " + this.getName() + " started");
while (processingCount > 0) {
try {
Thread.sleep(1000); // Simulate some work being done by thread
} catch (InterruptedException e) {
LOGGER.info("Thread " + this.getName() + " interrupted.");
LOGGER.debug("Thread " + this.getName() + " interrupted.");
}
processingCount--;
LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
LOGGER.debug("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
}
LOGGER.info("Thread " + this.getName() + " exiting");
LOGGER.debug("Thread " + this.getName() + " exiting");
}
}
@Test
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
Thread t1 = new SampleThread(0);
LOGGER.info("Invoking join.");
LOGGER.debug("Invoking join.");
t1.join();
LOGGER.info("Returned from join");
LOGGER.info("Thread state is" + t1.getState());
LOGGER.debug("Returned from join");
LOGGER.debug("Thread state is" + t1.getState());
assertFalse(t1.isAlive());
}
@Test
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
throws InterruptedException {
Thread t2 = new SampleThread(1);
t2.start();
LOGGER.info("Invoking join.");
LOGGER.debug("Invoking join.");
t2.join();
LOGGER.info("Returned from join");
LOGGER.debug("Returned from join");
assertFalse(t2.isAlive());
}
@Test
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
throws InterruptedException {
Thread t3 = new SampleThread(10);
t3.start();
@ -72,18 +72,18 @@ public class ThreadJoinUnitTest {
@Test
@Ignore
public void givenThreadTerminated_checkForEffect_notGuaranteed()
public void givenThreadTerminated_checkForEffect_notGuaranteed()
throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
//not guaranteed to stop even if t4 finishes.
do {
} while (t4.processingCount > 0);
} while (t4.processingCount > 0);
}
@Test
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

View File

@ -12,7 +12,6 @@ This module contains articles about basic Java concurrency
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
- [Set the Name of a Thread in Java](https://www.baeldung.com/java-set-thread-name)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)
- [[<-- Prev]](../core-java-concurrency-basic)[[Next -->]](../core-java-concurrency-basic-3)

View File

@ -0,0 +1,70 @@
package com.baeldung.concurrent.threads.name;
public class CustomThreadName {
public int currentNumber = 1;
public int N = 5;
public static void main(String[] args) {
CustomThreadName test = new CustomThreadName();
Thread oddThread = new Thread(() -> {
test.printOddNumber();
// Uncomment below to set thread name using setName() Method
// Thread.currentThread().setName("ODD");
}, "ODD");
// or Uncomment below to set thread name using setName() Method
// oddThread.setName("ODD");
Thread evenThread = new Thread(() -> {
test.printEvenNumber();
// Uncomment below to set thread name using setName() Method
// Thread.currentThread().setName("EVEN");
}, "EVEN");
// evenThread.setName("EVEN");
evenThread.start();
oddThread.start();
}
public void printEvenNumber() {
synchronized (this) {
while (currentNumber < N) {
while (currentNumber % 2 == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + " --> " + currentNumber);
currentNumber++;
notify();
}
}
}
public void printOddNumber() {
synchronized (this) {
while (currentNumber < N) {
while (currentNumber % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + " --> " + currentNumber);
currentNumber++;
notify();
}
}
}
}

View File

@ -7,12 +7,6 @@
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

View File

@ -0,0 +1,8 @@
## Core Java Concurrency Basic
This module contains articles about basic Java concurrency.
### Relevant Articles:
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [[<-- Prev]](../core-java-concurrency-basic-2)

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-concurrency-basic-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-concurrency-basic-3</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<finalName>core-java-concurrency-basic-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,7 +1,7 @@
package com.baeldung.concurrent.interrupt;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
@ -9,23 +9,23 @@ public class InterruptExampleUnitTest {
@Test
public void whenPropagateException_thenThrowsInterruptedException() {
assertThrows(InterruptedException.class, () -> InterruptExample.propagateException());
assertThrows(InterruptedException.class, InterruptExample::propagateException);
}
@Test
public void whenRestoreTheState_thenReturnsTrue() {
assertTrue(InterruptExample.restoreTheState());
}
@Test
public void whenThrowCustomException_thenContainsExpectedMessage() {
Exception exception = assertThrows(CustomInterruptedException.class, () -> InterruptExample.throwCustomException());
Exception exception = assertThrows(CustomInterruptedException.class, InterruptExample::throwCustomException);
String expectedMessage = "This thread was interrupted";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
@Test
public void whenHandleWithCustomException_thenReturnsTrue() throws CustomInterruptedException{
assertTrue(InterruptExample.handleWithCustomException());

View File

@ -2,4 +2,5 @@
- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.exceptions</groupId>
<artifactId>core-java-exceptions-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-exceptions-4</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<!-- Comment the arg below to print complete stack trace information -->
<!-- <arg>-g:none</arg>-->
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<h2.version>1.4.191</h2.version>
</properties>
</project>

View File

@ -0,0 +1,31 @@
package com.baeldung.exception.arrayindexoutofbounds;
import java.util.Arrays;
import java.util.List;
public class ArrayIndexOutOfBoundsExceptionDemo {
public static void main(String[] args) {
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
getArrayElementAtIndex(numbers, 5);
getListElementAtIndex(5);
addArrayElementsUsingLoop(numbers);
}
public static void addArrayElementsUsingLoop(int[] numbers) {
int sum = 0;
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
}
public static int getListElementAtIndex(int index) {
List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5);
return numbersList.get(index);
}
public static int getArrayElementAtIndex(int[] numbers, int index) {
return numbers[index];
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.exception.arrayindexoutofbounds;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class ArrayIndexOutOfBoundsExceptionDemoUnitTest {
private static int[] numbers;
@BeforeAll
public static void setUp() {
numbers = new int[] { 1, 2, 3, 4, 5 };
}
@Test
void givenAnArrayOfSizeFive_whenAccessedElementBeyondRange_thenShouldThrowArrayIndexOutOfBoundsException() {
assertThrows(ArrayIndexOutOfBoundsException.class,
() -> ArrayIndexOutOfBoundsExceptionDemo.addArrayElementsUsingLoop(numbers));
}
@Test
void givenAnArrayOfSizeFive_whenAccessedAnElementAtIndexEqualToSize_thenShouldThrowArrayIndexOutOfBoundsException() {
assertThrows(ArrayIndexOutOfBoundsException.class,
() -> ArrayIndexOutOfBoundsExceptionDemo.getArrayElementAtIndex(numbers, 5));
}
@Test
void givenAListReturnedByArraysAsListMethod_whenAccessedAnElementAtIndexEqualToSize_thenShouldThrowArrayIndexOutOfBoundsException() {
assertThrows(ArrayIndexOutOfBoundsException.class,
() -> ArrayIndexOutOfBoundsExceptionDemo.getListElementAtIndex(5));
}
}

View File

@ -1,6 +0,0 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -1,9 +0,0 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

View File

@ -7,13 +7,8 @@
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<logger name="net.sf.jmimemagic" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

View File

@ -3,3 +3,4 @@
- [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi)
- [LDAP Authentication Using Pure Java](https://www.baeldung.com/java-ldap-auth)
- [Testing LDAP Connections With Java](https://www.baeldung.com/java-test-ldap-connections)

View File

@ -1,4 +1,6 @@
/target/
.settings/
.classpath
.project
.project
*.log

View File

@ -10,3 +10,4 @@ This module contains article about constructors in Java
- [Throwing Exceptions in Constructors](https://www.baeldung.com/java-constructors-exceptions)
- [Constructors in Java Abstract Classes](https://www.baeldung.com/java-abstract-classes-constructors)
- [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error)
- [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification)

View File

@ -11,4 +11,5 @@ This module contains articles about core Java non-blocking input and output (IO)
- [How to Lock a File in Java](https://www.baeldung.com/java-lock-files)
- [Java NIO DatagramChannel](https://www.baeldung.com/java-nio-datagramchannel)
- [Java Path vs File](https://www.baeldung.com/java-path-vs-file)
- [What Is the Difference Between NIO and NIO.2?](https://www.baeldung.com/java-nio-vs-nio-2)
- [[<-- Prev]](/core-java-modules/core-java-nio)

View File

@ -0,0 +1,70 @@
package com.baeldung.niovsnio2;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
public class NioVsNio2UnitTest {
@Test
public void readFromFileUsingFileIO() throws Exception {
File file = new File("src/test/resources/nio-vs-nio2.txt");
FileInputStream in = new FileInputStream(file);
StringBuilder content = new StringBuilder();
int data = in.read();
while (data != -1) {
content.append((char) data);
data = in.read();
}
in.close();
assertThat(content.toString()).isEqualTo("Hello from file!");
}
@Test
public void readFromFileUsingFileChannel() throws Exception {
RandomAccessFile file = new RandomAccessFile("src/test/resources/nio-vs-nio2.txt", "r");
FileChannel channel = file.getChannel();
StringBuilder content = new StringBuilder();
ByteBuffer buffer = ByteBuffer.allocate(256);
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
content.append((char) buffer.get());
}
buffer.clear();
bytesRead = channel.read(buffer);
}
file.close();
assertThat(content.toString()).isEqualTo("Hello from file!");
}
@Test
public void readFromFileUsingNIO2() throws Exception {
List<String> strings = Files.readAllLines(Paths.get("src/test/resources/nio-vs-nio2.txt"));
assertThat(strings.get(0)).isEqualTo("Hello from file!");
}
@Test
public void listFilesUsingWalk() throws Exception {
Path path = Paths.get("src/test");
Stream<Path> walk = Files.walk(path);
walk.forEach(System.out::println);
}
}

View File

@ -0,0 +1 @@
Hello from file!

View File

@ -8,4 +8,6 @@ This module contains articles about core Java Security
- [Enabling Unlimited Strength Cryptography in Java](https://www.baeldung.com/jce-enable-unlimited-strength)
- [Initialization Vector for Encryption](https://www.baeldung.com/java-encryption-iv)
- [HMAC in Java](https://www.baeldung.com/java-hmac)
- [Generating a Secure AES Key in Java](https://www.baeldung.com/java-secure-aes-key)
- [Computing an X509 Certificates Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)

View File

@ -1,14 +1,29 @@
package com.baeldung.externalizable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ExternalizableUnitTest {
private final static String OUTPUT_FILE = "externalizable.txt";
private final static String OUTPUT_FILE_NAME = "externalizable.txt";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private File outputFile;
@Before
public void setUp() throws Exception {
outputFile = tempFolder.newFile(OUTPUT_FILE_NAME);
}
@Test
public void whenSerializing_thenUseExternalizable() throws IOException, ClassNotFoundException {
@ -18,7 +33,7 @@ public class ExternalizableUnitTest {
c.setCode(374);
c.setName("Armenia");
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
c.writeExternal(objectOutputStream);
@ -26,7 +41,7 @@ public class ExternalizableUnitTest {
objectOutputStream.close();
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
FileInputStream fileInputStream = new FileInputStream(outputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Country c2 = new Country();
@ -35,8 +50,8 @@ public class ExternalizableUnitTest {
objectInputStream.close();
fileInputStream.close();
assertTrue(c2.getCode() == c.getCode());
assertTrue(c2.getName().equals(c.getName()));
assertEquals(c2.getCode(), c.getCode());
assertEquals(c2.getName(), c.getName());
}
@Test
@ -49,7 +64,7 @@ public class ExternalizableUnitTest {
r.setClimate("Mediterranean");
r.setPopulation(120.000);
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
r.writeExternal(objectOutputStream);
@ -57,7 +72,7 @@ public class ExternalizableUnitTest {
objectOutputStream.close();
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
FileInputStream fileInputStream = new FileInputStream(outputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Region r2 = new Region();
@ -66,6 +81,6 @@ public class ExternalizableUnitTest {
objectInputStream.close();
fileInputStream.close();
assertTrue(r2.getPopulation() == null);
assertNull(r2.getPopulation());
}
}

View File

@ -1,36 +1,54 @@
package com.baeldung.serialization;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PersonUnitTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private File outputFile;
private File outputFile2;
@Before
public void setUp() throws Exception {
outputFile = tempFolder.newFile("yourfile.txt");
outputFile2 = tempFolder.newFile("yourfile2.txt");
}
@Test
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
Person p = new Person();
p.setAge(20);
p.setName("Joe");
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(p);
objectOutputStream.flush();
objectOutputStream.close();
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
FileInputStream fileInputStream = new FileInputStream(outputFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Person p2 = (Person) objectInputStream.readObject();
objectInputStream.close();
assertTrue(p2.getAge() == p.getAge());
assertTrue(p2.getName().equals(p.getName()));
assertEquals(p2.getAge(), p.getAge());
assertEquals(p2.getName(), p.getName());
}
@Test
@ -46,19 +64,19 @@ public class PersonUnitTest {
e.setPerson(p);
e.setAddress(a);
FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
FileOutputStream fileOutputStream = new FileOutputStream(outputFile2);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(e);
objectOutputStream.flush();
objectOutputStream.close();
FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
FileInputStream fileInputStream = new FileInputStream(outputFile2);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Employee e2 = (Employee) objectInputStream.readObject();
objectInputStream.close();
assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
assertEquals(e2.getPerson().getAge(), e.getPerson().getAge());
assertEquals(e2.getAddress().getHouseNumber(), (e.getAddress().getHouseNumber()));
}
}

View File

@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@ -13,17 +14,32 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.baeldung.util.MySerializationUtils;
import org.junit.rules.TemporaryFolder;
public class SerializationUnitTest {
private final static String OUTPUT_FILE_NAME = "yourfile.txt";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private File outputFile;
@Before
public void setUp() throws Exception {
outputFile = tempFolder.newFile(OUTPUT_FILE_NAME);
}
@Test(expected = NotSerializableException.class)
public void whenSerializing_ThenThrowsError() throws IOException {
Address address = new Address();
address.setHouseNumber(10);
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
objectOutputStream.writeObject(address);
}
@ -35,12 +51,12 @@ public class SerializationUnitTest {
p.setAge(20);
p.setName("Joe");
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
objectOutputStream.writeObject(p);
}
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
FileInputStream fileInputStream = new FileInputStream(outputFile);
try (ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
Person p2 = (Person) objectInputStream.readObject();
assertEquals(p2.getAge(), p.getAge());

View File

@ -4,6 +4,7 @@ This module contains articles about string-related algorithms.
### Relevant Articles:
- [Generating a Java String of N Repeated Characters](https://www.baeldung.com/java-string-of-repeated-characters)
- [Check if Two Strings are Anagrams in Java](https://www.baeldung.com/java-strings-anagrams)
- [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex)
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)

View File

@ -49,8 +49,9 @@
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<validator.version>1.7</validator.version>
<apache-commons-lang3.version>3.12.0</apache-commons-lang3.version>
</properties>
</project>

View File

@ -19,6 +19,18 @@ class RepeatedCharacterStringUnitTest {
private static final String EXPECTED_STRING = "aaaaaaa";
private static final int N = 7;
@Test
void givenSingleCharacterString_whenRepeat_thenStringCreated() {
String newString = "a".repeat(N);
assertEquals(EXPECTED_STRING, newString);
}
@Test
void givenMultiCharacterString_whenRepeat_thenStringCreated() {
String newString = "-->".repeat(5);
assertEquals("-->-->-->-->-->", newString);
}
@Test
void givenString_whenStringBuilderUsed_thenStringCreated() {
StringBuilder builder = new StringBuilder(N);

View File

@ -1,3 +1,4 @@
## Relevant Articles
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
- [Importing Maven Project into Eclipse](https://www.baeldung.com/maven-import-eclipse)

View File

@ -46,6 +46,7 @@
<module>core-java-concurrency-advanced-4</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-basic-2</module>
<module>core-java-concurrency-basic-3</module>
<module>core-java-concurrency-collections</module>
<module>core-java-concurrency-collections-2</module>
<module>core-java-console</module>
@ -55,6 +56,7 @@
<module>core-java-exceptions</module>
<module>core-java-exceptions-2</module>
<module>core-java-exceptions-3</module>
<module>core-java-exceptions-4</module>
<module>core-java-function</module>
<module>core-java-functional</module>
<module>core-java-io</module>
@ -107,7 +109,6 @@
<module>core-java-streams-4</module>
<module>core-java-string-algorithms</module>
<module>core-java-string-algorithms-2</module>
<module>core-java-string-algorithms-3</module>
<module>core-java-string-apis</module>
<module>core-java-string-conversions</module>
<module>core-java-string-conversions-2</module>

View File

@ -5,4 +5,5 @@ This module contains articles about Feign
### Relevant Articles:
- [Intro to Feign](https://www.baeldung.com/intro-to-feign)
- [Retrying Feign Calls](https://www.baeldung.com/feign-retry)

View File

@ -0,0 +1,27 @@
package com.baeldung.feign.retry;
import feign.FeignException;
import feign.Response;
import feign.RetryableException;
import feign.codec.ErrorDecoder;
import static feign.FeignException.errorStatus;
public class Custom5xxErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
FeignException exception = errorStatus(methodKey, response);
int status = response.status();
if (status >= 500) {
return new RetryableException(
response.status(),
exception.getMessage(),
response.request().httpMethod(),
exception,
null,
response.request());
}
return exception;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.feign.retry;
import feign.RetryableException;
import feign.Retryer;
public class NaiveRetryer implements feign.Retryer {
@Override
public void continueOrPropagate(RetryableException e) {
try {
Thread.sleep(1000L);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw e;
}
}
@Override
public Retryer clone() {
return new NaiveRetryer();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.feign.retry;
import com.baeldung.feign.clients.BookClient;
import feign.Feign;
import feign.Logger;
import feign.Retryer;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.okhttp.OkHttpClient;
import feign.slf4j.Slf4jLogger;
import lombok.Getter;
import java.util.concurrent.TimeUnit;
@Getter
public class ResilientFeignClientBuilder {
public BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
public static <T> T createClient(Class<T> type, String uri) {
return Feign.builder()
.client(new OkHttpClient())
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.retryer(new Retryer.Default(100L, TimeUnit.SECONDS.toMillis(3L), 5))
.errorDecoder(new Custom5xxErrorDecoder())
.target(type, uri);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.feign.retry;
import feign.*;
import feign.codec.ErrorDecoder;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class Custom5xxErrorDecoderUnitTest {
@Test
public void given5xxResponse_whenDecode_thenReturnRetryableException() {
// given
ErrorDecoder decoder = new Custom5xxErrorDecoder();
Response response = responseStub(500);
// when
Exception exception = decoder.decode("GET", response);
// then
assertTrue(exception instanceof RetryableException);
}
@Test
public void given4xxResponse_whenDecode_thenReturnFeignException() {
// given
ErrorDecoder decoder = new Custom5xxErrorDecoder();
Response response = responseStub(400);
// when
Exception exception = decoder.decode("GET", response);
// then
assertTrue(exception instanceof FeignException);
assertFalse(exception instanceof RetryableException);
}
@NotNull
private Response responseStub(int status) {
return Response.builder()
.request(Request.create(
Request.HttpMethod.GET, "url", new HashMap<>(), new byte[0], Charset.defaultCharset(), new RequestTemplate()))
.status(status)
.build();
}
}

View File

@ -0,0 +1,3 @@
## Relevant Articles:
[Convert a Maven Build to Gradle](https://www.baeldung.com/maven-convert-to-gradle)

View File

@ -0,0 +1,7 @@
## GraphQL Domain Graph Service (DGS)
This module contains articles about GraphQL using the Netflix Domain Graph Service (DGS).
## Relevant articles:
- [An Introduction to Domain Graph Service (DGS) Framework](https://www.baeldung.com/spring-boot-domain-graph-service)

View File

@ -0,0 +1,91 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.graphql-dgs</groupId>
<artifactId>graphql-dgs</artifactId>
<version>1.0</version>
<name>graphql-dgs</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.netflix.graphql.dgs</groupId>
<artifactId>graphql-dgs-platform-dependencies</artifactId>
<version>4.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.netflix.graphql.dgs.codegen</groupId>
<artifactId>graphql-dgs-codegen-client-core</artifactId>
<version>5.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.netflix.graphql.dgs</groupId>
<artifactId>graphql-dgs-spring-boot-starter</artifactId>
<version>4.9.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.2</version>
</plugin>
<plugin>
<groupId>io.github.deweyjose</groupId>
<artifactId>graphqlcodegen-maven-plugin</artifactId>
<version>1.14</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaPaths>
<param>src/main/resources/schema/schema.graphqls</param>
</schemaPaths>
<packageName>com.bealdung.graphqldgs.generated</packageName>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,25 @@
package com.bealdung.graphqlDGS;
public class Album {
private final String title;
private final String artist;
private final Integer recordNo;
public Album(String title, String artist, Integer recordNo) {
this.title = title;
this.recordNo = recordNo;
this.artist = artist;
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public Integer getRecordNo() {
return recordNo;
}
}

View File

@ -0,0 +1,28 @@
package com.bealdung.graphqlDGS;
import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsQuery;
import com.netflix.graphql.dgs.InputArgument;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@DgsComponent
public class AlbumsDataFetcher {
private final List<Album> albums = Arrays.asList(
new Album("Rumours", "Fleetwood Mac", 20),
new Album("What's Going On", "Marvin Gaye", 10),
new Album("Pet Sounds", "The Beach Boys", 12)
);
@DgsQuery
public List<Album> albums(@InputArgument String titleFilter) {
if(titleFilter == null) {
return albums;
}
return albums.stream()
.filter(s -> s.getTitle().contains(titleFilter))
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,13 @@
package com.bealdung.graphqlDGS;
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);
}
}

View File

@ -0,0 +1 @@
server.servlet.context-path=

View File

@ -0,0 +1,9 @@
type Query {
albums(titleFilter: String): [Album]
}
type Album {
title: String
artist: String
recordNo: Int
}

View File

@ -6,3 +6,4 @@
- [Optimizing HashMaps Performance](https://www.baeldung.com/java-hashmap-optimize-performance)
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)

View File

@ -24,7 +24,7 @@ public class YahooQuoteManagerImpl implements QuoteManager {
StringBuilder sb = new StringBuilder();
Currency.getAvailableCurrencies().forEach(currency -> {
if (!currency.equals(currency.getCurrencyCode())) {
if (!baseCurrency.equals(currency.getCurrencyCode())) {
sb.append(baseCurrency).append(currency.getCurrencyCode()).append("=X").append(",");
}
});

View File

@ -3,6 +3,8 @@
This module contains articles about JavaFX.
### Relevant Articles:
- [Introduction to JavaFX](https://www.baeldung.com/javafx)
- [Display Custom Items in JavaFX ListView](https://www.baeldung.com/javafx-listview-display-custom-items)
- [Adding EventHandler to JavaFX Button](https://www.baeldung.com/javafx-button-eventhandler)

View File

@ -0,0 +1,64 @@
package com.baeldung.button.eventhandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Font;
public class ButtonEventHandlerController {
private static final Logger logger = LoggerFactory.getLogger(ButtonEventHandlerController.class);
@FXML
private Button button;
@FXML
private Label label;
@FXML
private void initialize() {
button.setText("Click me");
handleClickEvent();
handleHoverEffect();
reuseRightClickEventHandler();
}
private void handleClickEvent() {
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
logger.info("OnAction {}", event);
}
});
button.setOnAction(event -> logger.info("OnAction {}", event));
button.setOnAction(event -> logger.info("OnAction2 {}", event));
}
private void handleHoverEffect() {
Effect shadow = new DropShadow();
button.setOnMouseEntered(e -> button.setEffect(shadow));
button.setOnMouseExited(e -> button.setEffect(null));
}
private void reuseRightClickEventHandler() {
EventHandler<MouseEvent> rightClickHandler = event -> {
if (MouseButton.SECONDARY.equals(event.getButton())) {
button.setFont(new Font(button.getFont()
.getSize() + 1));
}
};
button.setOnMousePressed(rightClickHandler);
label.setOnMousePressed(rightClickHandler);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.button.eventhandler;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/button_event-handler.fxml"));
Pane page = loader.load();
primaryStage.setTitle("Button event handler");
primaryStage.setScene(new Scene(page));
primaryStage.show();
}
}

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane xmlns:fx="http://javafx.com/fxml"
xmlns="http://javafx.com/javafx"
fx:controller="com.baeldung.button.eventhandler.ButtonEventHandlerController"
prefHeight="200.0" prefWidth="300.0">
<center>
<Button fx:id="button" HBox.hgrow="ALWAYS"/>
</center>
<bottom>
<Label fx:id="label" text="Test label"/>
</bottom>
</BorderPane>

View File

@ -15,7 +15,7 @@
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
@ -36,10 +36,45 @@
</dependency>
</dependencies>
<!-- uncomment in order to enable Hibernate Validator Anotation Processor -->
<!--
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<fork>true</fork>
<compilerArgs>
<arg>-Averbose=true</arg>
<arg>-AmethodConstraintsSupported=true</arg>
<arg>-AdiagnosticKind=ERROR</arg>
</compilerArgs>
<annotationProcessorPaths>
<path>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.ap.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
-->
<properties>
<hibernate-validator.version>6.0.13.Final</hibernate-validator.version>
<hibernate-validator.ap.version>6.2.0.Final</hibernate-validator.ap.version>
<maven.compiler.version>3.6.1</maven.compiler.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<javax.el.version>3.0.0</javax.el.version>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,95 @@
package com.baeldung.javaxval.hibernate.validator.ap;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import java.util.List;
import java.util.Optional;
public class Message {
@NotNull(message = "Content cannot be null")
private String content;
private boolean isDelivered;
private List<@NotBlank String> recipients;
// uncomment in order to trigger AP annotation detection
// The annotation @Past is disallowed for this data type.
// @Past
private String createdAt;
public String getContent() {
return content;
}
public Message(String content, boolean isDelivered, List<@NotBlank String> recipients, String createdAt) {
this.content = content;
this.isDelivered = isDelivered;
this.recipients = recipients;
this.createdAt = createdAt;
}
// uncomment in order to trigger AP annotation detection
// The annotation @Min is disallowed for the return type of this method.
// @Min(3)
public boolean broadcast() {
// setup a logic
// to send to recipients
return true;
}
// uncomment in order to trigger AP annotation detection
// Void methods may not be annotated with constraint annotations.
// @NotNull
public void archive() {
// archive the message
}
// uncomment in order to trigger AP annotation detection
// Constraint annotations must not be specified at methods, which are no valid JavaBeans getter methods.
// NOTE: add <arg>-AmethodConstraintsSupported=false</arg> to compiler args before
// @AssertTrue
public boolean delete() {
// delete the message
return false;
}
public void setContent(String content) {
this.content = content;
}
public boolean isDelivered() {
return isDelivered;
}
public void setDelivered(boolean delivered) {
isDelivered = delivered;
}
public List<String> getRecipients() {
return recipients;
}
public void setRecipients(List<String> recipients) {
this.recipients = recipients;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getName() {
return content;
}
public void setName(String content) {
this.content = content;
}
public Optional<@Past String> getCreatedAt() {
return Optional.ofNullable(createdAt);
}
}

View File

@ -1,48 +1,48 @@
package com.baeldung.jaxb.gen;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.baeldung.jaxb.gen package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link UserRequest }
*
*/
public UserRequest createUserRequest() {
return new UserRequest();
}
/**
* Create an instance of {@link UserResponse }
*
*/
public UserResponse createUserResponse() {
return new UserResponse();
}
}
package com.baeldung.jaxb.gen;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.baeldung.jaxb.gen package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link UserRequest }
*
*/
public UserRequest createUserRequest() {
return new UserRequest();
}
/**
* Create an instance of {@link UserResponse }
*
*/
public UserResponse createUserResponse() {
return new UserResponse();
}
}

View File

@ -1,87 +1,87 @@
package com.baeldung.jaxb.gen;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for UserRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="UserRequest"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserRequest", propOrder = {
"id",
"name"
})
@XmlRootElement(name = "userRequest")
public class UserRequest
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
package com.baeldung.jaxb.gen;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for UserRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="UserRequest"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserRequest", propOrder = {
"id",
"name"
})
@XmlRootElement(name = "userRequest")
public class UserRequest
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}

View File

@ -1,149 +1,149 @@
package com.baeldung.jaxb.gen;
import java.io.Serializable;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.w3._2001.xmlschema.Adapter1;
/**
* <p>Java class for UserResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="UserResponse"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserResponse", propOrder = {
"id",
"name",
"gender",
"created"
})
@XmlRootElement(name = "userResponse")
public class UserResponse
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String gender;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter1 .class)
@XmlSchemaType(name = "dateTime")
protected Calendar created;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the gender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGender() {
return gender;
}
/**
* Sets the value of the gender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGender(String value) {
this.gender = value;
}
/**
* Gets the value of the created property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getCreated() {
return created;
}
/**
* Sets the value of the created property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreated(Calendar value) {
this.created = value;
}
}
package com.baeldung.jaxb.gen;
import java.io.Serializable;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.w3._2001.xmlschema.Adapter1;
/**
* <p>Java class for UserResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="UserResponse"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserResponse", propOrder = {
"id",
"name",
"gender",
"created"
})
@XmlRootElement(name = "userResponse")
public class UserResponse
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String gender;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter1 .class)
@XmlSchemaType(name = "dateTime")
protected Calendar created;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the gender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGender() {
return gender;
}
/**
* Sets the value of the gender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGender(String value) {
this.gender = value;
}
/**
* Gets the value of the created property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getCreated() {
return created;
}
/**
* Sets the value of the created property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreated(Calendar value) {
this.created = value;
}
}

View File

@ -1,2 +1,2 @@
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.baeldung.jaxb.gen;
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.baeldung.jaxb.gen;

View File

@ -1,23 +1,23 @@
package org.w3._2001.xmlschema;
import java.util.Calendar;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class Adapter1
extends XmlAdapter<String, Calendar>
{
public Calendar unmarshal(String value) {
return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
}
public String marshal(Calendar value) {
if (value == null) {
return null;
}
return (javax.xml.bind.DatatypeConverter.printDateTime(value));
}
}
package org.w3._2001.xmlschema;
import java.util.Calendar;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class Adapter1
extends XmlAdapter<String, Calendar>
{
public Calendar unmarshal(String value) {
return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
}
public String marshal(Calendar value) {
if (value == null) {
return null;
}
return (javax.xml.bind.DatatypeConverter.printDateTime(value));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.logging.log4j2threadinfo;
import java.util.stream.IntStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Log4j2ThreadInfo {
private static final Logger logger = LogManager.getLogger(Log4j2ThreadInfo.class);
public static void main(String[] args) {
IntStream.range(0, 5).forEach(i -> {
Runnable runnable = () -> logger.info("Logging info");
Thread thread = new Thread(runnable);
thread.start();
});
}
}

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Properties>
<Property name="LOG_PATTERN">
%d{yyyy-MM-dd HH:mm:ss.SSS} --- thread_id="%tid" thread_name="%tn" thread_priority="%tp" --- [%p] %m%n
</Property>
</Properties>
<Appenders>
<RollingFile name="RollingName" filename="logs/app.log"
filePattern="$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log">
<PatternLayout>
<Pattern>${LOG_PATTERN}</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="20MB"/>
</Policies>
</RollingFile>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.baeldung.logging.log4j2threadinfo" level="trace">
<AppenderRef ref="Console"/>
</Logger>
<Root level="error">
<AppenderRef ref="RollingName"/>
</Root>
</Loggers>
</Configuration>

View File

@ -88,7 +88,7 @@
<rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.6.1</spring-boot.version>
<spring-boot.version>2.6.3</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
</properties>

View File

@ -0,0 +1,65 @@
package com.baeldung.connectionstatus;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionValidation
{
public static Connection getConnection()
throws Exception
{
Class.forName("org.h2.Driver");
String url = "jdbc:h2:mem:testdb";
return DriverManager.getConnection(url, "user", "password");
}
public static void runIfOpened(Connection connection)
throws SQLException
{
if (connection != null && !connection.isClosed()) {
// run sql statements
}
else {
// handle closed connection
}
}
public static void runIfValid(Connection connection)
throws SQLException
{
// Try to validate connection with a 5 seconds timeout
if (connection.isValid(5)) {
// run sql statements
}
else {
// handle invalid connection
}
}
public static void runIfConnectionValid(Connection connection)
{
if (isConnectionValid(connection)) {
// run sql statements
}
else {
// handle invalid connection
}
}
public static boolean isConnectionValid(Connection connection)
{
try {
if (connection != null && !connection.isClosed()) {
// Running a simple validation query
connection.prepareStatement("SELECT 1");
return true;
}
}
catch (SQLException e) {
// log some useful data here
}
return false;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.connectionstatus;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ConnectionValidationUnitTest
{
@Test
void givenConnectionObject_whenCreated_thenIsNotClosed()
throws Exception
{
Connection connection = ConnectionValidation.getConnection();
assertNotNull(connection);
assertFalse(connection.isClosed());
}
@Test
void givenConnectionObject_whenCreated_thenIsValid()
throws Exception
{
Connection connection = ConnectionValidation.getConnection();
assertTrue(connection.isValid(0));
}
@Test
void givenConnectionObject_whenValidated_thenIsValid()
throws Exception
{
Connection connection = ConnectionValidation.getConnection();
assertTrue(ConnectionValidation.isConnectionValid(connection));
}
}

Some files were not shown because too many files have changed in this diff Show More