Merge branch 'eugenp:master' into master
This commit is contained in:
commit
af2536ed30
|
@ -27,3 +27,4 @@ HELP.md
|
|||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
|
@ -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|
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -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>
|
|
@ -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 {
|
||||
|
|
@ -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,19 +21,6 @@ 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 {
|
||||
|
@ -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);
|
|
@ -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() {
|
|
@ -1,3 +1,5 @@
|
|||
*.docx
|
||||
temp.xls
|
||||
temp.xlsx
|
||||
|
||||
CellStyleTest_output.xlsx
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -44,6 +44,7 @@ public class ExcelUtility {
|
|||
}
|
||||
}
|
||||
inputStream.close();
|
||||
baeuldungWorkBook.close();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -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 {
|
||||
|
||||
|
|
|
@ -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 {
|
||||
|
||||
|
|
|
@ -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";
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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,9 +12,12 @@ 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;
|
||||
|
||||
|
@ -25,6 +28,9 @@ 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
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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()) {
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
|
@ -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>
|
|
@ -1,8 +1,14 @@
|
|||
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;
|
||||
|
@ -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) {
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,8 +3,8 @@ 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() {
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
|
||||
|
|
|
@ -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,39 +14,39 @@ 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());
|
||||
}
|
||||
|
||||
|
@ -55,9 +55,9 @@ public class ThreadJoinUnitTest {
|
|||
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());
|
||||
}
|
||||
|
||||
|
|
|
@ -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>
|
|
@ -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)
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
||||
|
|
|
@ -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)
|
|
@ -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>
|
|
@ -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>
|
|
@ -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,7 +9,7 @@ public class InterruptExampleUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenPropagateException_thenThrowsInterruptedException() {
|
||||
assertThrows(InterruptedException.class, () -> InterruptExample.propagateException());
|
||||
assertThrows(InterruptedException.class, InterruptExample::propagateException);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -19,7 +19,7 @@ public class InterruptExampleUnitTest {
|
|||
|
||||
@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();
|
||||
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
|
@ -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];
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -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
|
|
@ -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
|
|
@ -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>
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -2,3 +2,5 @@
|
|||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
|
||||
*.log
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
Hello from 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 Certificate’s Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)
|
||||
|
|
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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()));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
|
@ -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);
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant Articles:
|
||||
|
||||
[Convert a Maven Build to Gradle](https://www.baeldung.com/maven-convert-to-gradle)
|
|
@ -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)
|
|
@ -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>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
server.servlet.context-path=
|
|
@ -0,0 +1,9 @@
|
|||
type Query {
|
||||
albums(titleFilter: String): [Album]
|
||||
}
|
||||
|
||||
type Album {
|
||||
title: String
|
||||
artist: String
|
||||
recordNo: Int
|
||||
}
|
|
@ -6,3 +6,4 @@
|
|||
- [Optimizing HashMap’s 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)
|
||||
|
|
|
@ -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(",");
|
||||
}
|
||||
});
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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,8 +36,43 @@
|
|||
</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>
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
});
|
||||
}
|
||||
}
|
|
@ -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>
|
|
@ -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>
|
||||
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,6 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Cassandra Batch in Cassandra Query Language and Java](https://www.baeldung.com/java-cql-cassandra-batch)
|
||||
- [A Guide to Cassandra with Java](http://www.baeldung.com/cassandra-with-java)
|
||||
- [Intro to DataStax Java Driver for Apache Cassandra](https://www.baeldung.com/cassandra-datastax-java-driver)
|
||||
- [CQL Data Types](https://www.baeldung.com/cassandra-data-types)
|
||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about MongoDB in Java.
|
|||
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
|
||||
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
|
||||
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
|
||||
- [Get Last Inserted Document ID in MongoDB With Java Driver](https://www.baeldung.com/java-mongodb-last-inserted-id)
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.mongo.objectid;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.bson.types.ObjectId;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
public class RetrieveIdExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase("myMongoDb");
|
||||
MongoCollection<Document> collection = database.getCollection("example");
|
||||
|
||||
// Create document with user-generated ID
|
||||
ObjectId generatedId = new ObjectId();
|
||||
|
||||
System.out.println(generatedId.toString());
|
||||
|
||||
Document document = new Document();
|
||||
document.put("_id", generatedId);
|
||||
document.put("name", "Shubham");
|
||||
document.put("company", "Baeldung");
|
||||
collection.insertOne(document);
|
||||
|
||||
// Check that the ID of the document is still the one we set
|
||||
System.out.println(document.getObjectId("_id").equals(generatedId));
|
||||
|
||||
|
||||
// Create a second document by injecting the ID in the constructor
|
||||
|
||||
ObjectId generatedId2 = ObjectId.get();
|
||||
|
||||
Document document2 = new Document("_id", generatedId2);
|
||||
document2.put("name", "Shubham");
|
||||
document2.put("company", "Baeldung");
|
||||
collection.insertOne(document2);
|
||||
|
||||
Date creationDate = generatedId.getDate();
|
||||
System.out.println(creationDate);
|
||||
|
||||
int timestamp = generatedId.getTimestamp();
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
System.out.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -47,8 +47,8 @@ public class SpringContextTest {
|
|||
}
|
||||
|
||||
@Before
|
||||
public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
|
||||
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<String, Object>());
|
||||
public void createTable() {
|
||||
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<>());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -1,17 +1,15 @@
|
|||
package com.baeldung.spring.data.cassandra.repository;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.baeldung.spring.data.cassandra.config.CassandraConfig;
|
||||
import com.baeldung.spring.data.cassandra.model.Book;
|
||||
import com.datastax.driver.core.Cluster;
|
||||
import com.datastax.driver.core.Session;
|
||||
import com.datastax.driver.core.utils.UUIDs;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import org.apache.cassandra.exceptions.ConfigurationException;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
import com.baeldung.spring.data.cassandra.config.CassandraConfig;
|
||||
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
|
@ -25,15 +23,24 @@ import org.springframework.data.cassandra.core.CassandraAdminOperations;
|
|||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.datastax.driver.core.Cluster;
|
||||
import com.datastax.driver.core.Session;
|
||||
import com.datastax.driver.core.utils.UUIDs;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
|
||||
/**
|
||||
* Live test for Cassandra testing.
|
||||
*
|
||||
* This can be converted to IntegrationTest once cassandra-unit tests can be executed in parallel and
|
||||
* multiple test servers started as part of test suite.
|
||||
*
|
||||
* Open cassandra-unit issue for parallel execution: https://github.com/jsevellec/cassandra-unit/issues/155
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = CassandraConfig.class)
|
||||
public class BookRepositoryIntegrationTest {
|
||||
private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class);
|
||||
public class BookRepositoryLiveTest {
|
||||
private static final Log LOGGER = LogFactory.getLog(BookRepositoryLiveTest.class);
|
||||
|
||||
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
|
||||
|
||||
|
@ -47,8 +54,6 @@ public class BookRepositoryIntegrationTest {
|
|||
@Autowired
|
||||
private CassandraAdminOperations adminTemplate;
|
||||
|
||||
//
|
||||
|
||||
@BeforeClass
|
||||
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
|
||||
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
|
||||
|
@ -62,8 +67,8 @@ public class BookRepositoryIntegrationTest {
|
|||
}
|
||||
|
||||
@Before
|
||||
public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
|
||||
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<String, Object>());
|
||||
public void createTable() {
|
||||
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<>());
|
||||
}
|
||||
|
||||
@Test
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue