Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
e50635ad82
@ -3,7 +3,8 @@ language: java
|
|||||||
before_install:
|
before_install:
|
||||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||||
|
|
||||||
install: travis_wait 60 mvn -q test -fae
|
install: skip
|
||||||
|
script: travis_wait 60 mvn -q test -fae
|
||||||
|
|
||||||
sudo: required
|
sudo: required
|
||||||
|
|
||||||
|
|||||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2017 Eugen Paraschiv
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@ -1,9 +1,14 @@
|
|||||||
|
|
||||||
The "REST with Spring" Classes
|
The "REST with Spring" Classes
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
|
And here's the Master Class of Learn Spring Security: <br/>
|
||||||
|
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Spring Tutorials
|
Spring Tutorials
|
||||||
================
|
================
|
||||||
|
|||||||
@ -15,3 +15,4 @@
|
|||||||
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
||||||
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
||||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||||
|
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||||
|
|||||||
@ -39,6 +39,12 @@
|
|||||||
<artifactId>jgrapht-core</artifactId>
|
<artifactId>jgrapht-core</artifactId>
|
||||||
<version>1.0.1</version>
|
<version>1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>3.9.0</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@ -0,0 +1,111 @@
|
|||||||
|
package com.baeldung.algorithms.kthlargest;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
public class FindKthLargest {
|
||||||
|
|
||||||
|
public int findKthLargestBySorting(Integer[] arr, int k) {
|
||||||
|
Arrays.sort(arr);
|
||||||
|
int targetIndex = arr.length - k;
|
||||||
|
return arr[targetIndex];
|
||||||
|
}
|
||||||
|
|
||||||
|
public int findKthLargestBySortingDesc(Integer[] arr, int k) {
|
||||||
|
Arrays.sort(arr, Collections.reverseOrder());
|
||||||
|
return arr[k - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
public int findKthElementByQuickSelect(Integer[] arr, int left, int right, int k) {
|
||||||
|
if (k >= 0 && k <= right - left + 1) {
|
||||||
|
int pos = partition(arr, left, right);
|
||||||
|
if (pos - left == k) {
|
||||||
|
return arr[pos];
|
||||||
|
}
|
||||||
|
if (pos - left > k) {
|
||||||
|
return findKthElementByQuickSelect(arr, left, pos - 1, k);
|
||||||
|
}
|
||||||
|
return findKthElementByQuickSelect(arr, pos + 1, right, k - pos + left - 1);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int findKthElementByQuickSelectWithIterativePartition(Integer[] arr, int left, int right, int k) {
|
||||||
|
if (k >= 0 && k <= right - left + 1) {
|
||||||
|
int pos = partitionIterative(arr, left, right);
|
||||||
|
if (pos - left == k) {
|
||||||
|
return arr[pos];
|
||||||
|
}
|
||||||
|
if (pos - left > k) {
|
||||||
|
return findKthElementByQuickSelectWithIterativePartition(arr, left, pos - 1, k);
|
||||||
|
}
|
||||||
|
return findKthElementByQuickSelectWithIterativePartition(arr, pos + 1, right, k - pos + left - 1);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int partition(Integer[] arr, int left, int right) {
|
||||||
|
int pivot = arr[right];
|
||||||
|
Integer[] leftArr;
|
||||||
|
Integer[] rightArr;
|
||||||
|
|
||||||
|
leftArr = IntStream.range(left, right)
|
||||||
|
.filter(i -> arr[i] < pivot)
|
||||||
|
.map(i -> arr[i])
|
||||||
|
.boxed()
|
||||||
|
.toArray(Integer[]::new);
|
||||||
|
|
||||||
|
rightArr = IntStream.range(left, right)
|
||||||
|
.filter(i -> arr[i] > pivot)
|
||||||
|
.map(i -> arr[i])
|
||||||
|
.boxed()
|
||||||
|
.toArray(Integer[]::new);
|
||||||
|
|
||||||
|
int leftArraySize = leftArr.length;
|
||||||
|
System.arraycopy(leftArr, 0, arr, left, leftArraySize);
|
||||||
|
arr[leftArraySize + left] = pivot;
|
||||||
|
System.arraycopy(rightArr, 0, arr, left + leftArraySize + 1, rightArr.length);
|
||||||
|
|
||||||
|
return left + leftArraySize;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int partitionIterative(Integer[] arr, int left, int right) {
|
||||||
|
int pivot = arr[right], i = left;
|
||||||
|
for (int j = left; j <= right - 1; j++) {
|
||||||
|
if (arr[j] <= pivot) {
|
||||||
|
swap(arr, i, j);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
swap(arr, i, right);
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int findKthElementByRandomizedQuickSelect(Integer[] arr, int left, int right, int k) {
|
||||||
|
if (k >= 0 && k <= right - left + 1) {
|
||||||
|
int pos = randomPartition(arr, left, right);
|
||||||
|
if (pos - left == k) {
|
||||||
|
return arr[pos];
|
||||||
|
}
|
||||||
|
if (pos - left > k) {
|
||||||
|
return findKthElementByRandomizedQuickSelect(arr, left, pos - 1, k);
|
||||||
|
}
|
||||||
|
return findKthElementByRandomizedQuickSelect(arr, pos + 1, right, k - pos + left - 1);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int randomPartition(Integer arr[], int left, int right) {
|
||||||
|
int n = right - left + 1;
|
||||||
|
int pivot = (int) (Math.random()) % n;
|
||||||
|
swap(arr, left + pivot, right);
|
||||||
|
return partition(arr, left, right);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void swap(Integer[] arr, int n1, int n2) {
|
||||||
|
int temp = arr[n2];
|
||||||
|
arr[n2] = arr[n1];
|
||||||
|
arr[n1] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,57 @@
|
|||||||
|
package com.baeldung.algorithms.kthlargest;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FindKthLargestUnitTest {
|
||||||
|
|
||||||
|
private FindKthLargest findKthLargest;
|
||||||
|
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
findKthLargest = new FindKthLargest();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
|
||||||
|
int k = 3;
|
||||||
|
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
|
||||||
|
int k = 3;
|
||||||
|
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
|
||||||
|
int k = 3;
|
||||||
|
int kthLargest = arr.length - k;
|
||||||
|
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
|
||||||
|
int k = 3;
|
||||||
|
int kthLargest = arr.length - k;
|
||||||
|
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
|
||||||
|
int k = 3;
|
||||||
|
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
|
||||||
|
int k = 3;
|
||||||
|
int kthLargest = arr.length - k;
|
||||||
|
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -9,7 +9,7 @@
|
|||||||
<url>http://maven.apache.org</url>
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -26,8 +26,8 @@
|
|||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.7.0</version>
|
<version>3.7.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.6</source>
|
<source>1.8</source>
|
||||||
<target>1.6</target>
|
<target>1.8</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
|||||||
@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<auto-service.version>1.0-rc2</auto-service.version>
|
<auto-service.version>1.0-rc2</auto-service.version>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|||||||
@ -0,0 +1,224 @@
|
|||||||
|
package com.baeldung.poi.powerpoint;
|
||||||
|
|
||||||
|
import org.apache.poi.sl.usermodel.AutoNumberingScheme;
|
||||||
|
import org.apache.poi.sl.usermodel.PictureData;
|
||||||
|
import org.apache.poi.sl.usermodel.TableCell;
|
||||||
|
import org.apache.poi.sl.usermodel.TextParagraph;
|
||||||
|
import org.apache.poi.util.IOUtils;
|
||||||
|
import org.apache.poi.xslf.usermodel.*;
|
||||||
|
|
||||||
|
import java.awt.*;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper class for the PowerPoint presentation creation
|
||||||
|
*/
|
||||||
|
public class PowerPointHelper {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read an existing presentation
|
||||||
|
*
|
||||||
|
* @param fileLocation
|
||||||
|
* File location of the presentation
|
||||||
|
* @return instance of {@link XMLSlideShow}
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
public XMLSlideShow readingExistingSlideShow(String fileLocation) throws IOException {
|
||||||
|
return new XMLSlideShow(new FileInputStream(fileLocation));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a sample presentation
|
||||||
|
*
|
||||||
|
* @param fileLocation
|
||||||
|
* File location of the presentation
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
public void createPresentation(String fileLocation) throws IOException {
|
||||||
|
// Create presentation
|
||||||
|
XMLSlideShow ppt = new XMLSlideShow();
|
||||||
|
|
||||||
|
XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
|
||||||
|
|
||||||
|
// Retriving the slide layout
|
||||||
|
XSLFSlideLayout layout = defaultMaster.getLayout(SlideLayout.TITLE_ONLY);
|
||||||
|
|
||||||
|
// Creating the 1st slide
|
||||||
|
XSLFSlide slide1 = ppt.createSlide(layout);
|
||||||
|
XSLFTextShape title = slide1.getPlaceholder(0);
|
||||||
|
// Clearing text to remove the predefined one in the template
|
||||||
|
title.clearText();
|
||||||
|
XSLFTextParagraph p = title.addNewTextParagraph();
|
||||||
|
|
||||||
|
XSLFTextRun r1 = p.addNewTextRun();
|
||||||
|
r1.setText("Baeldung");
|
||||||
|
r1.setFontColor(new Color(78, 147, 89));
|
||||||
|
r1.setFontSize(48.);
|
||||||
|
|
||||||
|
// Add Image
|
||||||
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
|
byte[] pictureData = IOUtils.toByteArray(new FileInputStream(classLoader.getResource("logo-leaf.png").getFile()));
|
||||||
|
|
||||||
|
XSLFPictureData pd = ppt.addPicture(pictureData, PictureData.PictureType.PNG);
|
||||||
|
XSLFPictureShape picture = slide1.createPicture(pd);
|
||||||
|
picture.setAnchor(new Rectangle(320, 230, 100, 92));
|
||||||
|
|
||||||
|
// Creating 2nd slide
|
||||||
|
layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
|
||||||
|
XSLFSlide slide2 = ppt.createSlide(layout);
|
||||||
|
|
||||||
|
// setting the tile
|
||||||
|
title = slide2.getPlaceholder(0);
|
||||||
|
title.clearText();
|
||||||
|
XSLFTextRun r = title.addNewTextParagraph().addNewTextRun();
|
||||||
|
r.setText("Baeldung");
|
||||||
|
|
||||||
|
// Adding the link
|
||||||
|
XSLFHyperlink link = r.createHyperlink();
|
||||||
|
link.setAddress("http://www.baeldung.com");
|
||||||
|
|
||||||
|
// setting the content
|
||||||
|
XSLFTextShape content = slide2.getPlaceholder(1);
|
||||||
|
content.clearText(); // unset any existing text
|
||||||
|
content.addNewTextParagraph().addNewTextRun().setText("First paragraph");
|
||||||
|
content.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
|
||||||
|
content.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
|
||||||
|
|
||||||
|
// Creating 3rd slide - List
|
||||||
|
layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
|
||||||
|
XSLFSlide slide3 = ppt.createSlide(layout);
|
||||||
|
title = slide3.getPlaceholder(0);
|
||||||
|
title.clearText();
|
||||||
|
r = title.addNewTextParagraph().addNewTextRun();
|
||||||
|
r.setText("Lists");
|
||||||
|
|
||||||
|
content = slide3.getPlaceholder(1);
|
||||||
|
content.clearText();
|
||||||
|
XSLFTextParagraph p1 = content.addNewTextParagraph();
|
||||||
|
p1.setIndentLevel(0);
|
||||||
|
p1.setBullet(true);
|
||||||
|
r1 = p1.addNewTextRun();
|
||||||
|
r1.setText("Bullet");
|
||||||
|
|
||||||
|
// the next three paragraphs form an auto-numbered list
|
||||||
|
XSLFTextParagraph p2 = content.addNewTextParagraph();
|
||||||
|
p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
|
||||||
|
p2.setIndentLevel(1);
|
||||||
|
XSLFTextRun r2 = p2.addNewTextRun();
|
||||||
|
r2.setText("Numbered List Item - 1");
|
||||||
|
|
||||||
|
// Creating 4th slide
|
||||||
|
XSLFSlide slide4 = ppt.createSlide();
|
||||||
|
createTable(slide4);
|
||||||
|
|
||||||
|
// Save presentation
|
||||||
|
FileOutputStream out = new FileOutputStream(fileLocation);
|
||||||
|
ppt.write(out);
|
||||||
|
out.close();
|
||||||
|
|
||||||
|
// Closing presentation
|
||||||
|
ppt.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a slide from the presentation
|
||||||
|
*
|
||||||
|
* @param ppt
|
||||||
|
* The presentation
|
||||||
|
* @param slideNumber
|
||||||
|
* The number of the slide to be deleted (0-based)
|
||||||
|
*/
|
||||||
|
public void deleteSlide(XMLSlideShow ppt, int slideNumber) {
|
||||||
|
ppt.removeSlide(slideNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-order the slides inside a presentation
|
||||||
|
*
|
||||||
|
* @param ppt
|
||||||
|
* The presentation
|
||||||
|
* @param slideNumber
|
||||||
|
* The number of the slide to move
|
||||||
|
* @param newSlideNumber
|
||||||
|
* The new position of the slide (0-base)
|
||||||
|
*/
|
||||||
|
public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) {
|
||||||
|
List<XSLFSlide> slides = ppt.getSlides();
|
||||||
|
|
||||||
|
XSLFSlide secondSlide = slides.get(slideNumber);
|
||||||
|
ppt.setSlideOrder(secondSlide, newSlideNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the placeholder inside a slide
|
||||||
|
*
|
||||||
|
* @param slide
|
||||||
|
* The slide
|
||||||
|
* @return List of placeholder inside a slide
|
||||||
|
*/
|
||||||
|
public List<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) {
|
||||||
|
List<XSLFShape> placeholders = new ArrayList<>();
|
||||||
|
|
||||||
|
for (XSLFShape shape : slide.getShapes()) {
|
||||||
|
if (shape instanceof XSLFAutoShape) {
|
||||||
|
placeholders.add(shape);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return placeholders;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a table
|
||||||
|
*
|
||||||
|
* @param slide
|
||||||
|
* Slide
|
||||||
|
*/
|
||||||
|
private void createTable(XSLFSlide slide) {
|
||||||
|
|
||||||
|
XSLFTable tbl = slide.createTable();
|
||||||
|
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
|
||||||
|
|
||||||
|
int numColumns = 3;
|
||||||
|
int numRows = 5;
|
||||||
|
|
||||||
|
// header
|
||||||
|
XSLFTableRow headerRow = tbl.addRow();
|
||||||
|
headerRow.setHeight(50);
|
||||||
|
for (int i = 0; i < numColumns; i++) {
|
||||||
|
XSLFTableCell th = headerRow.addCell();
|
||||||
|
XSLFTextParagraph p = th.addNewTextParagraph();
|
||||||
|
p.setTextAlign(TextParagraph.TextAlign.CENTER);
|
||||||
|
XSLFTextRun r = p.addNewTextRun();
|
||||||
|
r.setText("Header " + (i + 1));
|
||||||
|
r.setBold(true);
|
||||||
|
r.setFontColor(Color.white);
|
||||||
|
th.setFillColor(new Color(79, 129, 189));
|
||||||
|
th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);
|
||||||
|
th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);
|
||||||
|
// all columns are equally sized
|
||||||
|
tbl.setColumnWidth(i, 150);
|
||||||
|
}
|
||||||
|
|
||||||
|
// data
|
||||||
|
for (int rownum = 0; rownum < numRows; rownum++) {
|
||||||
|
XSLFTableRow tr = tbl.addRow();
|
||||||
|
tr.setHeight(50);
|
||||||
|
for (int i = 0; i < numColumns; i++) {
|
||||||
|
XSLFTableCell cell = tr.addCell();
|
||||||
|
XSLFTextParagraph p = cell.addNewTextParagraph();
|
||||||
|
XSLFTextRun r = p.addNewTextRun();
|
||||||
|
|
||||||
|
r.setText("Cell " + (i * rownum + 1));
|
||||||
|
if (rownum % 2 == 0) {
|
||||||
|
cell.setFillColor(new Color(208, 216, 232));
|
||||||
|
} else {
|
||||||
|
cell.setFillColor(new Color(233, 247, 244));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,77 @@
|
|||||||
|
package com.baeldung.poi.powerpoint;
|
||||||
|
|
||||||
|
import org.apache.poi.xslf.usermodel.XMLSlideShow;
|
||||||
|
import org.apache.poi.xslf.usermodel.XSLFShape;
|
||||||
|
import org.apache.poi.xslf.usermodel.XSLFSlide;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class PowerPointIntegrationTest {
|
||||||
|
|
||||||
|
private PowerPointHelper pph;
|
||||||
|
private String fileLocation;
|
||||||
|
private static final String FILE_NAME = "presentation.pptx";
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
File currDir = new File(".");
|
||||||
|
String path = currDir.getAbsolutePath();
|
||||||
|
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||||
|
|
||||||
|
pph = new PowerPointHelper();
|
||||||
|
pph.createPresentation(fileLocation);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReadingAPresentation_thenOK() throws Exception {
|
||||||
|
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
|
||||||
|
|
||||||
|
Assert.assertNotNull(xmlSlideShow);
|
||||||
|
Assert.assertEquals(4, xmlSlideShow.getSlides().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRetrievingThePlaceholdersForEachSlide_thenOK() throws Exception {
|
||||||
|
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
|
||||||
|
|
||||||
|
List<XSLFShape> onlyTitleSlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(0));
|
||||||
|
List<XSLFShape> titleAndBodySlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(1));
|
||||||
|
List<XSLFShape> emptySlidePlaceholdes = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(3));
|
||||||
|
|
||||||
|
Assert.assertEquals(1, onlyTitleSlidePlaceholders.size());
|
||||||
|
Assert.assertEquals(2, titleAndBodySlidePlaceholders.size());
|
||||||
|
Assert.assertEquals(0, emptySlidePlaceholdes.size());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenSortingSlides_thenOK() throws Exception {
|
||||||
|
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
|
||||||
|
XSLFSlide slide4 = xmlSlideShow.getSlides().get(3);
|
||||||
|
pph.reorderSlide(xmlSlideShow, 3, 1);
|
||||||
|
|
||||||
|
Assert.assertEquals(slide4, xmlSlideShow.getSlides().get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPresentation_whenDeletingASlide_thenOK() throws Exception {
|
||||||
|
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
|
||||||
|
pph.deleteSlide(xmlSlideShow, 3);
|
||||||
|
|
||||||
|
Assert.assertEquals(3, xmlSlideShow.getSlides().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() throws Exception {
|
||||||
|
File testFile = new File(fileLocation);
|
||||||
|
if (testFile.exists()) {
|
||||||
|
testFile.delete();
|
||||||
|
}
|
||||||
|
pph = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -65,7 +65,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.6.2</version>
|
<version>3.7.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
|
|||||||
@ -28,8 +28,14 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>3.8.1</version>
|
<version>4.12</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>hamcrest-core</artifactId>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
|||||||
@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
<camel.version>2.19.1</camel.version>
|
<camel.version>2.19.1</camel.version>
|
||||||
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||||
|
|||||||
2
cas/cas-secured-app/README.md
Normal file
2
cas/cas-secured-app/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
## Relevant articles:
|
||||||
|
- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso)
|
||||||
@ -14,7 +14,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>2.0.0.BUILD-SNAPSHOT</version>
|
<version>2.0.0.M7</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
@ -87,14 +87,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
|
||||||
<id>spring-snapshots</id>
|
|
||||||
<name>Spring Snapshots</name>
|
|
||||||
<url>https://repo.spring.io/snapshot</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
<repository>
|
||||||
<id>spring-milestones</id>
|
<id>spring-milestones</id>
|
||||||
<name>Spring Milestones</name>
|
<name>Spring Milestones</name>
|
||||||
@ -106,14 +98,6 @@
|
|||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
<pluginRepositories>
|
<pluginRepositories>
|
||||||
<pluginRepository>
|
|
||||||
<id>spring-snapshots</id>
|
|
||||||
<name>Spring Snapshots</name>
|
|
||||||
<url>https://repo.spring.io/snapshot</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
<pluginRepository>
|
<pluginRepository>
|
||||||
<id>spring-milestones</id>
|
<id>spring-milestones</id>
|
||||||
<name>Spring Milestones</name>
|
<name>Spring Milestones</name>
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.cassecuredapp.controllers;
|
package com.baeldung.cassecuredapp.controllers;
|
||||||
|
|
||||||
import org.apache.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
||||||
@ -15,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||||||
@Controller
|
@Controller
|
||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private Logger logger = Logger.getLogger(AuthController.class);
|
private Logger logger = LogManager.getLogger(AuthController.class);
|
||||||
|
|
||||||
@GetMapping("/logout")
|
@GetMapping("/logout")
|
||||||
public String logout(
|
public String logout(
|
||||||
|
|||||||
@ -52,7 +52,11 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.3</version>
|
<version>3.7.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
<finalName>cas</finalName>
|
<finalName>cas</finalName>
|
||||||
|
|||||||
@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ?
|
|||||||
cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
|
cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
|
||||||
cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect
|
cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect
|
||||||
cas.authn.jdbc.query[0].user=root
|
cas.authn.jdbc.query[0].user=root
|
||||||
cas.authn.jdbc.query[0].password=
|
cas.authn.jdbc.query[0].password=root
|
||||||
cas.authn.jdbc.query[0].ddlAuto=none
|
cas.authn.jdbc.query[0].ddlAuto=none
|
||||||
#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver
|
#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver
|
||||||
cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver
|
cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver
|
||||||
|
|||||||
@ -0,0 +1,16 @@
|
|||||||
|
-- Dumping database structure for test
|
||||||
|
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET latin1 */;
|
||||||
|
USE `test`;
|
||||||
|
|
||||||
|
-- Dumping structure for table test.users
|
||||||
|
CREATE TABLE IF NOT EXISTS `users` (
|
||||||
|
`id` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
`email` varchar(50) DEFAULT NULL,
|
||||||
|
`password` text DEFAULT NULL,
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
|
||||||
|
|
||||||
|
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
|
||||||
|
INSERT INTO `users` (`id`, `email`, `password`) VALUES
|
||||||
|
(1, 'test@test.com', 'Mellon');
|
||||||
|
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
|
||||||
@ -30,3 +30,10 @@
|
|||||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||||
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
||||||
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||||
|
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||||
|
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||||
|
- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers)
|
||||||
|
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||||
|
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||||
|
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
|
||||||
|
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
||||||
|
|||||||
@ -83,6 +83,41 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-bytecode</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.codepoetics</groupId>
|
||||||
|
<artifactId>protonpack</artifactId>
|
||||||
|
<version>${protonpack.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.vavr</groupId>
|
||||||
|
<artifactId>vavr</artifactId>
|
||||||
|
<version>${vavr.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>one.util</groupId>
|
||||||
|
<artifactId>streamex</artifactId>
|
||||||
|
<version>${streamex.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -249,6 +284,9 @@
|
|||||||
<collections-generic.version>4.01</collections-generic.version>
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
<commons-codec.version>1.10</commons-codec.version>
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
<lombok.version>1.16.12</lombok.version>
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
<vavr.version>0.9.0</vavr.version>
|
||||||
|
<protonpack.version>1.13</protonpack.version>
|
||||||
|
<streamex.version>0.6.5</streamex.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
|||||||
@ -1,35 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class which shows different ways of converting java.util.Date into java.time.LocalDate.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateConverter {
|
|
||||||
|
|
||||||
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
|
|
||||||
return dateToConvert.toInstant()
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDate();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
|
|
||||||
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
|
|
||||||
return Instant.ofEpochMilli(dateToConvert.getTime())
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDate();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,35 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class which shows different ways of converting java.util.Date into java.time.LocalDateTime.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateTimeConverter {
|
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
|
|
||||||
return dateToConvert.toInstant()
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDateTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
|
|
||||||
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
|
|
||||||
return Instant.ofEpochMilli(dateToConvert.getTime())
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDateTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -2,7 +2,6 @@ package com.baeldung.datetime;
|
|||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.LocalTime;
|
import java.time.LocalTime;
|
||||||
import java.time.Period;
|
|
||||||
|
|
||||||
public class UseDuration {
|
public class UseDuration {
|
||||||
|
|
||||||
|
|||||||
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.application;
|
||||||
|
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||||
|
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
Vehicle car = new Car("BMW");
|
||||||
|
System.out.println(car.getBrand());
|
||||||
|
System.out.println(car.speedUp());
|
||||||
|
System.out.println(car.slowDown());
|
||||||
|
System.out.println(car.turnAlarmOn());
|
||||||
|
System.out.println(car.turnAlarmOff());
|
||||||
|
System.out.println(Vehicle.getHorsePower(2500, 480));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public interface Alarm {
|
||||||
|
|
||||||
|
default String turnAlarmOn() {
|
||||||
|
return "Turning the alarm on.";
|
||||||
|
}
|
||||||
|
|
||||||
|
default String turnAlarmOff() {
|
||||||
|
return "Turning the alarm off.";
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public class Car implements Vehicle {
|
||||||
|
|
||||||
|
private final String brand;
|
||||||
|
|
||||||
|
public Car(String brand) {
|
||||||
|
this.brand = brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getBrand() {
|
||||||
|
return brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String speedUp() {
|
||||||
|
return "The car is speeding up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String slowDown() {
|
||||||
|
return "The car is slowing down.";
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public class Motorbike implements Vehicle {
|
||||||
|
|
||||||
|
private final String brand;
|
||||||
|
|
||||||
|
public Motorbike(String brand) {
|
||||||
|
this.brand = brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getBrand() {
|
||||||
|
return brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String speedUp() {
|
||||||
|
return "The motorbike is speeding up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String slowDown() {
|
||||||
|
return "The motorbike is slowing down.";
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public class MultiAlarmCar implements Vehicle, Alarm {
|
||||||
|
|
||||||
|
private final String brand;
|
||||||
|
|
||||||
|
public MultiAlarmCar(String brand) {
|
||||||
|
this.brand = brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getBrand() {
|
||||||
|
return brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String speedUp() {
|
||||||
|
return "The motorbike is speeding up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String slowDown() {
|
||||||
|
return "The mootorbike is slowing down.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String turnAlarmOn() {
|
||||||
|
return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String turnAlarmOff() {
|
||||||
|
return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public interface Vehicle {
|
||||||
|
|
||||||
|
String getBrand();
|
||||||
|
|
||||||
|
String speedUp();
|
||||||
|
|
||||||
|
String slowDown();
|
||||||
|
|
||||||
|
default String turnAlarmOn() {
|
||||||
|
return "Turning the vehice alarm on.";
|
||||||
|
}
|
||||||
|
|
||||||
|
default String turnAlarmOff() {
|
||||||
|
return "Turning the vehicle alarm off.";
|
||||||
|
}
|
||||||
|
|
||||||
|
static int getHorsePower(int rpm, int torque) {
|
||||||
|
return (rpm * torque) / 5252;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,80 @@
|
|||||||
|
package com.baeldung.iterators;
|
||||||
|
|
||||||
|
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 {
|
||||||
|
|
||||||
|
public static int failFast1() {
|
||||||
|
ArrayList<Integer> numbers = new ArrayList<>();
|
||||||
|
|
||||||
|
numbers.add(10);
|
||||||
|
numbers.add(20);
|
||||||
|
numbers.add(30);
|
||||||
|
numbers.add(40);
|
||||||
|
|
||||||
|
Iterator<Integer> iterator = numbers.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
Integer number = iterator.next();
|
||||||
|
numbers.add(50);
|
||||||
|
}
|
||||||
|
|
||||||
|
return numbers.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int failFast2() {
|
||||||
|
ArrayList<Integer> numbers = new ArrayList<>();
|
||||||
|
numbers.add(10);
|
||||||
|
numbers.add(20);
|
||||||
|
numbers.add(30);
|
||||||
|
numbers.add(40);
|
||||||
|
|
||||||
|
Iterator<Integer> iterator = numbers.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (iterator.next() == 30) {
|
||||||
|
// will not throw Exception
|
||||||
|
iterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("using iterator's remove method = " + numbers);
|
||||||
|
|
||||||
|
iterator = numbers.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (iterator.next() == 40) {
|
||||||
|
// will throw Exception on
|
||||||
|
// next call of next() method
|
||||||
|
numbers.remove(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return numbers.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int failSafe1() {
|
||||||
|
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
map.put("First", 10);
|
||||||
|
map.put("Second", 20);
|
||||||
|
map.put("Third", 30);
|
||||||
|
map.put("Fourth", 40);
|
||||||
|
|
||||||
|
Iterator<String> iterator = map.keySet()
|
||||||
|
.iterator();
|
||||||
|
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
String key = iterator.next();
|
||||||
|
map.put("Fifth", 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
return map.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.spliteratorAPI;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Article {
|
||||||
|
private List<Author> listOfAuthors;
|
||||||
|
private int id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public Article(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Article(List<Author> listOfAuthors, int id) {
|
||||||
|
super();
|
||||||
|
this.listOfAuthors = listOfAuthors;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Author> getListOfAuthors() {
|
||||||
|
return listOfAuthors;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setListOfAuthors(List<Author> listOfAuthors) {
|
||||||
|
this.listOfAuthors = listOfAuthors;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.spliteratorAPI;
|
||||||
|
|
||||||
|
public class Author {
|
||||||
|
private String name;
|
||||||
|
private int relatedArticleId;
|
||||||
|
|
||||||
|
public Author(String name, int relatedArticleId) {
|
||||||
|
this.name = name;
|
||||||
|
this.relatedArticleId = relatedArticleId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRelatedArticleId() {
|
||||||
|
return relatedArticleId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRelatedArticleId(int relatedArticleId) {
|
||||||
|
this.relatedArticleId = relatedArticleId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "[name: " + name + ", relatedId: " + relatedArticleId + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,45 @@
|
|||||||
|
package com.baeldung.spliteratorAPI;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Spliterator;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
|
public class Executor {
|
||||||
|
public void executeCustomSpliterator() {
|
||||||
|
Article article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
|
||||||
|
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
|
||||||
|
new Author("Alice", 1), new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
|
||||||
|
Stream<Author> stream = IntStream.range(0, article.getListOfAuthors()
|
||||||
|
.size())
|
||||||
|
.mapToObj(article.getListOfAuthors()::get);
|
||||||
|
System.out.println("count= " + countAutors(stream.parallel()));
|
||||||
|
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
|
||||||
|
Stream<Author> stream2 = StreamSupport.stream(spliterator, true);
|
||||||
|
System.out.println("count= " + countAutors(stream2.parallel()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void executeSpliterator() {
|
||||||
|
Spliterator<Article> split1 = generateElements().spliterator();
|
||||||
|
Spliterator<Article> split2 = split1.trySplit();
|
||||||
|
ExecutorService service = Executors.newCachedThreadPool();
|
||||||
|
service.execute(new Task(split1));
|
||||||
|
service.execute(new Task(split2));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int countAutors(Stream<Author> stream) {
|
||||||
|
RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
|
||||||
|
return wordCounter.getCounter();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Article> generateElements() {
|
||||||
|
return Stream.generate(() -> new Article("Java"))
|
||||||
|
.limit(35000)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.spliteratorAPI;
|
||||||
|
|
||||||
|
public class RelatedAuthorCounter {
|
||||||
|
private final int counter;
|
||||||
|
private final boolean isRelated;
|
||||||
|
|
||||||
|
public RelatedAuthorCounter(int counter, boolean isRelated) {
|
||||||
|
this.counter = counter;
|
||||||
|
this.isRelated = isRelated;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RelatedAuthorCounter accumulate(Author author) {
|
||||||
|
if (author.getRelatedArticleId() == 0) {
|
||||||
|
return isRelated ? this : new RelatedAuthorCounter(counter, true);
|
||||||
|
} else {
|
||||||
|
return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) {
|
||||||
|
return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCounter() {
|
||||||
|
return counter;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.spliteratorAPI;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Spliterator;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
public class RelatedAuthorSpliterator implements Spliterator<Author> {
|
||||||
|
private final List<Author> list;
|
||||||
|
private int current = 0;
|
||||||
|
|
||||||
|
public RelatedAuthorSpliterator(List<Author> list) {
|
||||||
|
this.list = list;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean tryAdvance(Consumer<? super Author> action) {
|
||||||
|
action.accept(list.get(current++));
|
||||||
|
return current < list.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Spliterator<Author> trySplit() {
|
||||||
|
int currentSize = list.size() - current;
|
||||||
|
if (currentSize < 10) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (int splitPos = currentSize / 2 + current; splitPos < list.size(); splitPos++) {
|
||||||
|
if (list.get(splitPos)
|
||||||
|
.getRelatedArticleId() == 0) {
|
||||||
|
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(list.subList(current, splitPos));
|
||||||
|
current = splitPos;
|
||||||
|
return spliterator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long estimateSize() {
|
||||||
|
return list.size() - current;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int characteristics() {
|
||||||
|
return SIZED + CONCURRENT;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.spliteratorAPI;
|
||||||
|
|
||||||
|
import java.util.Spliterator;
|
||||||
|
|
||||||
|
public class Task implements Runnable {
|
||||||
|
private Spliterator<Article> spliterator;
|
||||||
|
private final static String SUFFIX = "- published by Baeldung";
|
||||||
|
|
||||||
|
public Task(Spliterator<Article> spliterator) {
|
||||||
|
this.spliterator = spliterator;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
int current = 0;
|
||||||
|
while (spliterator.tryAdvance(article -> {
|
||||||
|
article.setName(article.getName()
|
||||||
|
.concat(SUFFIX));
|
||||||
|
})) {
|
||||||
|
current++;
|
||||||
|
}
|
||||||
|
;
|
||||||
|
System.out.println(Thread.currentThread()
|
||||||
|
.getName() + ":" + current);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
class PrimitiveStreams {
|
||||||
|
|
||||||
|
int min(int[] integers) {
|
||||||
|
return Arrays.stream(integers).min().getAsInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
int max(int... integers) {
|
||||||
|
return IntStream.of(integers).max().getAsInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
int sum(int... integers) {
|
||||||
|
return IntStream.of(integers).sum();
|
||||||
|
}
|
||||||
|
|
||||||
|
double avg(int... integers) {
|
||||||
|
return IntStream.of(integers).average().getAsDouble();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,8 +1,6 @@
|
|||||||
package com.baeldung.streamApi;
|
package com.baeldung.stream;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.stream.IntStream;
|
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -16,7 +16,7 @@ public class StreamApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static String getLastElementUsingSkip(List<String> valueList) {
|
public static String getLastElementUsingSkip(List<String> valueList) {
|
||||||
long count = valueList.stream().count();
|
long count = (long) valueList.size();
|
||||||
Stream<String> stream = valueList.stream();
|
Stream<String> stream = valueList.stream();
|
||||||
return stream.skip(count - 1).findFirst().orElse(null);
|
return stream.skip(count - 1).findFirst().orElse(null);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,55 @@
|
|||||||
|
package com.baeldung.timezonedisplay;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class TimezoneDisplay {
|
||||||
|
|
||||||
|
public enum OffsetBase {
|
||||||
|
GMT, UTC
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getTimeZoneList(OffsetBase base) {
|
||||||
|
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
|
||||||
|
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
return availableZoneIds
|
||||||
|
.stream()
|
||||||
|
.map(ZoneId::of)
|
||||||
|
.sorted(new ZoneComparator())
|
||||||
|
.map(id -> String.format("(%s%s) %s", base, getOffset(now, id), id.getId()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getOffset(LocalDateTime dateTime, ZoneId id) {
|
||||||
|
return dateTime
|
||||||
|
.atZone(id)
|
||||||
|
.getOffset()
|
||||||
|
.getId()
|
||||||
|
.replace("Z", "+00:00");
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ZoneComparator implements Comparator<ZoneId> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compare(ZoneId zoneId1, ZoneId zoneId2) {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
ZoneOffset offset1 = now
|
||||||
|
.atZone(zoneId1)
|
||||||
|
.getOffset();
|
||||||
|
|
||||||
|
ZoneOffset offset2 = now
|
||||||
|
.atZone(zoneId2)
|
||||||
|
.getOffset();
|
||||||
|
|
||||||
|
return offset1.compareTo(offset2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.timezonedisplay;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class TimezoneDisplayApp {
|
||||||
|
|
||||||
|
public static void main(String... args) {
|
||||||
|
TimezoneDisplay display = new TimezoneDisplay();
|
||||||
|
|
||||||
|
System.out.println("Time zones in UTC:");
|
||||||
|
List<String> utc = display.getTimeZoneList(TimezoneDisplay.OffsetBase.UTC);
|
||||||
|
utc.forEach(System.out::println);
|
||||||
|
|
||||||
|
System.out.println("Time zones in GMT:");
|
||||||
|
List<String> gmt = display.getTimeZoneList(TimezoneDisplay.OffsetBase.GMT);
|
||||||
|
gmt.forEach(System.out::println);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Fork;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
|
||||||
|
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||||
|
|
||||||
|
@Fork(value = 1, warmups = 3)
|
||||||
|
@BenchmarkMode(Mode.All)
|
||||||
|
public class CounterStatistics {
|
||||||
|
|
||||||
|
private static final Map<String, Integer> counterMap = new HashMap<>();
|
||||||
|
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
|
||||||
|
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
|
||||||
|
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
|
||||||
|
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
CounterUtil.COUNTRY_NAMES = new String[10000];
|
||||||
|
final String prefix = "NewString";
|
||||||
|
Random random = new Random();
|
||||||
|
for (int i=0; i<10000; i++) {
|
||||||
|
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void wrapperAsCounter() {
|
||||||
|
CounterUtil.counterWithWrapperObject(counterMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void lambdaExpressionWithWrapper() {
|
||||||
|
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void parallelStreamWithWrapper() {
|
||||||
|
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void mutableIntegerAsCounter() {
|
||||||
|
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void primitiveArrayAsCounter() {
|
||||||
|
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||||
|
|
||||||
|
public class CounterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
|
||||||
|
Map<String, Integer> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithWrapperObject(counterMap);
|
||||||
|
|
||||||
|
assertEquals(3, counterMap.get("China")
|
||||||
|
.intValue());
|
||||||
|
assertEquals(2, counterMap.get("India")
|
||||||
|
.intValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
|
||||||
|
Map<String, Long> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithLambdaAndWrapper(counterMap);
|
||||||
|
|
||||||
|
assertEquals(3l, counterMap.get("China")
|
||||||
|
.longValue());
|
||||||
|
assertEquals(2l, counterMap.get("India")
|
||||||
|
.longValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
|
||||||
|
Map<String, MutableInteger> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithMutableInteger(counterMap);
|
||||||
|
assertEquals(3, counterMap.get("China")
|
||||||
|
.getCount());
|
||||||
|
assertEquals(2, counterMap.get("India")
|
||||||
|
.getCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithPrimitiveArray_runsSuccessfully() {
|
||||||
|
Map<String, int[]> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithPrimitiveArray(counterMap);
|
||||||
|
assertEquals(3, counterMap.get("China")[0]);
|
||||||
|
assertEquals(2, counterMap.get("India")[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,57 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class CounterUtil {
|
||||||
|
|
||||||
|
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||||
|
|
||||||
|
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
|
||||||
|
Stream.of(COUNTRY_NAMES)
|
||||||
|
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
|
||||||
|
Stream.of(COUNTRY_NAMES)
|
||||||
|
.parallel()
|
||||||
|
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class MutableInteger {
|
||||||
|
int count;
|
||||||
|
|
||||||
|
public MutableInteger(int count) {
|
||||||
|
this.count = count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void increment() {
|
||||||
|
this.count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCount() {
|
||||||
|
return this.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
|
||||||
|
.increment();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -1,72 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.temporal.ChronoField;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* JUnits for {@link DateToLocalDateConverter} class.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateConverterTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,78 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.temporal.ChronoField;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* JUnits for {@link DateToLocalDateTimeConverter} class.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateTimeConverterTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10, 8, 20);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
|
||||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10, 8, 20);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
|
||||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10, 8, 20);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
|
||||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -4,7 +4,6 @@ import java.time.LocalDate;
|
|||||||
import java.time.LocalTime;
|
import java.time.LocalTime;
|
||||||
import java.time.Month;
|
import java.time.Month;
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|||||||
@ -4,7 +4,6 @@ import java.time.DayOfWeek;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|||||||
@ -0,0 +1,79 @@
|
|||||||
|
package com.baeldung.defaultistaticinterfacemethods.test;
|
||||||
|
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Motorbike;
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class StaticDefaulInterfaceMethodUnitTest {
|
||||||
|
|
||||||
|
private static Car car;
|
||||||
|
private static Motorbike motorbike;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpCarInstance() {
|
||||||
|
car = new Car("BMW");
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpMotorbikeInstance() {
|
||||||
|
motorbike = new Motorbike("Yamaha");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstace_whenBrandisBMW_thenOneAssertion() {
|
||||||
|
assertThat(car.getBrand()).isEqualTo("BMW");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingSpeedUp_thenOneAssertion() {
|
||||||
|
assertThat(car.speedUp()).isEqualTo("The car is speeding up.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingSlowDown_thenOneAssertion() {
|
||||||
|
assertThat(car.slowDown()).isEqualTo("The car is slowing down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
|
||||||
|
assertThat(car.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
|
||||||
|
assertThat(car.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVehicleInterface_whenCallinggetHorsePower_thenOneAssertion() {
|
||||||
|
assertThat(Vehicle.getHorsePower(2500, 480)).isEqualTo(228);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMooorbikeInstace_whenBrandisYamaha_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.getBrand()).isEqualTo("Yamaha");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingSpeedUp_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.speedUp()).isEqualTo("The motorbike is speeding up.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingSlowDown_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.slowDown()).isEqualTo("The motorbike is slowing down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.iterators;
|
||||||
|
|
||||||
|
import static com.baeldung.iterators.Iterators.failFast1;
|
||||||
|
import static com.baeldung.iterators.Iterators.failFast2;
|
||||||
|
import static com.baeldung.iterators.Iterators.failSafe1;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Source code https://github.com/eugenp/tutorials
|
||||||
|
*
|
||||||
|
* @author Santosh Thakur
|
||||||
|
*/
|
||||||
|
|
||||||
|
public class IteratorsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailFast_ThenThrowsException() {
|
||||||
|
assertThatThrownBy(() -> {
|
||||||
|
failFast1();
|
||||||
|
}).isInstanceOf(ConcurrentModificationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailFast_ThenThrowsExceptionInSecondIteration() {
|
||||||
|
assertThatThrownBy(() -> {
|
||||||
|
failFast2();
|
||||||
|
}).isInstanceOf(ConcurrentModificationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailSafe_ThenDoesNotThrowException() {
|
||||||
|
assertThat(failSafe1()).isGreaterThanOrEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
import com.baeldung.streamApi.Product;
|
import com.baeldung.stream.Product;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
|
|||||||
@ -6,7 +6,6 @@ import java.util.Comparator;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import lombok.Data;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class Java8ComparatorUnitTest {
|
public class Java8ComparatorUnitTest {
|
||||||
@ -134,8 +133,7 @@ public class Java8ComparatorUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenThenComparing_thenSortedByAgeName() {
|
public void whenThenComparing_thenSortedByAgeName() {
|
||||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
|
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
|
||||||
.thenComparing(Employee::getName);
|
|
||||||
|
|
||||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||||
@ -144,8 +142,7 @@ public class Java8ComparatorUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenThenComparing_thenSortedByNameAge() {
|
public void whenThenComparing_thenSortedByNameAge() {
|
||||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
|
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
|
||||||
.thenComparingInt(Employee::getAge);
|
|
||||||
|
|
||||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||||
|
|||||||
@ -0,0 +1,99 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class PrimitiveStreamsUnitTest {
|
||||||
|
|
||||||
|
private PrimitiveStreams streams = new PrimitiveStreams();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||||
|
int[] integers = new int[] {20, 98, 12, 7, 35};
|
||||||
|
int min = streams.min(integers); // returns 7
|
||||||
|
|
||||||
|
assertEquals(7, min);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenMaxIsCalledThenCorrectMaxIsReturned() {
|
||||||
|
int max = streams.max(20, 98, 12, 7, 35);
|
||||||
|
|
||||||
|
assertEquals(98, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenSumIsCalledThenCorrectSumIsReturned() {
|
||||||
|
int sum = streams.sum(20, 98, 12, 7, 35);
|
||||||
|
|
||||||
|
assertEquals(172, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenAvgIsCalledThenCorrectAvgIsReturned() {
|
||||||
|
double avg = streams.avg(20, 98, 12, 7, 35);
|
||||||
|
|
||||||
|
assertTrue(34.4 == avg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenARangeOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||||
|
int sum = IntStream.range(1, 10).sum();
|
||||||
|
|
||||||
|
assertEquals(45, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenARangeClosedOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||||
|
int sum = IntStream.rangeClosed(1, 10).sum();
|
||||||
|
|
||||||
|
assertEquals(55, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenARangeWhenForEachIsCalledThenTheIndicesWillBePrinted() {
|
||||||
|
IntStream.rangeClosed(1, 5).parallel().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||||
|
|
||||||
|
int sum = Stream.of(33,45)
|
||||||
|
.mapToInt(i -> i)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
assertEquals(78, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||||
|
List<Integer> evenInts = IntStream.rangeClosed(1, 10)
|
||||||
|
.filter(i -> i % 2 == 0)
|
||||||
|
.boxed()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(expected, evenInts);
|
||||||
|
}
|
||||||
|
|
||||||
|
class Person {
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
Person(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,101 @@
|
|||||||
|
package com.baeldung.stringjoiner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.StringJoiner;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StringJoinerUnitTest {
|
||||||
|
private final String DELIMITER_COMMA = ",";
|
||||||
|
private final String DELIMITER_HYPHEN = "-";
|
||||||
|
private final String PREFIX = "[";
|
||||||
|
private final String SUFFIX = "]";
|
||||||
|
private final String EMPTY_JOINER = "empty";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoinerWithoutPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
|
||||||
|
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
|
||||||
|
assertEquals(0, commaSeparatedJoiner.toString().length());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoinerWithPrefixSuffixWithoutEmptyValue_thenReturnDefault() {
|
||||||
|
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||||
|
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), PREFIX + SUFFIX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoinerWithoutPrefixSuffixWithEmptyValue_thenReturnDefault() {
|
||||||
|
StringJoiner commaSeparatedJoiner = new StringJoiner(DELIMITER_COMMA);
|
||||||
|
commaSeparatedJoiner.setEmptyValue(EMPTY_JOINER);
|
||||||
|
|
||||||
|
assertEquals(commaSeparatedJoiner.toString(), EMPTY_JOINER);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenJoinerWithPrefixSuffixWithEmptyValue_thenReturnDefault() {
|
||||||
|
StringJoiner commaSeparatedPrefixSuffixJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||||
|
commaSeparatedPrefixSuffixJoiner.setEmptyValue(EMPTY_JOINER);
|
||||||
|
|
||||||
|
assertEquals(commaSeparatedPrefixSuffixJoiner.toString(), EMPTY_JOINER);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddElements_thenJoinElements() {
|
||||||
|
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||||
|
rgbJoiner.add("Red")
|
||||||
|
.add("Green")
|
||||||
|
.add("Blue");
|
||||||
|
|
||||||
|
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddListElements_thenJoinListElements() {
|
||||||
|
List<String> rgbList = new ArrayList<String>();
|
||||||
|
rgbList.add("Red");
|
||||||
|
rgbList.add("Green");
|
||||||
|
rgbList.add("Blue");
|
||||||
|
|
||||||
|
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||||
|
|
||||||
|
for (String color : rgbList) {
|
||||||
|
rgbJoiner.add(color);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue]");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMergeJoiners_thenReturnMerged() {
|
||||||
|
StringJoiner rgbJoiner = new StringJoiner(DELIMITER_COMMA, PREFIX, SUFFIX);
|
||||||
|
StringJoiner cmybJoiner = new StringJoiner(DELIMITER_HYPHEN, PREFIX, SUFFIX);
|
||||||
|
|
||||||
|
rgbJoiner.add("Red")
|
||||||
|
.add("Green")
|
||||||
|
.add("Blue");
|
||||||
|
cmybJoiner.add("Cyan")
|
||||||
|
.add("Magenta")
|
||||||
|
.add("Yellow")
|
||||||
|
.add("Black");
|
||||||
|
|
||||||
|
rgbJoiner.merge(cmybJoiner);
|
||||||
|
|
||||||
|
assertEquals(rgbJoiner.toString(), "[Red,Green,Blue,Cyan-Magenta-Yellow-Black]");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsedWithinCollectors_thenJoin() {
|
||||||
|
List<String> rgbList = Arrays.asList("Red", "Green", "Blue");
|
||||||
|
String commaSeparatedRGB = rgbList.stream()
|
||||||
|
.map(color -> color.toString())
|
||||||
|
.collect(Collectors.joining(","));
|
||||||
|
|
||||||
|
assertEquals(commaSeparatedRGB, "Red,Green,Blue");
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,7 +1,6 @@
|
|||||||
package com.baeldung.temporaladjusters;
|
package com.baeldung.temporaladjusters;
|
||||||
|
|
||||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
|||||||
@ -18,3 +18,5 @@
|
|||||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||||
|
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||||
|
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||||
|
|||||||
3
core-java-9/compile-httpclient.bat
Normal file
3
core-java-9/compile-httpclient.bat
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
javac --module-path mods -d mods/com.baeldung.httpclient^
|
||||||
|
src/modules/com.baeldung.httpclient/module-info.java^
|
||||||
|
src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java
|
||||||
@ -2,10 +2,10 @@
|
|||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>core-java9</artifactId>
|
<artifactId>core-java-9</artifactId>
|
||||||
<version>0.2-SNAPSHOT</version>
|
<version>0.2-SNAPSHOT</version>
|
||||||
|
|
||||||
<name>core-java9</name>
|
<name>core-java-9</name>
|
||||||
|
|
||||||
<pluginRepositories>
|
<pluginRepositories>
|
||||||
<pluginRepository>
|
<pluginRepository>
|
||||||
@ -90,7 +90,7 @@
|
|||||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<ch.qos.logback.version>1.2.1</ch.qos.logback.version>
|
<ch.qos.logback.version>1.2.1</ch.qos.logback.version>
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
|
|||||||
1
core-java-9/run-httpclient.bat
Normal file
1
core-java-9/run-httpclient.bat
Normal file
@ -0,0 +1 @@
|
|||||||
|
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample
|
||||||
@ -3,18 +3,35 @@
|
|||||||
*/
|
*/
|
||||||
package com.baeldung.java9.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9.
|
* Class which shows a way to convert java.util.Date into java.time.LocalDate.
|
||||||
*
|
*
|
||||||
* @author abialas
|
* @author abialas
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class DateToLocalDateConverter {
|
public class DateToLocalDateConverter {
|
||||||
|
|
||||||
|
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
|
||||||
|
return dateToConvert.toInstant()
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
|
||||||
|
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
|
||||||
|
return Instant.ofEpochMilli(dateToConvert.getTime())
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDate();
|
||||||
|
}
|
||||||
|
|
||||||
public static LocalDate convertToLocalDate(Date dateToConvert) {
|
public static LocalDate convertToLocalDate(Date dateToConvert) {
|
||||||
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,18 +3,35 @@
|
|||||||
*/
|
*/
|
||||||
package com.baeldung.java9.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9.
|
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime.
|
||||||
*
|
*
|
||||||
* @author abialas
|
* @author abialas
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class DateToLocalDateTimeConverter {
|
public class DateToLocalDateTimeConverter {
|
||||||
|
|
||||||
|
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
|
||||||
|
return dateToConvert.toInstant()
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
|
||||||
|
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
|
||||||
|
return Instant.ofEpochMilli(dateToConvert.getTime())
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
|
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
|
||||||
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* To change this license header, choose License Headers in Project Properties.
|
||||||
|
* To change this template file, choose Tools | Templates
|
||||||
|
* and open the template in the editor.
|
||||||
|
*/
|
||||||
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import jdk.incubator.http.HttpClient;
|
||||||
|
import jdk.incubator.http.HttpRequest;
|
||||||
|
import jdk.incubator.http.HttpRequest.BodyProcessor;
|
||||||
|
import jdk.incubator.http.HttpResponse;
|
||||||
|
import jdk.incubator.http.HttpResponse.BodyHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @author pkaria
|
||||||
|
*/
|
||||||
|
public class HttpClientExample {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
httpGetRequest();
|
||||||
|
httpPostRequest();
|
||||||
|
asynchronousRequest();
|
||||||
|
asynchronousMultipleRequests();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
|
||||||
|
.headers("Accept-Enconding", "gzip, deflate").build();
|
||||||
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
String responseBody = response.body();
|
||||||
|
int responseStatusCode = response.statusCode();
|
||||||
|
System.out.println(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient
|
||||||
|
.newBuilder()
|
||||||
|
.build();
|
||||||
|
HttpRequest request = HttpRequest
|
||||||
|
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
|
||||||
|
.POST(BodyProcessor.fromString("Sample Post Request"))
|
||||||
|
.build();
|
||||||
|
HttpResponse<String> response
|
||||||
|
= client.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
String responseBody = response.body();
|
||||||
|
System.out.println(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void asynchronousRequest() throws URISyntaxException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
|
||||||
|
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
|
||||||
|
HttpResponse.BodyHandler.asString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void asynchronousMultipleRequests() throws URISyntaxException {
|
||||||
|
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
List<CompletableFuture<File>> futures = targets
|
||||||
|
.stream()
|
||||||
|
.map(target -> client
|
||||||
|
.sendAsync(
|
||||||
|
HttpRequest.newBuilder(target)
|
||||||
|
.GET()
|
||||||
|
.build(),
|
||||||
|
BodyHandler.asFile(Paths.get("base", target.getPath())))
|
||||||
|
.thenApply(response -> response.body())
|
||||||
|
.thenApply(path -> path.toFile()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
module com.baeldung.httpclient {
|
||||||
|
requires jdk.incubator.httpclient;
|
||||||
|
}
|
||||||
@ -22,6 +22,54 @@ import com.baeldung.java9.datetime.DateToLocalDateConverter;
|
|||||||
*/
|
*/
|
||||||
public class DateToLocalDateConverterTest {
|
public class DateToLocalDateConverterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
|
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
|
||||||
// given
|
// given
|
||||||
|
|||||||
@ -29,6 +29,60 @@ public class DateToLocalDateTimeConverterTest {
|
|||||||
calendar.set(2010, 10, 10, 8, 20);
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
Date dateToConvert = calendar.getTime();
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
// when
|
// when
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
@ -0,0 +1,106 @@
|
|||||||
|
package com.baeldung.java9.varhandles;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
import java.lang.invoke.VarHandle;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class VariableHandlesTest {
|
||||||
|
|
||||||
|
public int publicTestVariable = 1;
|
||||||
|
private int privateTestVariable = 1;
|
||||||
|
public int variableToSet = 1;
|
||||||
|
public int variableToCompareAndSet = 1;
|
||||||
|
public int variableToGetAndAdd = 0;
|
||||||
|
public byte variableToBitwiseOr = 0;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||||
|
|
||||||
|
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
||||||
|
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle privateIntHandle = MethodHandles
|
||||||
|
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
|
||||||
|
|
||||||
|
assertThat(privateIntHandle.coordinateTypes().size() == 1);
|
||||||
|
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle arrayVarHandle = MethodHandles
|
||||||
|
.arrayElementVarHandle(int[].class);
|
||||||
|
|
||||||
|
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
|
||||||
|
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||||
|
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
|
||||||
|
publicIntHandle.set(this, 15);
|
||||||
|
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
|
||||||
|
publicIntHandle.compareAndSet(this, 1, 100);
|
||||||
|
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
|
||||||
|
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
||||||
|
|
||||||
|
assertThat(before == 0);
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
|
||||||
|
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
||||||
|
|
||||||
|
assertThat(before == 0);
|
||||||
|
assertThat(variableToBitwiseOr == 127);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -31,3 +31,5 @@
|
|||||||
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
||||||
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
||||||
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
||||||
|
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
|
||||||
|
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
|
||||||
|
|||||||
@ -3,7 +3,6 @@ package com.baeldung.concurrent.daemon;
|
|||||||
public class NewThread extends Thread {
|
public class NewThread extends Thread {
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
|
|
||||||
long startTime = System.currentTimeMillis();
|
long startTime = System.currentTimeMillis();
|
||||||
while (true) {
|
while (true) {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
|
|||||||
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
public class Data {
|
||||||
|
private String packet;
|
||||||
|
|
||||||
|
// True if receiver should wait
|
||||||
|
// False if sender should wait
|
||||||
|
private boolean transfer = true;
|
||||||
|
|
||||||
|
public synchronized String receive() {
|
||||||
|
while (transfer) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
transfer = true;
|
||||||
|
|
||||||
|
notifyAll();
|
||||||
|
return packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void send(String packet) {
|
||||||
|
while (!transfer) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
transfer = false;
|
||||||
|
|
||||||
|
this.packet = packet;
|
||||||
|
notifyAll();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
public class NetworkDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Data data = new Data();
|
||||||
|
Thread sender = new Thread(new Sender(data));
|
||||||
|
Thread receiver = new Thread(new Receiver(data));
|
||||||
|
|
||||||
|
sender.start();
|
||||||
|
receiver.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class Receiver implements Runnable {
|
||||||
|
private Data load;
|
||||||
|
|
||||||
|
public Receiver(Data load) {
|
||||||
|
this.load = load;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
for(String receivedMessage = load.receive();
|
||||||
|
!"End".equals(receivedMessage) ;
|
||||||
|
receivedMessage = load.receive()) {
|
||||||
|
|
||||||
|
System.out.println(receivedMessage);
|
||||||
|
|
||||||
|
//Thread.sleep() to mimic heavy server-side processing
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class Sender implements Runnable {
|
||||||
|
private Data data;
|
||||||
|
|
||||||
|
public Sender(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
String packets[] = {
|
||||||
|
"First packet",
|
||||||
|
"Second packet",
|
||||||
|
"Third packet",
|
||||||
|
"Fourth packet",
|
||||||
|
"End"
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String packet : packets) {
|
||||||
|
data.send(packet);
|
||||||
|
|
||||||
|
//Thread.sleep() to mimic heavy server-side processing
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -9,11 +9,10 @@ import java.util.List;
|
|||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
import static junit.framework.TestCase.assertTrue;
|
import static junit.framework.TestCase.assertTrue;
|
||||||
import static org.junit.Assert.fail;
|
|
||||||
|
|
||||||
public class WaitingForThreadsToFinishTest {
|
public class WaitingForThreadsToFinishManualTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishManualTest.class);
|
||||||
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
|
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
|
||||||
@ -40,9 +39,7 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
CountDownLatch latch = new CountDownLatch(2);
|
CountDownLatch latch = new CountDownLatch(2);
|
||||||
|
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
WORKER_THREAD_POOL.submit(() -> {
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
try {
|
try {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
latch.countDown();
|
latch.countDown();
|
||||||
@ -50,7 +47,6 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
|
||||||
@Override
|
|
||||||
public String call() throws Exception {
|
|
||||||
fail("This thread should have been rejected !");
|
|
||||||
Thread.sleep(1000000);
|
Thread.sleep(1000000);
|
||||||
return null;
|
return null;
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} catch (RejectedExecutionException ex) {
|
} catch (RejectedExecutionException ex) {
|
||||||
//
|
//
|
||||||
@ -150,66 +142,4 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMultipleThreads_whenUsingCompletableFutures_thenMainThreadShouldWaitForAllToFinish() {
|
|
||||||
|
|
||||||
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(1000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Hello";
|
|
||||||
});
|
|
||||||
|
|
||||||
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(5000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Beautiful";
|
|
||||||
});
|
|
||||||
|
|
||||||
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(3000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
return "World";
|
|
||||||
});
|
|
||||||
|
|
||||||
long startProcessingTime = System.currentTimeMillis();
|
|
||||||
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);
|
|
||||||
combinedFuture.join();
|
|
||||||
|
|
||||||
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
|
|
||||||
assertTrue(totalProcessingTime >= 5000 && totalProcessingTime < 6000);
|
|
||||||
|
|
||||||
LOG.debug("Responses from all threads are available after " + totalProcessingTime + " milliseconds");
|
|
||||||
|
|
||||||
try {
|
|
||||||
String thread1Response = future1.get();
|
|
||||||
assertTrue(thread1Response.equals("Hello"));
|
|
||||||
|
|
||||||
String thread2Response = future2.get();
|
|
||||||
assertTrue(thread2Response.equals("Beautiful"));
|
|
||||||
|
|
||||||
String thread3Response = future3.get();
|
|
||||||
assertTrue(thread3Response.equals("World"));
|
|
||||||
|
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@ -1,16 +1,21 @@
|
|||||||
package com.baeldung.concurrent.stopping;
|
package com.baeldung.concurrent.stopping;
|
||||||
|
|
||||||
|
import static com.jayway.awaitility.Awaitility.await;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertFalse;
|
import com.jayway.awaitility.Awaitility;
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
public class StopThreadTest {
|
public class StopThreadTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenStoppedThreadIsStopped() throws InterruptedException {
|
public void whenStoppedThreadIsStopped() throws InterruptedException {
|
||||||
|
|
||||||
int interval = 100;
|
int interval = 5;
|
||||||
|
|
||||||
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
||||||
controlSubThread.start();
|
controlSubThread.start();
|
||||||
@ -22,21 +27,20 @@ public class StopThreadTest {
|
|||||||
|
|
||||||
// Stop it and make sure the flags have been reversed
|
// Stop it and make sure the flags have been reversed
|
||||||
controlSubThread.stop();
|
controlSubThread.stop();
|
||||||
Thread.sleep(interval);
|
await()
|
||||||
assertTrue(controlSubThread.isStopped());
|
.until(() -> assertTrue(controlSubThread.isStopped()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
||||||
|
|
||||||
int interval = 5000;
|
int interval = 50;
|
||||||
|
|
||||||
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
||||||
controlSubThread.start();
|
controlSubThread.start();
|
||||||
|
|
||||||
// Give things a chance to get set up
|
// Give things a chance to get set up
|
||||||
Thread.sleep(100);
|
Thread.sleep(interval);
|
||||||
assertTrue(controlSubThread.isRunning());
|
assertTrue(controlSubThread.isRunning());
|
||||||
assertFalse(controlSubThread.isStopped());
|
assertFalse(controlSubThread.isStopped());
|
||||||
|
|
||||||
@ -44,7 +48,9 @@ public class StopThreadTest {
|
|||||||
controlSubThread.interrupt();
|
controlSubThread.interrupt();
|
||||||
|
|
||||||
// Wait less than the time we would normally sleep, and make sure we exited.
|
// Wait less than the time we would normally sleep, and make sure we exited.
|
||||||
Thread.sleep(interval/10);
|
Awaitility.await()
|
||||||
assertTrue(controlSubThread.isStopped());
|
.pollDelay(2, TimeUnit.MILLISECONDS)
|
||||||
|
.atMost(interval/ 10, TimeUnit.MILLISECONDS)
|
||||||
|
.until(controlSubThread::isStopped);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class NetworkIntegrationTest {
|
||||||
|
|
||||||
|
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||||
|
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
|
||||||
|
private String expected;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpStreams() {
|
||||||
|
System.setOut(new PrintStream(outContent));
|
||||||
|
System.setErr(new PrintStream(errContent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpExpectedOutput() {
|
||||||
|
StringWriter expectedStringWriter = new StringWriter();
|
||||||
|
|
||||||
|
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
|
||||||
|
printWriter.println("First packet");
|
||||||
|
printWriter.println("Second packet");
|
||||||
|
printWriter.println("Third packet");
|
||||||
|
printWriter.println("Fourth packet");
|
||||||
|
printWriter.close();
|
||||||
|
|
||||||
|
expected = expectedStringWriter.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanUpStreams() {
|
||||||
|
System.setOut(null);
|
||||||
|
System.setErr(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
|
||||||
|
Data data = new Data();
|
||||||
|
Thread sender = new Thread(new Sender(data));
|
||||||
|
Thread receiver = new Thread(new Receiver(data));
|
||||||
|
|
||||||
|
sender.start();
|
||||||
|
receiver.start();
|
||||||
|
|
||||||
|
//wait for sender and receiver to finish before we test against expected
|
||||||
|
try {
|
||||||
|
sender.join();
|
||||||
|
receiver.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(expected, outContent.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
26
core-java-io/.gitignore
vendored
Normal file
26
core-java-io/.gitignore
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
*.class
|
||||||
|
|
||||||
|
0.*
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
.resourceCache
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
||||||
|
|
||||||
|
# Files generated by integration tests
|
||||||
|
*.txt
|
||||||
|
backup-pom.xml
|
||||||
|
/bin/
|
||||||
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
25
core-java-io/README.md
Normal file
25
core-java-io/README.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
=========
|
||||||
|
|
||||||
|
## Core Java IO Cookbooks and Examples
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
|
||||||
|
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
|
||||||
|
- [Java – Write to File](http://www.baeldung.com/java-write-to-file)
|
||||||
|
- [Java - Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
|
||||||
|
- [Java Scanner](http://www.baeldung.com/java-scanner)
|
||||||
|
- [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
|
||||||
|
- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
|
||||||
|
- [Differences Between the Java WatchService API and the Apache Commons IO Monitor Library](http://www.baeldung.com/java-watchservice-vs-apache-commons-io-monitor-library)
|
||||||
|
- [Calculate the Size of a File in Java](http://www.baeldung.com/java-file-size)
|
||||||
|
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
|
||||||
|
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)
|
||||||
|
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||||
|
- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file)
|
||||||
|
- [FileNotFoundException in Java](http://www.baeldung.com/java-filenotfound-exception)
|
||||||
|
- [How to Read a File in Java](http://www.baeldung.com/reading-file-in-java)
|
||||||
|
- [A Guide To NIO2 Asynchronous File Channel](http://www.baeldung.com/java-nio2-async-file-channel)
|
||||||
|
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
|
||||||
|
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
|
||||||
|
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
|
||||||
|
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
|
||||||
505
core-java-io/pom.xml
Normal file
505
core-java-io/pom.xml
Normal file
@ -0,0 +1,505 @@
|
|||||||
|
<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</groupId>
|
||||||
|
<artifactId>core-java-io</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>core-java-io</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<!-- utils -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.sourceforge.collections</groupId>
|
||||||
|
<artifactId>collections-generic</artifactId>
|
||||||
|
<version>${collections-generic.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-collections4</artifactId>
|
||||||
|
<version>${commons-collections4.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
<version>${commons-io.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-math3</artifactId>
|
||||||
|
<version>${commons-math3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.decimal4j</groupId>
|
||||||
|
<artifactId>decimal4j</artifactId>
|
||||||
|
<version>${decimal4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.bouncycastle</groupId>
|
||||||
|
<artifactId>bcprov-jdk15on</artifactId>
|
||||||
|
<version>${bouncycastle.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.unix4j</groupId>
|
||||||
|
<artifactId>unix4j-command</artifactId>
|
||||||
|
<version>${unix4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.grep4j</groupId>
|
||||||
|
<artifactId>grep4j</artifactId>
|
||||||
|
<version>${grep4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- web -->
|
||||||
|
|
||||||
|
<!-- marshalling -->
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>${jackson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- logging -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>log4j</groupId>
|
||||||
|
<artifactId>log4j</artifactId>
|
||||||
|
<version>1.2.17</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
<!-- <scope>runtime</scope> -->
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||||
|
</dependency>
|
||||||
|
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>log4j-over-slf4j</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- test scoped -->
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>hamcrest-all</artifactId>
|
||||||
|
<version>1.3</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>hamcrest-core</artifactId>
|
||||||
|
<version>${org.hamcrest.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>hamcrest-library</artifactId>
|
||||||
|
<version>${org.hamcrest.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.mockito</groupId>
|
||||||
|
<artifactId>mockito-core</artifactId>
|
||||||
|
<version>${mockito.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.jayway.awaitility</groupId>
|
||||||
|
<artifactId>awaitility</artifactId>
|
||||||
|
<version>${avaitility.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>${commons-codec.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.javamoney</groupId>
|
||||||
|
<artifactId>moneta</artifactId>
|
||||||
|
<version>1.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.owasp.esapi</groupId>
|
||||||
|
<artifactId>esapi</artifactId>
|
||||||
|
<version>2.1.0.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.messaging.mq</groupId>
|
||||||
|
<artifactId>fscontext</artifactId>
|
||||||
|
<version>${fscontext.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.codepoetics</groupId>
|
||||||
|
<artifactId>protonpack</artifactId>
|
||||||
|
<version>${protonpack.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>one.util</groupId>
|
||||||
|
<artifactId>streamex</artifactId>
|
||||||
|
<version>${streamex.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.vavr</groupId>
|
||||||
|
<artifactId>vavr</artifactId>
|
||||||
|
<version>${vavr.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-web</artifactId>
|
||||||
|
<version>4.3.4.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
|
<version>1.5.8.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hsqldb</groupId>
|
||||||
|
<artifactId>hsqldb</artifactId>
|
||||||
|
<version>2.4.0</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-io</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<testFailureIgnore>true</testFailureIgnore>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>copy-dependencies</id>
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>copy-dependencies</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<addClasspath>true</addClasspath>
|
||||||
|
<classpathPrefix>libs/</classpathPrefix>
|
||||||
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>single</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
<descriptorRefs>
|
||||||
|
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||||
|
</descriptorRefs>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>shade</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||||
|
<transformers>
|
||||||
|
<transformer
|
||||||
|
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||||
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
|
</transformer>
|
||||||
|
</transformers>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>com.jolira</groupId>
|
||||||
|
<artifactId>onejar-maven-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
|
<attachToBuild>true</attachToBuild>
|
||||||
|
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||||
|
</configuration>
|
||||||
|
<goals>
|
||||||
|
<goal>one-jar</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<classifier>spring-boot</classifier>
|
||||||
|
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
<version>1.6.0</version>
|
||||||
|
<configuration>
|
||||||
|
<executable>java</executable>
|
||||||
|
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||||
|
<arguments>
|
||||||
|
<argument>-Xmx300m</argument>
|
||||||
|
<argument>-XX:+UseParallelGC</argument>
|
||||||
|
<argument>-classpath</argument>
|
||||||
|
<classpath/>
|
||||||
|
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||||
|
</arguments>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
|
<version>3.0.0-M1</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
|
|
||||||
|
</plugins>
|
||||||
|
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>integration</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>run-benchmarks</id>
|
||||||
|
<!-- <phase>integration-test</phase>-->
|
||||||
|
<phase>none</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>exec</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<classpathScope>test</classpathScope>
|
||||||
|
<executable>java</executable>
|
||||||
|
<arguments>
|
||||||
|
<argument>-classpath</argument>
|
||||||
|
<classpath/>
|
||||||
|
<argument>org.openjdk.jmh.Main</argument>
|
||||||
|
<argument>.*</argument>
|
||||||
|
</arguments>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- marshalling -->
|
||||||
|
<jackson.version>2.8.5</jackson.version>
|
||||||
|
|
||||||
|
<!-- logging -->
|
||||||
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
|
<!-- util -->
|
||||||
|
<guava.version>22.0</guava.version>
|
||||||
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
|
<decimal4j.version>1.0.3</decimal4j.version>
|
||||||
|
<commons-io.version>2.5</commons-io.version>
|
||||||
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
|
<unix4j.version>0.4</unix4j.version>
|
||||||
|
<grep4j.version>1.8.7</grep4j.version>
|
||||||
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
<fscontext.version>4.6-b01</fscontext.version>
|
||||||
|
<protonpack.version>1.13</protonpack.version>
|
||||||
|
<streamex.version>0.6.5</streamex.version>
|
||||||
|
<vavr.version>0.9.0</vavr.version>
|
||||||
|
|
||||||
|
<!-- testing -->
|
||||||
|
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
<mockito.version>2.8.9</mockito.version>
|
||||||
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
|
<!-- maven plugins -->
|
||||||
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
||||||
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.filesystem.jndi;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.Hashtable;
|
||||||
|
|
||||||
|
import javax.naming.Context;
|
||||||
|
import javax.naming.InitialContext;
|
||||||
|
import javax.naming.NamingException;
|
||||||
|
|
||||||
|
public class LookupFSJNDI {
|
||||||
|
private InitialContext ctx = null;
|
||||||
|
|
||||||
|
public LookupFSJNDI() throws NamingException {
|
||||||
|
super();
|
||||||
|
init();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void init() throws NamingException {
|
||||||
|
Hashtable<String, String> env = new Hashtable<String, String>();
|
||||||
|
|
||||||
|
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
|
||||||
|
// URI to namespace (actual directory)
|
||||||
|
env.put(Context.PROVIDER_URL, "file:./src/test/resources");
|
||||||
|
|
||||||
|
ctx = new InitialContext(env);
|
||||||
|
}
|
||||||
|
|
||||||
|
public InitialContext getCtx() {
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public File getFile(String fileName) {
|
||||||
|
File file;
|
||||||
|
try {
|
||||||
|
file = (File) getCtx().lookup(fileName);
|
||||||
|
} catch (NamingException e) {
|
||||||
|
file = null;
|
||||||
|
}
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
48
core-java-io/src/main/java/com/baeldung/stream/FileCopy.java
Normal file
48
core-java-io/src/main/java/com/baeldung/stream/FileCopy.java
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
|
||||||
|
public class FileCopy {
|
||||||
|
|
||||||
|
public static void copyFileUsingStream(File source, File dest) throws IOException {
|
||||||
|
InputStream is = null;
|
||||||
|
OutputStream os = null;
|
||||||
|
is = new FileInputStream(source);
|
||||||
|
os = new FileOutputStream(dest);
|
||||||
|
byte[] buffer = new byte[1024];
|
||||||
|
int length;
|
||||||
|
while ((length = is.read(buffer)) > 0) {
|
||||||
|
os.write(buffer, 0, length);
|
||||||
|
}
|
||||||
|
is.close();
|
||||||
|
os.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyFileUsingChannel(File source, File dest) throws IOException {
|
||||||
|
FileChannel sourceChannel = null;
|
||||||
|
FileChannel destChannel = null;
|
||||||
|
sourceChannel = new FileInputStream(source).getChannel();
|
||||||
|
destChannel = new FileOutputStream(dest).getChannel();
|
||||||
|
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
|
||||||
|
sourceChannel.close();
|
||||||
|
destChannel.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
|
||||||
|
FileUtils.copyFile(source, dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyFileUsingJavaFiles(File source, File dest) throws IOException {
|
||||||
|
Files.copy(source.toPath(), dest.toPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.util;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
|
||||||
|
import org.apache.commons.io.IOUtils;
|
||||||
|
|
||||||
|
public class StreamUtils {
|
||||||
|
|
||||||
|
public static String getStringFromInputStream(InputStream input) throws IOException {
|
||||||
|
StringWriter writer = new StringWriter();
|
||||||
|
IOUtils.copy(input, writer, "UTF-8");
|
||||||
|
return writer.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user