Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
4f74fb6650
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2017 Eugen Paraschiv
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
@ -1,9 +1,14 @@
|
|||||||
|
|
||||||
The "REST with Spring" Classes
|
The "REST with Spring" Classes
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
|
And here's the Master Class of Learn Spring Security: <br/>
|
||||||
|
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Spring Tutorials
|
Spring Tutorials
|
||||||
================
|
================
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -28,8 +28,14 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>3.8.1</version>
|
<version>4.12</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>hamcrest-core</artifactId>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
2
cas/cas-secured-app/README.md
Normal file
2
cas/cas-secured-app/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
## Relevant articles:
|
||||||
|
- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso)
|
@ -14,7 +14,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>2.0.0.BUILD-SNAPSHOT</version>
|
<version>2.0.0.M7</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
@ -87,14 +87,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
|
||||||
<id>spring-snapshots</id>
|
|
||||||
<name>Spring Snapshots</name>
|
|
||||||
<url>https://repo.spring.io/snapshot</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
<repository>
|
||||||
<id>spring-milestones</id>
|
<id>spring-milestones</id>
|
||||||
<name>Spring Milestones</name>
|
<name>Spring Milestones</name>
|
||||||
@ -106,14 +98,6 @@
|
|||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
<pluginRepositories>
|
<pluginRepositories>
|
||||||
<pluginRepository>
|
|
||||||
<id>spring-snapshots</id>
|
|
||||||
<name>Spring Snapshots</name>
|
|
||||||
<url>https://repo.spring.io/snapshot</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
<pluginRepository>
|
<pluginRepository>
|
||||||
<id>spring-milestones</id>
|
<id>spring-milestones</id>
|
||||||
<name>Spring Milestones</name>
|
<name>Spring Milestones</name>
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.cassecuredapp.controllers;
|
package com.baeldung.cassecuredapp.controllers;
|
||||||
|
|
||||||
import org.apache.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
||||||
@ -15,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||||||
@Controller
|
@Controller
|
||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private Logger logger = Logger.getLogger(AuthController.class);
|
private Logger logger = LogManager.getLogger(AuthController.class);
|
||||||
|
|
||||||
@GetMapping("/logout")
|
@GetMapping("/logout")
|
||||||
public String logout(
|
public String logout(
|
||||||
|
@ -30,3 +30,6 @@
|
|||||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||||
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
||||||
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||||
|
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||||
|
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||||
|
- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers)
|
||||||
|
@ -83,6 +83,24 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-bytecode</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -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() {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -1,35 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class which shows different ways of converting java.util.Date into java.time.LocalDate.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateConverter {
|
|
||||||
|
|
||||||
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
|
|
||||||
return dateToConvert.toInstant()
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDate();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
|
|
||||||
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
|
|
||||||
return Instant.ofEpochMilli(dateToConvert.getTime())
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDate();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class which shows different ways of converting java.util.Date into java.time.LocalDateTime.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateTimeConverter {
|
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
|
|
||||||
return dateToConvert.toInstant()
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDateTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
|
|
||||||
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
|
|
||||||
return Instant.ofEpochMilli(dateToConvert.getTime())
|
|
||||||
.atZone(ZoneId.systemDefault())
|
|
||||||
.toLocalDateTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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,45 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Fork;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
|
||||||
|
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||||
|
|
||||||
|
@Fork(value = 1, warmups = 3)
|
||||||
|
@BenchmarkMode(Mode.All)
|
||||||
|
public class CounterStatistics {
|
||||||
|
|
||||||
|
private static final Map<String, Integer> counterMap = new HashMap<>();
|
||||||
|
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
|
||||||
|
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
|
||||||
|
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void wrapperAsCounter() {
|
||||||
|
CounterUtil.counterWithWrapperObject(counterMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void lambdaExpressionWithWrapper() {
|
||||||
|
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void mutableIntegerAsCounter() {
|
||||||
|
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void primitiveArrayAsCounter() {
|
||||||
|
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||||
|
|
||||||
|
public class CounterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
|
||||||
|
Map<String, Integer> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithWrapperObject(counterMap);
|
||||||
|
|
||||||
|
assertEquals(3, counterMap.get("China")
|
||||||
|
.intValue());
|
||||||
|
assertEquals(2, counterMap.get("India")
|
||||||
|
.intValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
|
||||||
|
Map<String, Long> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithLambdaAndWrapper(counterMap);
|
||||||
|
|
||||||
|
assertEquals(3l, counterMap.get("China")
|
||||||
|
.longValue());
|
||||||
|
assertEquals(2l, counterMap.get("India")
|
||||||
|
.longValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
|
||||||
|
Map<String, MutableInteger> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithMutableInteger(counterMap);
|
||||||
|
assertEquals(3, counterMap.get("China")
|
||||||
|
.getCount());
|
||||||
|
assertEquals(2, counterMap.get("India")
|
||||||
|
.getCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithPrimitiveArray_runsSuccessfully() {
|
||||||
|
Map<String, int[]> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithPrimitiveArray(counterMap);
|
||||||
|
assertEquals(3, counterMap.get("China")[0]);
|
||||||
|
assertEquals(2, counterMap.get("India")[0]);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class CounterUtil {
|
||||||
|
|
||||||
|
private final static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||||
|
|
||||||
|
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
|
||||||
|
counterMap.putAll(Stream.of(COUNTRY_NAMES)
|
||||||
|
.parallel()
|
||||||
|
.collect(Collectors.groupingBy(k -> k, Collectors.counting())));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class MutableInteger {
|
||||||
|
int count;
|
||||||
|
|
||||||
|
public MutableInteger(int count) {
|
||||||
|
this.count = count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void increment() {
|
||||||
|
this.count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCount() {
|
||||||
|
return this.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
MutableInteger oldValue = counterMap.get(country);
|
||||||
|
if (oldValue != null) {
|
||||||
|
oldValue.increment();
|
||||||
|
} else {
|
||||||
|
counterMap.put(country, new MutableInteger(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
int[] oldCounter = counterMap.get(country);
|
||||||
|
if (oldCounter != null) {
|
||||||
|
oldCounter[0] += 1;
|
||||||
|
} else {
|
||||||
|
counterMap.put(country, new int[] { 1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,72 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.time.temporal.ChronoField;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* JUnits for {@link DateToLocalDateConverter} class.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateConverterTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,78 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
package com.baeldung.datetime;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.temporal.ChronoField;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* JUnits for {@link DateToLocalDateTimeConverter} class.
|
|
||||||
*
|
|
||||||
* @author abialas
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
public class DateToLocalDateTimeConverterTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10, 8, 20);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
|
||||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10, 8, 20);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
|
||||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
|
|
||||||
// given
|
|
||||||
Calendar calendar = Calendar.getInstance();
|
|
||||||
calendar.set(2010, 10, 10, 8, 20);
|
|
||||||
Date dateToConvert = calendar.getTime();
|
|
||||||
|
|
||||||
// when
|
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
|
|
||||||
|
|
||||||
// then
|
|
||||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
|
||||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
|
||||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
|
||||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
|
||||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -18,3 +18,4 @@
|
|||||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||||
|
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||||
|
3
core-java-9/compile-httpclient.bat
Normal file
3
core-java-9/compile-httpclient.bat
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
javac --module-path mods -d mods/com.baeldung.httpclient^
|
||||||
|
src/modules/com.baeldung.httpclient/module-info.java^
|
||||||
|
src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java
|
1
core-java-9/run-httpclient.bat
Normal file
1
core-java-9/run-httpclient.bat
Normal file
@ -0,0 +1 @@
|
|||||||
|
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample
|
@ -3,18 +3,35 @@
|
|||||||
*/
|
*/
|
||||||
package com.baeldung.java9.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class which shows a way to convert java.util.Date into java.time.LocalDate with new Java 1.9.
|
* Class which shows a way to convert java.util.Date into java.time.LocalDate.
|
||||||
*
|
*
|
||||||
* @author abialas
|
* @author abialas
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class DateToLocalDateConverter {
|
public class DateToLocalDateConverter {
|
||||||
|
|
||||||
|
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
|
||||||
|
return dateToConvert.toInstant()
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
|
||||||
|
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
|
||||||
|
return Instant.ofEpochMilli(dateToConvert.getTime())
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDate();
|
||||||
|
}
|
||||||
|
|
||||||
public static LocalDate convertToLocalDate(Date dateToConvert) {
|
public static LocalDate convertToLocalDate(Date dateToConvert) {
|
||||||
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||||
}
|
}
|
||||||
|
@ -3,18 +3,35 @@
|
|||||||
*/
|
*/
|
||||||
package com.baeldung.java9.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime with new Java 1.9.
|
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime.
|
||||||
*
|
*
|
||||||
* @author abialas
|
* @author abialas
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class DateToLocalDateTimeConverter {
|
public class DateToLocalDateTimeConverter {
|
||||||
|
|
||||||
|
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
|
||||||
|
return dateToConvert.toInstant()
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
|
||||||
|
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
|
||||||
|
return Instant.ofEpochMilli(dateToConvert.getTime())
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDateTime();
|
||||||
|
}
|
||||||
|
|
||||||
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
|
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
|
||||||
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* To change this license header, choose License Headers in Project Properties.
|
||||||
|
* To change this template file, choose Tools | Templates
|
||||||
|
* and open the template in the editor.
|
||||||
|
*/
|
||||||
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import jdk.incubator.http.HttpClient;
|
||||||
|
import jdk.incubator.http.HttpRequest;
|
||||||
|
import jdk.incubator.http.HttpRequest.BodyProcessor;
|
||||||
|
import jdk.incubator.http.HttpResponse;
|
||||||
|
import jdk.incubator.http.HttpResponse.BodyHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @author pkaria
|
||||||
|
*/
|
||||||
|
public class HttpClientExample {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
httpGetRequest();
|
||||||
|
httpPostRequest();
|
||||||
|
asynchronousRequest();
|
||||||
|
asynchronousMultipleRequests();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
|
||||||
|
.headers("Accept-Enconding", "gzip, deflate").build();
|
||||||
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
String responseBody = response.body();
|
||||||
|
int responseStatusCode = response.statusCode();
|
||||||
|
System.out.println(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient
|
||||||
|
.newBuilder()
|
||||||
|
.build();
|
||||||
|
HttpRequest request = HttpRequest
|
||||||
|
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
|
||||||
|
.POST(BodyProcessor.fromString("Sample Post Request"))
|
||||||
|
.build();
|
||||||
|
HttpResponse<String> response
|
||||||
|
= client.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
String responseBody = response.body();
|
||||||
|
System.out.println(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void asynchronousRequest() throws URISyntaxException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
|
||||||
|
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
|
||||||
|
HttpResponse.BodyHandler.asString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void asynchronousMultipleRequests() throws URISyntaxException {
|
||||||
|
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
List<CompletableFuture<File>> futures = targets
|
||||||
|
.stream()
|
||||||
|
.map(target -> client
|
||||||
|
.sendAsync(
|
||||||
|
HttpRequest.newBuilder(target)
|
||||||
|
.GET()
|
||||||
|
.build(),
|
||||||
|
BodyHandler.asFile(Paths.get("base", target.getPath())))
|
||||||
|
.thenApply(response -> response.body())
|
||||||
|
.thenApply(path -> path.toFile()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
module com.baeldung.httpclient {
|
||||||
|
requires jdk.incubator.httpclient;
|
||||||
|
}
|
@ -22,6 +22,54 @@ import com.baeldung.java9.datetime.DateToLocalDateConverter;
|
|||||||
*/
|
*/
|
||||||
public class DateToLocalDateConverterTest {
|
public class DateToLocalDateConverterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
|
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
|
||||||
// given
|
// given
|
||||||
|
@ -29,6 +29,60 @@ public class DateToLocalDateTimeConverterTest {
|
|||||||
calendar.set(2010, 10, 10, 8, 20);
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
Date dateToConvert = calendar.getTime();
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
|
// when
|
||||||
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||||
|
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||||
|
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
|
||||||
|
// given
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.set(2010, 10, 10, 8, 20);
|
||||||
|
Date dateToConvert = calendar.getTime();
|
||||||
|
|
||||||
// when
|
// when
|
||||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
|
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package com.baeldung.datetime;
|
package com.baeldung.java9.datetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
@ -31,3 +31,5 @@
|
|||||||
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
||||||
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
||||||
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
||||||
|
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
|
||||||
|
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
|
||||||
|
@ -3,7 +3,6 @@ package com.baeldung.concurrent.daemon;
|
|||||||
public class NewThread extends Thread {
|
public class NewThread extends Thread {
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
|
|
||||||
long startTime = System.currentTimeMillis();
|
long startTime = System.currentTimeMillis();
|
||||||
while (true) {
|
while (true) {
|
||||||
for (int i = 0; i < 10; i++) {
|
for (int i = 0; i < 10; i++) {
|
||||||
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
public class Data {
|
||||||
|
private String packet;
|
||||||
|
|
||||||
|
// True if receiver should wait
|
||||||
|
// False if sender should wait
|
||||||
|
private boolean transfer = true;
|
||||||
|
|
||||||
|
public synchronized String receive() {
|
||||||
|
while (transfer) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
transfer = true;
|
||||||
|
|
||||||
|
notifyAll();
|
||||||
|
return packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void send(String packet) {
|
||||||
|
while (!transfer) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
transfer = false;
|
||||||
|
|
||||||
|
this.packet = packet;
|
||||||
|
notifyAll();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
public class NetworkDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Data data = new Data();
|
||||||
|
Thread sender = new Thread(new Sender(data));
|
||||||
|
Thread receiver = new Thread(new Receiver(data));
|
||||||
|
|
||||||
|
sender.start();
|
||||||
|
receiver.start();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class Receiver implements Runnable {
|
||||||
|
private Data load;
|
||||||
|
|
||||||
|
public Receiver(Data load) {
|
||||||
|
this.load = load;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
for(String receivedMessage = load.receive();
|
||||||
|
!"End".equals(receivedMessage) ;
|
||||||
|
receivedMessage = load.receive()) {
|
||||||
|
|
||||||
|
System.out.println(receivedMessage);
|
||||||
|
|
||||||
|
//Thread.sleep() to mimic heavy server-side processing
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class Sender implements Runnable {
|
||||||
|
private Data data;
|
||||||
|
|
||||||
|
public Sender(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
String packets[] = {
|
||||||
|
"First packet",
|
||||||
|
"Second packet",
|
||||||
|
"Third packet",
|
||||||
|
"Fourth packet",
|
||||||
|
"End"
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String packet : packets) {
|
||||||
|
data.send(packet);
|
||||||
|
|
||||||
|
//Thread.sleep() to mimic heavy server-side processing
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -9,7 +9,6 @@ import java.util.List;
|
|||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
import static junit.framework.TestCase.assertTrue;
|
import static junit.framework.TestCase.assertTrue;
|
||||||
import static org.junit.Assert.fail;
|
|
||||||
|
|
||||||
public class WaitingForThreadsToFinishTest {
|
public class WaitingForThreadsToFinishTest {
|
||||||
|
|
||||||
@ -40,9 +39,7 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
CountDownLatch latch = new CountDownLatch(2);
|
CountDownLatch latch = new CountDownLatch(2);
|
||||||
|
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
WORKER_THREAD_POOL.submit(() -> {
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
try {
|
try {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
latch.countDown();
|
latch.countDown();
|
||||||
@ -50,7 +47,6 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
|
||||||
@Override
|
|
||||||
public String call() throws Exception {
|
|
||||||
fail("This thread should have been rejected !");
|
|
||||||
Thread.sleep(1000000);
|
Thread.sleep(1000000);
|
||||||
return null;
|
return null;
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} catch (RejectedExecutionException ex) {
|
} catch (RejectedExecutionException ex) {
|
||||||
//
|
//
|
||||||
|
@ -1,7 +1,11 @@
|
|||||||
package com.baeldung.concurrent.stopping;
|
package com.baeldung.concurrent.stopping;
|
||||||
|
|
||||||
|
import com.jayway.awaitility.Awaitility;
|
||||||
import org.junit.Test;
|
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.assertFalse;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
@ -22,11 +26,10 @@ public class StopThreadTest {
|
|||||||
|
|
||||||
// Stop it and make sure the flags have been reversed
|
// Stop it and make sure the flags have been reversed
|
||||||
controlSubThread.stop();
|
controlSubThread.stop();
|
||||||
Thread.sleep(interval);
|
await()
|
||||||
assertTrue(controlSubThread.isStopped());
|
.until(() -> assertTrue(controlSubThread.isStopped()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
||||||
|
|
||||||
@ -44,7 +47,8 @@ public class StopThreadTest {
|
|||||||
controlSubThread.interrupt();
|
controlSubThread.interrupt();
|
||||||
|
|
||||||
// Wait less than the time we would normally sleep, and make sure we exited.
|
// Wait less than the time we would normally sleep, and make sure we exited.
|
||||||
Thread.sleep(interval/10);
|
Awaitility.await()
|
||||||
assertTrue(controlSubThread.isStopped());
|
.atMost(interval/ 10, TimeUnit.MILLISECONDS)
|
||||||
|
.until(controlSubThread::isStopped);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class NetworkIntegrationTest {
|
||||||
|
|
||||||
|
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||||
|
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
|
||||||
|
private String expected;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpStreams() {
|
||||||
|
System.setOut(new PrintStream(outContent));
|
||||||
|
System.setErr(new PrintStream(errContent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpExpectedOutput() {
|
||||||
|
StringWriter expectedStringWriter = new StringWriter();
|
||||||
|
|
||||||
|
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
|
||||||
|
printWriter.println("First packet");
|
||||||
|
printWriter.println("Second packet");
|
||||||
|
printWriter.println("Third packet");
|
||||||
|
printWriter.println("Fourth packet");
|
||||||
|
printWriter.close();
|
||||||
|
|
||||||
|
expected = expectedStringWriter.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanUpStreams() {
|
||||||
|
System.setOut(null);
|
||||||
|
System.setErr(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
|
||||||
|
Data data = new Data();
|
||||||
|
Thread sender = new Thread(new Sender(data));
|
||||||
|
Thread receiver = new Thread(new Receiver(data));
|
||||||
|
|
||||||
|
sender.start();
|
||||||
|
receiver.start();
|
||||||
|
|
||||||
|
//wait for sender and receiver to finish before we test against expected
|
||||||
|
try {
|
||||||
|
sender.join();
|
||||||
|
receiver.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(expected, outContent.toString());
|
||||||
|
}
|
||||||
|
}
|
26
core-java-sun/.gitignore
vendored
Normal file
26
core-java-sun/.gitignore
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
*.class
|
||||||
|
|
||||||
|
0.*
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
.resourceCache
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
||||||
|
|
||||||
|
# Files generated by integration tests
|
||||||
|
*.txt
|
||||||
|
backup-pom.xml
|
||||||
|
/bin/
|
||||||
|
/temp
|
||||||
|
|
||||||
|
#IntelliJ specific
|
||||||
|
.idea/
|
||||||
|
*.iml
|
6
core-java-sun/README.md
Normal file
6
core-java-sun/README.md
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
=========
|
||||||
|
|
||||||
|
## Core Java Cookbooks and Examples
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
489
core-java-sun/pom.xml
Normal file
489
core-java-sun/pom.xml
Normal file
@ -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>
|
2
core-java-sun/src/main/java/com/baeldung/README.md
Normal file
2
core-java-sun/src/main/java/com/baeldung/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)
|
6
core-java-sun/src/main/resources/log4j.properties
Normal file
6
core-java-sun/src/main/resources/log4j.properties
Normal file
@ -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
|
@ -117,3 +117,12 @@
|
|||||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||||
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
|
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
|
||||||
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
||||||
|
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
|
||||||
|
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||||
|
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
||||||
|
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||||
|
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||||
|
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
|
||||||
|
- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file)
|
||||||
|
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
|
||||||
|
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||||
|
95
core-java/customers.xml
Normal file
95
core-java/customers.xml
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<webRowSet xmlns="http://java.sun.com/xml/ns/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
|
||||||
|
<properties>
|
||||||
|
<command>SELECT * FROM customers</command>
|
||||||
|
<concurrency>1008</concurrency>
|
||||||
|
<datasource><null/></datasource>
|
||||||
|
<escape-processing>true</escape-processing>
|
||||||
|
<fetch-direction>1000</fetch-direction>
|
||||||
|
<fetch-size>0</fetch-size>
|
||||||
|
<isolation-level>2</isolation-level>
|
||||||
|
<key-columns>
|
||||||
|
</key-columns>
|
||||||
|
<map>
|
||||||
|
</map>
|
||||||
|
<max-field-size>0</max-field-size>
|
||||||
|
<max-rows>0</max-rows>
|
||||||
|
<query-timeout>0</query-timeout>
|
||||||
|
<read-only>true</read-only>
|
||||||
|
<rowset-type>ResultSet.TYPE_SCROLL_INSENSITIVE</rowset-type>
|
||||||
|
<show-deleted>false</show-deleted>
|
||||||
|
<table-name>customers</table-name>
|
||||||
|
<url>jdbc:h2:mem:testdb</url>
|
||||||
|
<sync-provider>
|
||||||
|
<sync-provider-name>com.sun.rowset.providers.RIOptimisticProvider</sync-provider-name>
|
||||||
|
<sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
|
||||||
|
<sync-provider-version>1.0</sync-provider-version>
|
||||||
|
<sync-provider-grade>2</sync-provider-grade>
|
||||||
|
<data-source-lock>1</data-source-lock>
|
||||||
|
</sync-provider>
|
||||||
|
</properties>
|
||||||
|
<metadata>
|
||||||
|
<column-count>2</column-count>
|
||||||
|
<column-definition>
|
||||||
|
<column-index>1</column-index>
|
||||||
|
<auto-increment>false</auto-increment>
|
||||||
|
<case-sensitive>true</case-sensitive>
|
||||||
|
<currency>false</currency>
|
||||||
|
<nullable>0</nullable>
|
||||||
|
<signed>true</signed>
|
||||||
|
<searchable>true</searchable>
|
||||||
|
<column-display-size>11</column-display-size>
|
||||||
|
<column-label>ID</column-label>
|
||||||
|
<column-name>ID</column-name>
|
||||||
|
<schema-name>PUBLIC</schema-name>
|
||||||
|
<column-precision>10</column-precision>
|
||||||
|
<column-scale>0</column-scale>
|
||||||
|
<table-name>CUSTOMERS</table-name>
|
||||||
|
<catalog-name>TESTDB</catalog-name>
|
||||||
|
<column-type>4</column-type>
|
||||||
|
<column-type-name>INTEGER</column-type-name>
|
||||||
|
</column-definition>
|
||||||
|
<column-definition>
|
||||||
|
<column-index>2</column-index>
|
||||||
|
<auto-increment>false</auto-increment>
|
||||||
|
<case-sensitive>true</case-sensitive>
|
||||||
|
<currency>false</currency>
|
||||||
|
<nullable>0</nullable>
|
||||||
|
<signed>true</signed>
|
||||||
|
<searchable>true</searchable>
|
||||||
|
<column-display-size>50</column-display-size>
|
||||||
|
<column-label>NAME</column-label>
|
||||||
|
<column-name>NAME</column-name>
|
||||||
|
<schema-name>PUBLIC</schema-name>
|
||||||
|
<column-precision>50</column-precision>
|
||||||
|
<column-scale>0</column-scale>
|
||||||
|
<table-name>CUSTOMERS</table-name>
|
||||||
|
<catalog-name>TESTDB</catalog-name>
|
||||||
|
<column-type>12</column-type>
|
||||||
|
<column-type-name>VARCHAR</column-type-name>
|
||||||
|
</column-definition>
|
||||||
|
</metadata>
|
||||||
|
<data>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>1</columnValue>
|
||||||
|
<columnValue>Customer1</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>2</columnValue>
|
||||||
|
<columnValue>Customer2</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>3</columnValue>
|
||||||
|
<columnValue>Customer3</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>4</columnValue>
|
||||||
|
<columnValue>Customer4</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>5</columnValue>
|
||||||
|
<columnValue>Customer5</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
</data>
|
||||||
|
</webRowSet>
|
@ -180,7 +180,12 @@
|
|||||||
<artifactId>esapi</artifactId>
|
<artifactId>esapi</artifactId>
|
||||||
<version>2.1.0.1</version>
|
<version>2.1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.196</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.sun.messaging.mq</groupId>
|
<groupId>com.sun.messaging.mq</groupId>
|
||||||
<artifactId>fscontext</artifactId>
|
<artifactId>fscontext</artifactId>
|
||||||
@ -216,13 +221,13 @@
|
|||||||
<artifactId>spring-web</artifactId>
|
<artifactId>spring-web</artifactId>
|
||||||
<version>4.3.4.RELEASE</version>
|
<version>4.3.4.RELEASE</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.sun</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>tools</artifactId>
|
<artifactId>spring-boot-starter</artifactId>
|
||||||
<version>1.8.0</version>
|
<version>1.5.8.RELEASE</version>
|
||||||
<scope>system</scope>
|
|
||||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
public class ArrayBenchmarkRunner {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
|
Options options = new OptionsBuilder()
|
||||||
|
.include(SearchArrayTest.class.getSimpleName()).threads(1)
|
||||||
|
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||||
|
.jvmArgs("-server").build();
|
||||||
|
|
||||||
|
new Runner(options).run();
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
public class ArrayInverter {
|
||||||
|
|
||||||
|
public void invertUsingFor(Object[] array) {
|
||||||
|
for (int i = 0; i < array.length / 2; i++) {
|
||||||
|
Object temp = array[i];
|
||||||
|
array[i] = array[array.length - 1 - i];
|
||||||
|
array[array.length - 1 - i] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void invertUsingCollectionsReverse(Object[] array) {
|
||||||
|
List<Object> list = Arrays.asList(array);
|
||||||
|
Collections.reverse(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object[] invertUsingStreams(final Object[] array) {
|
||||||
|
return IntStream.range(1, array.length + 1).mapToObj(i -> array[array.length - i]).toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void invertUsingCommonsLang(Object[] array) {
|
||||||
|
ArrayUtils.reverse(array);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object[] invertUsingGuava(Object[] array) {
|
||||||
|
List<Object> list = Arrays.asList(array);
|
||||||
|
List<Object> reverted = Lists.reverse(list);
|
||||||
|
return reverted.toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
115
core-java/src/main/java/com/baeldung/array/SearchArrayTest.java
Normal file
115
core-java/src/main/java/com/baeldung/array/SearchArrayTest.java
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||||
|
public class SearchArrayTest {
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayLoop() {
|
||||||
|
|
||||||
|
int count = 1000;
|
||||||
|
String[] strings = seedArray(count);
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
searchLoop(strings, "T");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayAllocNewList() {
|
||||||
|
|
||||||
|
int count = 1000;
|
||||||
|
String[] strings = seedArray(count);
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
searchList(strings, "W");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayAllocNewSet() {
|
||||||
|
|
||||||
|
int count = 1000;
|
||||||
|
String[] strings = seedArray(count);
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
searchSet(strings, "S");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayReuseList() {
|
||||||
|
|
||||||
|
int count = 1000;
|
||||||
|
String[] strings = seedArray(count);
|
||||||
|
|
||||||
|
List<String> asList = Arrays.asList(strings);
|
||||||
|
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
asList.contains("W");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayReuseSet() {
|
||||||
|
|
||||||
|
int count = 1000;
|
||||||
|
String[] strings = seedArray(count);
|
||||||
|
Set<String> asSet = new HashSet<>(Arrays.asList(strings));
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
asSet.contains("S");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayBinarySearch() {
|
||||||
|
|
||||||
|
int count = 1000;
|
||||||
|
String[] strings = seedArray(count);
|
||||||
|
Arrays.sort(strings);
|
||||||
|
|
||||||
|
long startTime = System.nanoTime();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
Arrays.binarySearch(strings, "A");
|
||||||
|
}
|
||||||
|
long duration = System.nanoTime() - startTime;
|
||||||
|
//System.out.println("Binary search: " + duration / 10000);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean searchList(String[] strings, String searchString) {
|
||||||
|
return Arrays.asList(strings).contains(searchString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean searchSet(String[] strings, String searchString) {
|
||||||
|
Set<String> set = new HashSet<>(Arrays.asList(strings));
|
||||||
|
return set.contains(searchString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean searchLoop(String[] strings, String searchString) {
|
||||||
|
for (String s : strings) {
|
||||||
|
if (s.equals(searchString))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String[] seedArray(int length) {
|
||||||
|
|
||||||
|
String[] strings = new String[length];
|
||||||
|
Random random = new Random();
|
||||||
|
for (int i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
strings[i] = String.valueOf(random.nextInt());
|
||||||
|
}
|
||||||
|
return strings;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
51
core-java/src/main/java/com/baeldung/comparable/Player.java
Normal file
51
core-java/src/main/java/com/baeldung/comparable/Player.java
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.comparable;
|
||||||
|
|
||||||
|
public class Player implements Comparable<Player> {
|
||||||
|
|
||||||
|
private int ranking;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
public Player(int ranking, String name, int age) {
|
||||||
|
this.ranking = ranking;
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRanking() {
|
||||||
|
return ranking;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRanking(int ranking) {
|
||||||
|
this.ranking = ranking;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(Player otherPlayer) {
|
||||||
|
return (this.getRanking() - otherPlayer.getRanking());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.comparable;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class PlayerSorter {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
List<Player> footballTeam = new ArrayList<Player>();
|
||||||
|
Player player1 = new Player(59, "John", 20);
|
||||||
|
Player player2 = new Player(67, "Roger", 22);
|
||||||
|
Player player3 = new Player(45, "Steven", 24);
|
||||||
|
footballTeam.add(player1);
|
||||||
|
footballTeam.add(player2);
|
||||||
|
footballTeam.add(player3);
|
||||||
|
|
||||||
|
System.out.println("Before Sorting : " + footballTeam);
|
||||||
|
Collections.sort(footballTeam);
|
||||||
|
System.out.println("After Sorting : " + footballTeam);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
46
core-java/src/main/java/com/baeldung/comparator/Player.java
Normal file
46
core-java/src/main/java/com/baeldung/comparator/Player.java
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
|
public class Player {
|
||||||
|
|
||||||
|
private int ranking;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
public Player(int ranking, String name, int age) {
|
||||||
|
this.ranking = ranking;
|
||||||
|
this.name = name;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getRanking() {
|
||||||
|
return ranking;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRanking(int ranking) {
|
||||||
|
this.ranking = ranking;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
public class PlayerAgeComparator implements Comparator<Player> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||||
|
return (firstPlayer.getAge() - secondPlayer.getAge());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class PlayerAgeSorter {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
List<Player> footballTeam = new ArrayList<Player>();
|
||||||
|
Player player1 = new Player(59, "John", 22);
|
||||||
|
Player player2 = new Player(67, "Roger", 20);
|
||||||
|
Player player3 = new Player(45, "Steven", 24);
|
||||||
|
footballTeam.add(player1);
|
||||||
|
footballTeam.add(player2);
|
||||||
|
footballTeam.add(player3);
|
||||||
|
|
||||||
|
System.out.println("Before Sorting : " + footballTeam);
|
||||||
|
//Instance of PlayerAgeComparator
|
||||||
|
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
|
||||||
|
Collections.sort(footballTeam, playerComparator);
|
||||||
|
System.out.println("After Sorting by age : " + footballTeam);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
|
||||||
|
public class PlayerRankingComparator implements Comparator<Player> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compare(Player firstPlayer, Player secondPlayer) {
|
||||||
|
return (firstPlayer.getRanking() - secondPlayer.getRanking());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.comparator;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class PlayerRankingSorter {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
List<Player> footballTeam = new ArrayList<Player>();
|
||||||
|
Player player1 = new Player(59, "John", 22);
|
||||||
|
Player player2 = new Player(67, "Roger", 20);
|
||||||
|
Player player3 = new Player(45, "Steven", 40);
|
||||||
|
footballTeam.add(player1);
|
||||||
|
footballTeam.add(player2);
|
||||||
|
footballTeam.add(player3);
|
||||||
|
|
||||||
|
System.out.println("Before Sorting : " + footballTeam);
|
||||||
|
//Instance of PlayerRankingComparator
|
||||||
|
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
|
||||||
|
Collections.sort(footballTeam, playerComparator);
|
||||||
|
System.out.println("After Sorting by ranking : " + footballTeam);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public interface AbstractFactory {
|
||||||
|
Animal getAnimal(String toyType) ;
|
||||||
|
Color getColor(String colorType);
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class AbstractPatternDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
AbstractFactory abstractFactory;
|
||||||
|
|
||||||
|
//creating a brown toy dog
|
||||||
|
abstractFactory = FactoryProvider.getFactory("Toy");
|
||||||
|
Animal toy = abstractFactory.getAnimal("Dog");
|
||||||
|
|
||||||
|
abstractFactory = FactoryProvider.getFactory("Color");
|
||||||
|
Color color = abstractFactory.getColor("Brown");
|
||||||
|
|
||||||
|
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,6 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public interface Animal {
|
||||||
|
String getType();
|
||||||
|
String makeSound();
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class AnimalFactory implements AbstractFactory {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Animal getAnimal(String animalType) {
|
||||||
|
if ("Dog".equalsIgnoreCase(animalType)) {
|
||||||
|
return new Dog();
|
||||||
|
} else if ("Duck".equalsIgnoreCase(animalType)) {
|
||||||
|
return new Duck();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Color getColor(String color) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class Brown implements Color {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getColor() {
|
||||||
|
return "brown";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public interface Color {
|
||||||
|
String getColor();
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class ColorFactory implements AbstractFactory {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Color getColor(String colorType) {
|
||||||
|
if ("Brown".equalsIgnoreCase(colorType)) {
|
||||||
|
return new Brown();
|
||||||
|
} else if ("White".equalsIgnoreCase(colorType)) {
|
||||||
|
return new White();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Animal getAnimal(String toyType) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class Dog implements Animal {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getType() {
|
||||||
|
return "Dog";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String makeSound() {
|
||||||
|
return "Barks";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class Duck implements Animal {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getType() {
|
||||||
|
return "Duck";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String makeSound() {
|
||||||
|
return "Squeks";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class FactoryProvider {
|
||||||
|
public static AbstractFactory getFactory(String choice){
|
||||||
|
|
||||||
|
if("Toy".equalsIgnoreCase(choice)){
|
||||||
|
return new AnimalFactory();
|
||||||
|
}
|
||||||
|
else if("Color".equalsIgnoreCase(choice)){
|
||||||
|
return new ColorFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||||
|
|
||||||
|
public class White implements Color {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getColor() {
|
||||||
|
return "White";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,64 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.builder;
|
||||||
|
|
||||||
|
public class BankAccount {
|
||||||
|
private String name;
|
||||||
|
private String accountNumber;
|
||||||
|
private String email;
|
||||||
|
private boolean newsletter;
|
||||||
|
|
||||||
|
//The constructor that takes a builder from which it will create object
|
||||||
|
//the access to this is only provided to builder
|
||||||
|
private BankAccount(BankAccountBuilder builder) {
|
||||||
|
this.name = builder.name;
|
||||||
|
this.accountNumber = builder.accountNumber;
|
||||||
|
this.email = builder.email;
|
||||||
|
this.newsletter = builder.newsletter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class BankAccountBuilder {
|
||||||
|
private String name;
|
||||||
|
private String accountNumber;
|
||||||
|
private String email;
|
||||||
|
private boolean newsletter;
|
||||||
|
|
||||||
|
//All Mandatory parameters goes with this constructor
|
||||||
|
public BankAccountBuilder(String name, String accountNumber) {
|
||||||
|
this.name = name;
|
||||||
|
this.accountNumber = accountNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
//setters for optional parameters which returns this same builder
|
||||||
|
//to support fluent design
|
||||||
|
public BankAccountBuilder withEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BankAccountBuilder wantNewsletter(boolean newsletter) {
|
||||||
|
this.newsletter = newsletter;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
//the actual build method that prepares and returns a BankAccount object
|
||||||
|
public BankAccount build() {
|
||||||
|
return new BankAccount(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//getters
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAccountNumber() {
|
||||||
|
return accountNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isNewsletter() {
|
||||||
|
return newsletter;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.builder;
|
||||||
|
|
||||||
|
public class BuilderPatternDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
BankAccount newAccount = new BankAccount
|
||||||
|
.BankAccountBuilder("Jon", "22738022275")
|
||||||
|
.withEmail("jon@example.com")
|
||||||
|
.wantNewsletter(true)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
System.out.println("Name: " + newAccount.getName());
|
||||||
|
System.out.println("AccountNumber:" + newAccount.getAccountNumber());
|
||||||
|
System.out.println("Email: " + newAccount.getEmail());
|
||||||
|
System.out.println("Want News letter?: " + newAccount.isNewsletter());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.factory;
|
||||||
|
|
||||||
|
public class FactoryDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Polygon p;
|
||||||
|
PolygonFactory factory = new PolygonFactory();
|
||||||
|
|
||||||
|
//get the shape which has 4 sides
|
||||||
|
p = factory.getPolygon(4);
|
||||||
|
System.out.println("The shape with 4 sides is a " + p.getType());
|
||||||
|
|
||||||
|
//get the shape which has 4 sides
|
||||||
|
p = factory.getPolygon(8);
|
||||||
|
System.out.println("The shape with 8 sides is a " + p.getType());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.factory;
|
||||||
|
|
||||||
|
public class Heptagon implements Polygon {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getType() {
|
||||||
|
return "Heptagon";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.factory;
|
||||||
|
|
||||||
|
public class Octagon implements Polygon {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getType() {
|
||||||
|
return "Octagon";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.factory;
|
||||||
|
|
||||||
|
public class Pentagon implements Polygon {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getType() {
|
||||||
|
return "Pentagon";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.designpatterns.creational.factory;
|
||||||
|
|
||||||
|
public interface Polygon {
|
||||||
|
String getType();
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user