Merge remote-tracking branch 'central/master'
This commit is contained in:
commit
7da69bcbda
|
@ -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
|
||||
==============================
|
||||
|
||||
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)**
|
||||
|
||||
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
|
||||
================
|
||||
|
|
|
@ -14,3 +14,4 @@
|
|||
- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort)
|
||||
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
||||
- [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)
|
||||
|
|
|
@ -1,22 +1,15 @@
|
|||
package com.baeldung.algorithms.editdistance;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class EditDistanceBase {
|
||||
|
||||
public static int costOfSubstitution(char a, char b) {
|
||||
if (a == b) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
static int costOfSubstitution(char a, char b) {
|
||||
return a == b ? 0 : 1;
|
||||
}
|
||||
|
||||
public static int min(int... numbers) {
|
||||
int min = Integer.MAX_VALUE;
|
||||
|
||||
for (int x : numbers) {
|
||||
if (x < min)
|
||||
min = x;
|
||||
}
|
||||
|
||||
return min;
|
||||
static int min(int... numbers) {
|
||||
return Arrays.stream(numbers)
|
||||
.min().orElse(Integer.MAX_VALUE);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ package com.baeldung.algorithms.editdistance;
|
|||
|
||||
public class EditDistanceDynamicProgramming extends EditDistanceBase {
|
||||
|
||||
public static int calculate(String x, String y) {
|
||||
static int calculate(String x, String y) {
|
||||
int[][] dp = new int[x.length() + 1][y.length() + 1];
|
||||
|
||||
for (int i = 0; i <= x.length(); i++) {
|
||||
|
@ -14,12 +14,13 @@ public class EditDistanceDynamicProgramming extends EditDistanceBase {
|
|||
dp[i][j] = i;
|
||||
|
||||
else {
|
||||
dp[i][j] = min(dp[i - 1][j - 1] + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), dp[i - 1][j] + 1, dp[i][j - 1] + 1);
|
||||
dp[i][j] = min(dp[i - 1][j - 1]
|
||||
+ costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)),
|
||||
dp[i - 1][j] + 1, dp[i][j - 1] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dp[x.length()][y.length()];
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -2,13 +2,15 @@ package com.baeldung.algorithms.editdistance;
|
|||
|
||||
public class EditDistanceRecursive extends EditDistanceBase {
|
||||
|
||||
public static int calculate(String x, String y) {
|
||||
static int calculate(String x, String y) {
|
||||
|
||||
if (x.isEmpty())
|
||||
if (x.isEmpty()) {
|
||||
return y.length();
|
||||
}
|
||||
|
||||
if (y.isEmpty())
|
||||
if (y.isEmpty()) {
|
||||
return x.length();
|
||||
}
|
||||
|
||||
int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0));
|
||||
int insertion = calculate(x, y.substring(1)) + 1;
|
||||
|
@ -16,5 +18,4 @@ public class EditDistanceRecursive extends EditDistanceBase {
|
|||
|
||||
return min(substitution, insertion, deletion);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.algorithms.prime;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PrimeGenerator {
|
||||
public static List<Integer> sieveOfEratosthenes(int n) {
|
||||
final boolean prime[] = new boolean[n + 1];
|
||||
Arrays.fill(prime, true);
|
||||
|
||||
for (int p = 2; p * p <= n; p++) {
|
||||
if (prime[p]) {
|
||||
for (int i = p * 2; i <= n; i += p)
|
||||
prime[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
final List<Integer> primes = new LinkedList<>();
|
||||
for (int i = 2; i <= n; i++) {
|
||||
if (prime[i])
|
||||
primes.add(i);
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
|
||||
public static List<Integer> primeNumbersBruteForce(int max) {
|
||||
final List<Integer> primeNumbers = new LinkedList<Integer>();
|
||||
for (int i = 2; i <= max; i++) {
|
||||
if (isPrimeBruteForce(i)) {
|
||||
primeNumbers.add(i);
|
||||
}
|
||||
}
|
||||
return primeNumbers;
|
||||
}
|
||||
|
||||
private static boolean isPrimeBruteForce(int x) {
|
||||
for (int i = 2; i < x; i++) {
|
||||
if (x % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static List<Integer> primeNumbersTill(int max) {
|
||||
return IntStream.rangeClosed(2, max)
|
||||
.filter(x -> isPrime(x))
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static boolean isPrime(int x) {
|
||||
return IntStream.rangeClosed(2, (int) (Math.sqrt(x)))
|
||||
.allMatch(n -> x % n != 0);
|
||||
}
|
||||
}
|
|
@ -1,16 +1,17 @@
|
|||
package com.baeldung.algorithms.editdistance;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(Parameterized.class)
|
||||
public class EditDistanceTest extends EditDistanceDataProvider {
|
||||
|
||||
String x;
|
||||
String y;
|
||||
int result;
|
||||
private String x;
|
||||
private String y;
|
||||
private int result;
|
||||
|
||||
public EditDistanceTest(String a, String b, int res) {
|
||||
super();
|
||||
|
@ -21,11 +22,11 @@ public class EditDistanceTest extends EditDistanceDataProvider {
|
|||
|
||||
@Test
|
||||
public void testEditDistance_RecursiveImplementation() {
|
||||
Assert.assertEquals(result, EditDistanceRecursive.calculate(x, y));
|
||||
assertEquals(result, EditDistanceRecursive.calculate(x, y));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEditDistance_givenDynamicProgrammingImplementation() {
|
||||
Assert.assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
|
||||
assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.algorithms.prime;
|
||||
|
||||
import static com.baeldung.algorithms.prime.PrimeGenerator.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PrimeGeneratorTest {
|
||||
@Test
|
||||
public void whenBruteForced_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = primeNumbersBruteForce(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptimized_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = primeNumbersTill(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSieveOfEratosthenes_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant articles
|
||||
|
||||
- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark)
|
|
@ -17,37 +17,24 @@ import scala.Tuple2;
|
|||
public class WordCount {
|
||||
|
||||
private static final Pattern SPACE = Pattern.compile(" ");
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 1) {
|
||||
System.err.println("Usage: JavaWordCount <file>");
|
||||
System.exit(1);
|
||||
if (args.length < 1) {
|
||||
System.err.println("Usage: JavaWordCount <file>");
|
||||
System.exit(1);
|
||||
}
|
||||
SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount")
|
||||
.setMaster("local");
|
||||
JavaSparkContext ctx = new JavaSparkContext(sparkConf);
|
||||
JavaRDD<String> lines = ctx.textFile(args[0], 1);
|
||||
|
||||
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator());
|
||||
JavaPairRDD<String, Integer> wordAsTuple = words.mapToPair(word -> new Tuple2<>(word, 1));
|
||||
JavaPairRDD<String, Integer> wordWithCount = wordAsTuple.reduceByKey((Integer i1, Integer i2)->i1 + i2);
|
||||
List<Tuple2<String, Integer>> output = wordWithCount.collect();
|
||||
for (Tuple2<?, ?> tuple : output) {
|
||||
System.out.println(tuple._1() + ": " + tuple._2());
|
||||
}
|
||||
ctx.stop();
|
||||
}
|
||||
SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
|
||||
JavaSparkContext ctx = new JavaSparkContext(sparkConf);
|
||||
JavaRDD<String> lines = ctx.textFile(args[0], 1);
|
||||
|
||||
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator());
|
||||
JavaPairRDD<String, Integer> ones = words.mapToPair(
|
||||
new PairFunction<String, String, Integer>() {
|
||||
@Override
|
||||
public Tuple2<String, Integer> call(String s) {
|
||||
return new Tuple2<>(s, 1);
|
||||
}
|
||||
});
|
||||
|
||||
JavaPairRDD<String, Integer> counts = ones.reduceByKey(
|
||||
new Function2<Integer, Integer, Integer>() {
|
||||
@Override
|
||||
public Integer call(Integer i1, Integer i2) {
|
||||
return i1 + i2;
|
||||
}
|
||||
});
|
||||
|
||||
List<Tuple2<String, Integer>> output = counts.collect();
|
||||
for (Tuple2<?, ?> tuple : output) {
|
||||
System.out.println(tuple._1() + ": " + tuple._2());
|
||||
}
|
||||
ctx.stop();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -28,8 +28,14 @@
|
|||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
## Relevant articles:
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,27 @@
|
|||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
nbproject/private/
|
||||
build/
|
||||
nbbuild/
|
||||
dist/
|
||||
nbdist/
|
||||
.nb-gradle/
|
||||
/.mvn/
|
||||
/mvnw
|
||||
/mvnw.cmd
|
|
@ -65,6 +65,24 @@
|
|||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<forkCount>3</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
<exclude>**/JdbcTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
@ -107,4 +125,5 @@
|
|||
</pluginRepositories>
|
||||
|
||||
|
||||
|
||||
</project>
|
|
@ -40,14 +40,14 @@ public class CasSecuredAppApplication {
|
|||
@Primary
|
||||
public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) {
|
||||
CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint();
|
||||
entryPoint.setLoginUrl("https://localhost:8443/cas/login");
|
||||
entryPoint.setLoginUrl("https://localhost:6443/cas/login");
|
||||
entryPoint.setServiceProperties(sP);
|
||||
return entryPoint;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TicketValidator ticketValidator() {
|
||||
return new Cas30ServiceTicketValidator("https://localhost:8443/cas");
|
||||
return new Cas30ServiceTicketValidator("https://localhost:6443/cas");
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
@ -71,7 +71,7 @@ public class CasSecuredAppApplication {
|
|||
@Bean
|
||||
public LogoutFilter logoutFilter() {
|
||||
LogoutFilter logoutFilter = new LogoutFilter(
|
||||
"https://localhost:8443/cas/logout", securityContextLogoutHandler());
|
||||
"https://localhost:6443/cas/logout", securityContextLogoutHandler());
|
||||
logoutFilter.setFilterProcessesUrl("/logout/cas");
|
||||
return logoutFilter;
|
||||
}
|
||||
|
@ -79,7 +79,7 @@ public class CasSecuredAppApplication {
|
|||
@Bean
|
||||
public SingleSignOutFilter singleSignOutFilter() {
|
||||
SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
|
||||
singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443/cas");
|
||||
singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas");
|
||||
singleSignOutFilter.setIgnoreInitConfiguration(true);
|
||||
return singleSignOutFilter;
|
||||
}
|
|
@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
|
|||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class CasSecuredAppApplicationTests {
|
||||
public class CasSecuredAppApplicationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
|
@ -2,9 +2,9 @@
|
|||
# CAS Server Context Configuration
|
||||
#
|
||||
server.context-path=/cas
|
||||
server.port=8443
|
||||
server.port=6443
|
||||
|
||||
server.ssl.key-store=file:/etc/cas/thekeystore
|
||||
server.ssl.key-store=classpath:/etc/cas/thekeystore
|
||||
server.ssl.key-store-password=changeit
|
||||
server.ssl.key-password=changeit
|
||||
# server.ssl.ciphers=
|
||||
|
@ -40,6 +40,12 @@ spring.http.encoding.charset=UTF-8
|
|||
spring.http.encoding.enabled=true
|
||||
spring.http.encoding.force=true
|
||||
|
||||
##
|
||||
#CAS CONFIG LOCATION
|
||||
#
|
||||
cas.standalone.config=classpath:/etc/cas/config
|
||||
|
||||
|
||||
##
|
||||
# CAS Cloud Bus Configuration
|
||||
#
|
||||
|
@ -82,6 +88,7 @@ spring.thymeleaf.mode=HTML
|
|||
# CAS Log4j Configuration
|
||||
#
|
||||
# logging.config=file:/etc/cas/log4j2.xml
|
||||
|
||||
server.context-parameters.isLog4jAutoInitializationDisabled=true
|
||||
|
||||
##
|
||||
|
@ -102,11 +109,12 @@ 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].dialect=org.hibernate.dialect.MySQLDialect
|
||||
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].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].fieldPassword=password
|
||||
cas.authn.jdbc.query[0].passwordEncoder.type=BCRYPT
|
||||
cas.authn.jdbc.query[0].passwordEncoder.type=NONE
|
||||
|
||||
|
||||
##
|
|
@ -1,16 +1,15 @@
|
|||
cas.server.name: https://localhost:8443
|
||||
cas.server.prefix: https://localhost:8443/cas
|
||||
cas.server.name: https://localhost:6443
|
||||
cas.server.prefix: https://localhost:643/cas
|
||||
|
||||
cas.adminPagesSecurity.ip=127\.0\.0\.1
|
||||
|
||||
logging.config: file:/etc/cas/config/log4j2.xml
|
||||
|
||||
cas.serviceRegistry.initFromJson=true
|
||||
cas.serviceRegistry.config.location=classpath:/services
|
||||
|
||||
cas.authn.accept.users=
|
||||
cas.authn.accept.name=
|
||||
|
||||
|
||||
#CAS Database Authentication Property
|
||||
|
||||
# cas.authn.jdbc.query[0].healthQuery=
|
|
@ -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 */;
|
|
@ -0,0 +1,2 @@
|
|||
info:
|
||||
description: CAS Configuration
|
|
@ -0,0 +1,7 @@
|
|||
cas.server.name: https://cas.example.org:8443
|
||||
cas.server.prefix: https://cas.example.org:8443/cas
|
||||
|
||||
cas.adminPagesSecurity.ip=127\.0\.0\.1
|
||||
|
||||
logging.config: file:/etc/cas/config/log4j2.xml
|
||||
# cas.serviceRegistry.config.location: classpath:/services
|
|
@ -0,0 +1,117 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!-- Specify the refresh internal in seconds. -->
|
||||
<Configuration monitorInterval="5" packages="org.apereo.cas.logging">
|
||||
<Properties>
|
||||
<!--
|
||||
Default log directory is the current directory but that can be overridden with -Dcas.log.dir=<logdir>
|
||||
Or you can change this property to a new default
|
||||
-->
|
||||
<Property name="cas.log.dir" >.</Property>
|
||||
<!-- To see more CAS specific logging, adjust this property to info or debug or run server with -Dcas.log.leve=debug -->
|
||||
<Property name="cas.log.level" >warn</Property>
|
||||
</Properties>
|
||||
<Appenders>
|
||||
<Console name="console" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d %p [%c] - <%m>%n"/>
|
||||
</Console>
|
||||
<RollingFile name="file" fileName="${sys:cas.log.dir}/cas.log" append="true"
|
||||
filePattern="${sys:cas.log.dir}/cas-%d{yyyy-MM-dd-HH}-%i.log">
|
||||
<PatternLayout pattern="%d %p [%c] - <%m>%n"/>
|
||||
<Policies>
|
||||
<OnStartupTriggeringPolicy />
|
||||
<SizeBasedTriggeringPolicy size="10 MB"/>
|
||||
<TimeBasedTriggeringPolicy />
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
<RollingFile name="auditlogfile" fileName="${sys:cas.log.dir}/cas_audit.log" append="true"
|
||||
filePattern="${sys:cas.log.dir}/cas_audit-%d{yyyy-MM-dd-HH}-%i.log">
|
||||
<PatternLayout pattern="%d %p [%c] - %m%n"/>
|
||||
<Policies>
|
||||
<OnStartupTriggeringPolicy />
|
||||
<SizeBasedTriggeringPolicy size="10 MB"/>
|
||||
<TimeBasedTriggeringPolicy />
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
|
||||
<RollingFile name="perfFileAppender" fileName="${sys:cas.log.dir}/perfStats.log" append="true"
|
||||
filePattern="${sys:cas.log.dir}/perfStats-%d{yyyy-MM-dd-HH}-%i.log">
|
||||
<PatternLayout pattern="%m%n"/>
|
||||
<Policies>
|
||||
<OnStartupTriggeringPolicy />
|
||||
<SizeBasedTriggeringPolicy size="10 MB"/>
|
||||
<TimeBasedTriggeringPolicy />
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
|
||||
<CasAppender name="casAudit">
|
||||
<AppenderRef ref="auditlogfile" />
|
||||
</CasAppender>
|
||||
<CasAppender name="casFile">
|
||||
<AppenderRef ref="file" />
|
||||
</CasAppender>
|
||||
<CasAppender name="casConsole">
|
||||
<AppenderRef ref="console" />
|
||||
</CasAppender>
|
||||
<CasAppender name="casPerf">
|
||||
<AppenderRef ref="perfFileAppender" />
|
||||
</CasAppender>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<!-- If adding a Logger with level set higher than warn, make category as selective as possible -->
|
||||
<!-- Loggers inherit appenders from Root Logger unless additivity is false -->
|
||||
<AsyncLogger name="org.apereo" level="${sys:cas.log.level}" includeLocation="true"/>
|
||||
<AsyncLogger name="org.apereo.services.persondir" level="${sys:cas.log.level}" includeLocation="true"/>
|
||||
<AsyncLogger name="org.apereo.cas.web.flow" level="info" includeLocation="true"/>
|
||||
<AsyncLogger name="org.apache" level="warn" />
|
||||
<AsyncLogger name="org.apache.http" level="error" />
|
||||
<AsyncLogger name="org.springframework" level="warn" />
|
||||
<AsyncLogger name="org.springframework.cloud.server" level="warn" />
|
||||
<AsyncLogger name="org.springframework.cloud.client" level="warn" />
|
||||
<AsyncLogger name="org.springframework.cloud.bus" level="warn" />
|
||||
<AsyncLogger name="org.springframework.aop" level="warn" />
|
||||
<AsyncLogger name="org.springframework.boot" level="warn" />
|
||||
<AsyncLogger name="org.springframework.boot.actuate.autoconfigure" level="warn" />
|
||||
<AsyncLogger name="org.springframework.webflow" level="warn" />
|
||||
<AsyncLogger name="org.springframework.session" level="warn" />
|
||||
<AsyncLogger name="org.springframework.amqp" level="error" />
|
||||
<AsyncLogger name="org.springframework.integration" level="warn" />
|
||||
<AsyncLogger name="org.springframework.messaging" level="warn" />
|
||||
<AsyncLogger name="org.springframework.web" level="warn" />
|
||||
<AsyncLogger name="org.springframework.orm.jpa" level="warn" />
|
||||
<AsyncLogger name="org.springframework.scheduling" level="warn" />
|
||||
<AsyncLogger name="org.springframework.context.annotation" level="error" />
|
||||
<AsyncLogger name="org.springframework.boot.devtools" level="error" />
|
||||
<AsyncLogger name="org.springframework.web.socket" level="warn" />
|
||||
<AsyncLogger name="org.thymeleaf" level="warn" />
|
||||
<AsyncLogger name="org.pac4j" level="warn" />
|
||||
<AsyncLogger name="org.opensaml" level="warn"/>
|
||||
<AsyncLogger name="net.sf.ehcache" level="warn" />
|
||||
<AsyncLogger name="com.couchbase" level="warn" includeLocation="true"/>
|
||||
<AsyncLogger name="com.ryantenney.metrics" level="warn" />
|
||||
<AsyncLogger name="net.jradius" level="warn" />
|
||||
<AsyncLogger name="org.openid4java" level="warn" />
|
||||
<AsyncLogger name="org.ldaptive" level="warn" />
|
||||
<AsyncLogger name="com.hazelcast" level="warn" />
|
||||
<AsyncLogger name="org.jasig.spring" level="warn" />
|
||||
|
||||
<!-- Log perf stats only to perfStats.log -->
|
||||
<AsyncLogger name="perfStatsLogger" level="info" additivity="false" includeLocation="true">
|
||||
<AppenderRef ref="casPerf"/>
|
||||
</AsyncLogger>
|
||||
|
||||
<!-- Log audit to all root appenders, and also to audit log (additivity is not false) -->
|
||||
<AsyncLogger name="org.apereo.inspektr.audit.support" level="info" includeLocation="true" >
|
||||
<AppenderRef ref="casAudit"/>
|
||||
</AsyncLogger>
|
||||
|
||||
<!-- All Loggers inherit appenders specified here, unless additivity="false" on the Logger -->
|
||||
<AsyncRoot level="warn">
|
||||
<AppenderRef ref="casFile"/>
|
||||
<!--
|
||||
For deployment to an application server running as service,
|
||||
delete the casConsole appender below
|
||||
-->
|
||||
<AppenderRef ref="casConsole"/>
|
||||
</AsyncRoot>
|
||||
</Loggers>
|
||||
</Configuration>
|
Binary file not shown.
Binary file not shown.
|
@ -30,3 +30,5 @@
|
|||
- [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)
|
||||
- [“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)
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
@Deprecated
|
||||
class ClassWithAnnotation {
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
class ClassWithDeprecatedMethod {
|
||||
|
||||
@Deprecated
|
||||
static void deprecatedMethod() {
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
class ClassWithSafeVarargs<T> {
|
||||
|
||||
@SafeVarargs
|
||||
final void iterateOverVarargs(T... args) {
|
||||
for (T x : args) {
|
||||
// do stuff with x
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
class ClassWithSuppressWarnings {
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
void useDeprecatedMethod() {
|
||||
ClassWithDeprecatedMethod.deprecatedMethod(); // no warning is generated here
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
@FunctionalInterface
|
||||
interface IntConsumer {
|
||||
|
||||
void accept(Integer number);
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
import java.lang.annotation.Repeatable;
|
||||
|
||||
@Repeatable(Intervals.class)
|
||||
@interface Interval {
|
||||
int hour() default 1;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
public class IntervalUsage {
|
||||
|
||||
@Interval(hour = 17)
|
||||
@Interval(hour = 13)
|
||||
void doPeriodicCleanup() {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
@interface Intervals {
|
||||
Interval[] value();
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Inherited
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD})
|
||||
@interface MyAnnotation {
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
class MyAnnotationTarget {
|
||||
|
||||
// this is OK
|
||||
@MyAnnotation
|
||||
String someField;
|
||||
|
||||
// @MyAnnotation <- this is invalid usage!
|
||||
void doSomething() {
|
||||
|
||||
// this also works
|
||||
@MyAnnotation
|
||||
String localVariable;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
interface MyOperation {
|
||||
|
||||
void perform();
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.annotations;
|
||||
|
||||
class MyOperationImpl implements MyOperation {
|
||||
|
||||
@Override
|
||||
public void perform() {
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.prime;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class PrimeGenerator {
|
||||
public static List<Integer> sieveOfEratosthenes(int n) {
|
||||
final boolean prime[] = new boolean[n + 1];
|
||||
Arrays.fill(prime, true);
|
||||
|
||||
for (int p = 2; p * p <= n; p++) {
|
||||
if (prime[p]) {
|
||||
for (int i = p * 2; i <= n; i += p)
|
||||
prime[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
final List<Integer> primes = new LinkedList<>();
|
||||
for (int i = 2; i <= n; i++) {
|
||||
if (prime[i])
|
||||
primes.add(i);
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
|
||||
public static List<Integer> primeNumbersBruteForce(int max) {
|
||||
final List<Integer> primeNumbers = new LinkedList<Integer>();
|
||||
for (int i = 2; i <= max; i++) {
|
||||
if (isPrimeBruteForce(i)) {
|
||||
primeNumbers.add(i);
|
||||
}
|
||||
}
|
||||
return primeNumbers;
|
||||
}
|
||||
|
||||
private static boolean isPrimeBruteForce(int x) {
|
||||
for (int i = 2; i < x; i++) {
|
||||
if (x % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static List<Integer> primeNumbersTill(int max) {
|
||||
return IntStream.rangeClosed(2, max)
|
||||
.filter(x -> isPrime(x))
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static boolean isPrime(int x) {
|
||||
return IntStream.rangeClosed(2, (int) (Math.sqrt(x)))
|
||||
.allMatch(n -> x % n != 0);
|
||||
}
|
||||
}
|
|
@ -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,28 @@
|
|||
package com.baeldung.prime;
|
||||
|
||||
import static com.baeldung.prime.PrimeGenerator.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PrimeGeneratorTest {
|
||||
@Test
|
||||
public void whenBruteForced_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = primeNumbersBruteForce(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptimized_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = primeNumbersTill(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSieveOfEratosthenes_returnsSuccessfully() {
|
||||
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
|
||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows a way to convert 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();
|
||||
}
|
||||
|
||||
public static LocalDate convertToLocalDate(Date dateToConvert) {
|
||||
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows a way to convert 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();
|
||||
}
|
||||
|
||||
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
|
||||
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows different ways of converting java.time.LocalDateTime into java.util.Date.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateTimeToDateConverter {
|
||||
|
||||
public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) {
|
||||
return java.sql.Timestamp.valueOf(dateToConvert);
|
||||
}
|
||||
|
||||
public static Date convertToDateViaInstant(LocalDateTime dateToConvert) {
|
||||
return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows different ways of converting java.time.LocalDate into java.util.Date.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateToDateConverter {
|
||||
|
||||
public static Date convertToDateViaSqlDate(LocalDate dateToConvert) {
|
||||
return java.sql.Date.valueOf(dateToConvert);
|
||||
}
|
||||
|
||||
public static Date convertToDateViaInstant(LocalDate dateToConvert) {
|
||||
return java.util.Date.from(dateToConvert.atStartOfDay()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.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;
|
||||
|
||||
import com.baeldung.java9.datetime.DateToLocalDateConverter;
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,97 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.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;
|
||||
|
||||
import com.baeldung.java9.datetime.DateToLocalDateTimeConverter;
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10, 8, 20);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(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));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* JUnits for {@link LocalDateTimeToDateConverter} class.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateTimeToDateConverterTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
|
||||
// given
|
||||
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
|
||||
|
||||
// when
|
||||
Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(8, calendar.get(Calendar.HOUR));
|
||||
assertEquals(20, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() {
|
||||
// given
|
||||
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
|
||||
|
||||
// when
|
||||
Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(8, calendar.get(Calendar.HOUR));
|
||||
assertEquals(20, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java9.datetime;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* JUnits for {@link LocalDateToDateConverter} class.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateToDateConverterTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
||||
// given
|
||||
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
|
||||
|
||||
// when
|
||||
Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
||||
// given
|
||||
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
|
||||
|
||||
// when
|
||||
Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
}
|
|
@ -30,3 +30,4 @@
|
|||
- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
|
||||
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
||||
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
||||
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
public class NewThread extends Thread {
|
||||
|
||||
public void run() {
|
||||
long startTime = System.currentTimeMillis();
|
||||
while (true) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
System.out.println("New Thread is running..." + i);
|
||||
}
|
||||
|
||||
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
|
||||
if (System.currentTimeMillis() - startTime > 2000) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.concurrent.executorservice;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class DelayedCallable implements Callable<String> {
|
||||
|
||||
private String name;
|
||||
private long period;
|
||||
private CountDownLatch latch;
|
||||
|
||||
public DelayedCallable(String name, long period, CountDownLatch latch) {
|
||||
this(name, period);
|
||||
this.latch = latch;
|
||||
}
|
||||
|
||||
public DelayedCallable(String name, long period) {
|
||||
this.name = name;
|
||||
this.period = period;
|
||||
}
|
||||
|
||||
public String call() {
|
||||
|
||||
try {
|
||||
Thread.sleep(period);
|
||||
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
} catch (InterruptedException ex) {
|
||||
// handle exception
|
||||
ex.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.concurrent.stopping;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public class ControlSubThread implements Runnable {
|
||||
|
||||
private Thread worker;
|
||||
private int interval = 100;
|
||||
private AtomicBoolean running = new AtomicBoolean(false);
|
||||
private AtomicBoolean stopped = new AtomicBoolean(true);
|
||||
|
||||
|
||||
public ControlSubThread(int sleepInterval) {
|
||||
interval = sleepInterval;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
worker = new Thread(this);
|
||||
worker.start();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
running.set(false);
|
||||
}
|
||||
|
||||
public void interrupt() {
|
||||
running.set(false);
|
||||
worker.interrupt();
|
||||
}
|
||||
|
||||
boolean isRunning() {
|
||||
return running.get();
|
||||
}
|
||||
|
||||
boolean isStopped() {
|
||||
return stopped.get();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
running.set(true);
|
||||
stopped.set(false);
|
||||
while (running.get()) {
|
||||
try {
|
||||
Thread.sleep(interval);
|
||||
} catch (InterruptedException e) {
|
||||
// no-op, just loop again
|
||||
}
|
||||
// do something
|
||||
}
|
||||
stopped.set(true);
|
||||
}
|
||||
}
|
|
@ -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) {}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.concurrent.daemon;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DaemonThreadTest {
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenCallIsDaemon_thenCorrect() {
|
||||
NewThread daemonThread = new NewThread();
|
||||
NewThread userThread = new NewThread();
|
||||
daemonThread.setDaemon(true);
|
||||
daemonThread.start();
|
||||
userThread.start();
|
||||
|
||||
assertTrue(daemonThread.isDaemon());
|
||||
assertFalse(userThread.isDaemon());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalThreadStateException.class)
|
||||
@Ignore
|
||||
public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() {
|
||||
NewThread daemonThread = new NewThread();
|
||||
daemonThread.start();
|
||||
daemonThread.setDaemon(true);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,215 @@
|
|||
package com.baeldung.concurrent.executorservice;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class WaitingForThreadsToFinishTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class);
|
||||
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||
|
||||
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
|
||||
threadPool.shutdown();
|
||||
try {
|
||||
if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
|
||||
threadPool.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
threadPool.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleThreads_whenUsingCountDownLatch_thenMainShoudWaitForAllToFinish() {
|
||||
|
||||
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||
|
||||
try {
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// create a CountDownLatch that waits for the 2 threads to finish
|
||||
CountDownLatch latch = new CountDownLatch(2);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
latch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// wait for the latch to be decremented by the two threads
|
||||
latch.await();
|
||||
|
||||
long processingTime = System.currentTimeMillis() - startTime;
|
||||
assertTrue(processingTime >= 1000);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToFinish() {
|
||||
|
||||
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Callable<String>> callables = Arrays.asList(
|
||||
new DelayedCallable("fast thread", 100),
|
||||
new DelayedCallable("slow thread", 3000));
|
||||
|
||||
try {
|
||||
long startProcessingTime = System.currentTimeMillis();
|
||||
List<Future<String>> futures = WORKER_THREAD_POOL.invokeAll(callables);
|
||||
|
||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
|
||||
try {
|
||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
fail("This thread should have been rejected !");
|
||||
Thread.sleep(1000000);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException ex) {
|
||||
//
|
||||
}
|
||||
|
||||
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
|
||||
assertTrue(totalProcessingTime >= 3000);
|
||||
|
||||
String firstThreadResponse = futures.get(0)
|
||||
.get();
|
||||
assertTrue("First response should be from the fast thread", "fast thread".equals(firstThreadResponse));
|
||||
|
||||
String secondThreadResponse = futures.get(1)
|
||||
.get();
|
||||
assertTrue("Last response should be from the slow thread", "slow thread".equals(secondThreadResponse));
|
||||
|
||||
} catch (ExecutionException | InterruptedException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleThreads_whenUsingCompletionService_thenMainThreadShouldWaitForAllToFinish() {
|
||||
|
||||
CompletionService<String> service = new ExecutorCompletionService<>(WORKER_THREAD_POOL);
|
||||
|
||||
List<Callable<String>> callables = Arrays.asList(
|
||||
new DelayedCallable("fast thread", 100),
|
||||
new DelayedCallable("slow thread", 3000));
|
||||
|
||||
for (Callable<String> callable : callables) {
|
||||
service.submit(callable);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
long startProcessingTime = System.currentTimeMillis();
|
||||
|
||||
Future<String> future = service.take();
|
||||
String firstThreadResponse = future.get();
|
||||
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
|
||||
|
||||
assertTrue("First response should be from the fast thread", "fast thread".equals(firstThreadResponse));
|
||||
assertTrue(totalProcessingTime >= 100 && totalProcessingTime < 1000);
|
||||
LOG.debug("Thread finished after: " + totalProcessingTime + " milliseconds");
|
||||
|
||||
future = service.take();
|
||||
String secondThreadResponse = future.get();
|
||||
totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
|
||||
|
||||
assertTrue("Last response should be from the slow thread", "slow thread".equals(secondThreadResponse));
|
||||
assertTrue(totalProcessingTime >= 3000 && totalProcessingTime < 4000);
|
||||
LOG.debug("Thread finished after: " + totalProcessingTime + " milliseconds");
|
||||
|
||||
} catch (ExecutionException | InterruptedException ex) {
|
||||
ex.printStackTrace();
|
||||
} finally {
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,133 @@
|
|||
package com.baeldung.concurrent.runnable;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class RunnableVsThreadLiveTest {
|
||||
|
||||
private static Logger log =
|
||||
LoggerFactory.getLogger(RunnableVsThreadLiveTest.class);
|
||||
|
||||
private static ExecutorService executorService;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
executorService = Executors.newCachedThreadPool();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARunnable_whenRunIt_thenResult() throws Exception{
|
||||
Thread thread = new Thread(new SimpleRunnable(
|
||||
"SimpleRunnable executed using Thread"));
|
||||
thread.start();
|
||||
thread.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARunnable_whenSubmitToES_thenResult() throws Exception{
|
||||
|
||||
executorService.submit(new SimpleRunnable(
|
||||
"SimpleRunnable executed using ExecutorService")).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARunnableLambda_whenSubmitToES_thenResult()
|
||||
throws Exception{
|
||||
|
||||
executorService.submit(()->
|
||||
log.info("Lambda runnable executed!!!")).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAThread_whenRunIt_thenResult() throws Exception{
|
||||
Thread thread = new SimpleThread(
|
||||
"SimpleThread executed using Thread");
|
||||
thread.start();
|
||||
thread.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAThread_whenSubmitToES_thenResult() throws Exception{
|
||||
|
||||
executorService.submit(new SimpleThread(
|
||||
"SimpleThread executed using ExecutorService")).get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACallable_whenSubmitToES_thenResult() throws Exception {
|
||||
|
||||
Future<Integer> future = executorService.submit(
|
||||
new SimpleCallable());
|
||||
log.info("Result from callable: {}", future.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACallableAsLambda_whenSubmitToES_thenResult()
|
||||
throws Exception {
|
||||
|
||||
Future<Integer> future = executorService.submit(() -> RandomUtils.nextInt(0, 100));
|
||||
|
||||
log.info("Result from callable: {}", future.get());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() {
|
||||
if ( executorService != null && !executorService.isShutdown()) {
|
||||
executorService.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleThread extends Thread{
|
||||
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(SimpleThread.class);
|
||||
|
||||
private String message;
|
||||
|
||||
SimpleThread(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
log.info(message);
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleRunnable implements Runnable {
|
||||
|
||||
private static final Logger log =
|
||||
LoggerFactory.getLogger(SimpleRunnable.class);
|
||||
|
||||
private String message;
|
||||
|
||||
SimpleRunnable(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
log.info(message);
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleCallable implements Callable<Integer> {
|
||||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
return RandomUtils.nextInt(0, 100);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.concurrent.stopping;
|
||||
|
||||
import com.jayway.awaitility.Awaitility;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StopThreadTest {
|
||||
|
||||
@Test
|
||||
public void whenStoppedThreadIsStopped() throws InterruptedException {
|
||||
|
||||
int interval = 100;
|
||||
|
||||
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
||||
controlSubThread.start();
|
||||
|
||||
// Give things a chance to get set up
|
||||
Thread.sleep(interval);
|
||||
assertTrue(controlSubThread.isRunning());
|
||||
assertFalse(controlSubThread.isStopped());
|
||||
|
||||
// Stop it and make sure the flags have been reversed
|
||||
controlSubThread.stop();
|
||||
await()
|
||||
.until(() -> assertTrue(controlSubThread.isStopped()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
||||
|
||||
int interval = 5000;
|
||||
|
||||
ControlSubThread controlSubThread = new ControlSubThread(interval);
|
||||
controlSubThread.start();
|
||||
|
||||
// Give things a chance to get set up
|
||||
Thread.sleep(100);
|
||||
assertTrue(controlSubThread.isRunning());
|
||||
assertFalse(controlSubThread.isStopped());
|
||||
|
||||
// Stop it and make sure the flags have been reversed
|
||||
controlSubThread.interrupt();
|
||||
|
||||
// Wait less than the time we would normally sleep, and make sure we exited.
|
||||
Awaitility.await()
|
||||
.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());
|
||||
}
|
||||
}
|
|
@ -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
|
|
@ -0,0 +1,6 @@
|
|||
=========
|
||||
|
||||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
|
@ -0,0 +1,489 @@
|
|||
<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-sun</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-sun</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>com.sun</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
<version>1.8.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java</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>
|
||||
|
||||
</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>
|
||||
|
||||
|
||||
</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>23.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.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.javac;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.CLASS)
|
||||
@Target({ElementType.PARAMETER})
|
||||
public @interface Positive {
|
||||
}
|
|
@ -0,0 +1,123 @@
|
|||
package com.baeldung.javac;
|
||||
|
||||
import com.sun.source.tree.MethodTree;
|
||||
import com.sun.source.tree.VariableTree;
|
||||
import com.sun.source.util.*;
|
||||
import com.sun.tools.javac.api.BasicJavacTask;
|
||||
import com.sun.tools.javac.code.TypeTag;
|
||||
import com.sun.tools.javac.tree.JCTree;
|
||||
import com.sun.tools.javac.tree.TreeMaker;
|
||||
import com.sun.tools.javac.util.Context;
|
||||
import com.sun.tools.javac.util.Name;
|
||||
import com.sun.tools.javac.util.Names;
|
||||
|
||||
import javax.tools.JavaCompiler;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.sun.tools.javac.util.List.nil;
|
||||
|
||||
/**
|
||||
* A {@link JavaCompiler javac} plugin which inserts {@code >= 0} checks into resulting {@code *.class} files
|
||||
* for numeric method parameters marked by {@link Positive}
|
||||
*/
|
||||
public class SampleJavacPlugin implements Plugin {
|
||||
|
||||
public static final String NAME = "MyPlugin";
|
||||
|
||||
private static Set<String> TARGET_TYPES = new HashSet<>(Arrays.asList(
|
||||
// Use only primitive types for simplicity
|
||||
byte.class.getName(), short.class.getName(), char.class.getName(),
|
||||
int.class.getName(), long.class.getName(), float.class.getName(), double.class.getName()));
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return NAME;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(JavacTask task, String... args) {
|
||||
Context context = ((BasicJavacTask) task).getContext();
|
||||
task.addTaskListener(new TaskListener() {
|
||||
@Override
|
||||
public void started(TaskEvent e) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finished(TaskEvent e) {
|
||||
if (e.getKind() != TaskEvent.Kind.PARSE) {
|
||||
return;
|
||||
}
|
||||
e.getCompilationUnit()
|
||||
.accept(new TreeScanner<Void, Void>() {
|
||||
@Override
|
||||
public Void visitMethod(MethodTree method, Void v) {
|
||||
List<VariableTree> parametersToInstrument = method.getParameters()
|
||||
.stream()
|
||||
.filter(SampleJavacPlugin.this::shouldInstrument)
|
||||
.collect(Collectors.toList());
|
||||
if (!parametersToInstrument.isEmpty()) {
|
||||
// There is a possible case that more than one argument is marked by @Positive,
|
||||
// as the checks are added to the method's body beginning, we process parameters RTL
|
||||
// to ensure correct order.
|
||||
Collections.reverse(parametersToInstrument);
|
||||
parametersToInstrument.forEach(p -> addCheck(method, p, context));
|
||||
}
|
||||
// There is a possible case that there is a nested class declared in a method's body,
|
||||
// hence, we want to proceed with method body AST as well.
|
||||
return super.visitMethod(method, v);
|
||||
}
|
||||
}, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean shouldInstrument(VariableTree parameter) {
|
||||
return TARGET_TYPES.contains(parameter.getType().toString())
|
||||
&& parameter.getModifiers().getAnnotations()
|
||||
.stream()
|
||||
.anyMatch(a -> Positive.class.getSimpleName().equals(a.getAnnotationType().toString()));
|
||||
}
|
||||
|
||||
private void addCheck(MethodTree method, VariableTree parameter, Context context) {
|
||||
JCTree.JCIf check = createCheck(parameter, context);
|
||||
JCTree.JCBlock body = (JCTree.JCBlock) method.getBody();
|
||||
body.stats = body.stats.prepend(check);
|
||||
}
|
||||
|
||||
private static JCTree.JCIf createCheck(VariableTree parameter, Context context) {
|
||||
TreeMaker factory = TreeMaker.instance(context);
|
||||
Names symbolsTable = Names.instance(context);
|
||||
|
||||
return factory.at(((JCTree) parameter).pos)
|
||||
.If(factory.Parens(createIfCondition(factory, symbolsTable, parameter)),
|
||||
createIfBlock(factory, symbolsTable, parameter),
|
||||
null);
|
||||
}
|
||||
|
||||
private static JCTree.JCBinary createIfCondition(TreeMaker factory, Names symbolsTable, VariableTree parameter) {
|
||||
Name parameterId = symbolsTable.fromString(parameter.getName().toString());
|
||||
return factory.Binary(JCTree.Tag.LE,
|
||||
factory.Ident(parameterId),
|
||||
factory.Literal(TypeTag.INT, 0));
|
||||
}
|
||||
|
||||
private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) {
|
||||
String parameterName = parameter.getName().toString();
|
||||
Name parameterId = symbolsTable.fromString(parameterName);
|
||||
|
||||
String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '",
|
||||
parameterName, parameter.getType(), Positive.class.getSimpleName());
|
||||
String errorMessageSuffix = "' for it";
|
||||
|
||||
return factory.Block(0, com.sun.tools.javac.util.List.of(
|
||||
factory.Throw(
|
||||
factory.NewClass(null, nil(),
|
||||
factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())),
|
||||
com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS,
|
||||
factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix),
|
||||
factory.Ident(parameterId)),
|
||||
factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null))));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
log4j.rootLogger=DEBUG, A1
|
||||
|
||||
log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
||||
|
||||
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.javac;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SampleJavacPluginIntegrationTest {
|
||||
|
||||
private static final String CLASS_TEMPLATE =
|
||||
"package com.baeldung.javac;\n" +
|
||||
"\n" +
|
||||
"public class Test {\n" +
|
||||
" public static %1$s service(@Positive %1$s i) {\n" +
|
||||
" return i;\n" +
|
||||
" }\n" +
|
||||
"}\n" +
|
||||
"";
|
||||
|
||||
private TestCompiler compiler = new TestCompiler();
|
||||
private TestRunner runner = new TestRunner();
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenInt_whenNegative_thenThrowsException() throws Throwable {
|
||||
compileAndRun(double.class,-1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenInt_whenZero_thenThrowsException() throws Throwable {
|
||||
compileAndRun(int.class,0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInt_whenPositive_thenSuccess() throws Throwable {
|
||||
assertEquals(1, compileAndRun(int.class, 1));
|
||||
}
|
||||
|
||||
private Object compileAndRun(Class<?> argumentType, Object argument) throws Throwable {
|
||||
String qualifiedClassName = "com.baeldung.javac.Test";
|
||||
byte[] byteCode = compiler.compile(qualifiedClassName, String.format(CLASS_TEMPLATE, argumentType.getName()));
|
||||
return runner.run(byteCode, qualifiedClassName, "service", new Class[] {argumentType}, argument);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.javac;
|
||||
|
||||
import javax.tools.SimpleJavaFileObject;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URI;
|
||||
|
||||
/** Holds compiled byte code in a byte array */
|
||||
public class SimpleClassFile extends SimpleJavaFileObject {
|
||||
|
||||
private ByteArrayOutputStream out;
|
||||
|
||||
public SimpleClassFile(URI uri) {
|
||||
super(uri, Kind.CLASS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutputStream openOutputStream() throws IOException {
|
||||
return out = new ByteArrayOutputStream();
|
||||
}
|
||||
|
||||
public byte[] getCompiledBinaries() {
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.javac;
|
||||
|
||||
import javax.tools.*;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Adapts {@link SimpleClassFile} to the {@link JavaCompiler} */
|
||||
public class SimpleFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
|
||||
|
||||
private final List<SimpleClassFile> compiled = new ArrayList<>();
|
||||
|
||||
public SimpleFileManager(StandardJavaFileManager delegate) {
|
||||
super(delegate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JavaFileObject getJavaFileForOutput(Location location,
|
||||
String className,
|
||||
JavaFileObject.Kind kind,
|
||||
FileObject sibling)
|
||||
{
|
||||
SimpleClassFile result = new SimpleClassFile(URI.create("string://" + className));
|
||||
compiled.add(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return compiled binaries processed by the current class
|
||||
*/
|
||||
public List<SimpleClassFile> getCompiled() {
|
||||
return compiled;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue