Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
3d3c1fe06b
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2017 Eugen Paraschiv
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -1,9 +1,14 @@
|
|||
|
||||
The "REST with Spring" Classes
|
||||
==============================
|
||||
|
||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||
|
||||
And here's the Master Class of Learn Spring Security: <br/>
|
||||
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
|
||||
|
||||
|
||||
Spring Tutorials
|
||||
================
|
||||
|
|
|
@ -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>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -14,7 +14,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.BUILD-SNAPSHOT</version>
|
||||
<version>2.0.0.M7</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
|
@ -87,14 +87,6 @@
|
|||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
|
@ -106,14 +98,6 @@
|
|||
</repositories>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-snapshots</id>
|
||||
<name>Spring Snapshots</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
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.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
||||
|
@ -15,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||
@Controller
|
||||
public class AuthController {
|
||||
|
||||
private Logger logger = Logger.getLogger(AuthController.class);
|
||||
private Logger logger = LogManager.getLogger(AuthController.class);
|
||||
|
||||
@GetMapping("/logout")
|
||||
public String logout(
|
||||
|
|
|
@ -1,258 +1,276 @@
|
|||
<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-8</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-8</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
<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>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<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>
|
||||
</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>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.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>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
</properties>
|
||||
<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-8</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-8</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
<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>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.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>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>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<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>
|
||||
</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>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.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>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
</properties>
|
||||
</project>
|
|
@ -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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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
|
|
@ -0,0 +1 @@
|
|||
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample
|
|
@ -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;
|
||||
}
|
|
@ -3,7 +3,6 @@ package com.baeldung.concurrent.daemon;
|
|||
public class NewThread extends Thread {
|
||||
|
||||
public void run() {
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
while (true) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
|
|
|
@ -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 static junit.framework.TestCase.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class WaitingForThreadsToFinishTest {
|
||||
|
||||
|
@ -40,16 +39,13 @@ public class WaitingForThreadsToFinishTest {
|
|||
CountDownLatch latch = new CountDownLatch(2);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
latch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
WORKER_THREAD_POOL.submit(() -> {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
latch.countDown();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
|
|||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||
|
||||
try {
|
||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
fail("This thread should have been rejected !");
|
||||
Thread.sleep(1000000);
|
||||
return null;
|
||||
}
|
||||
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
|
||||
Thread.sleep(1000000);
|
||||
return null;
|
||||
});
|
||||
} catch (RejectedExecutionException ex) {
|
||||
//
|
||||
|
|
|
@ -1,7 +1,11 @@
|
|||
package com.baeldung.concurrent.stopping;
|
||||
|
||||
import com.jayway.awaitility.Awaitility;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
|
@ -22,11 +26,10 @@ public class StopThreadTest {
|
|||
|
||||
// Stop it and make sure the flags have been reversed
|
||||
controlSubThread.stop();
|
||||
Thread.sleep(interval);
|
||||
assertTrue(controlSubThread.isStopped());
|
||||
await()
|
||||
.until(() -> assertTrue(controlSubThread.isStopped()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenInterruptedThreadIsStopped() throws InterruptedException {
|
||||
|
||||
|
@ -44,7 +47,8 @@ public class StopThreadTest {
|
|||
controlSubThread.interrupt();
|
||||
|
||||
// Wait less than the time we would normally sleep, and make sure we exited.
|
||||
Thread.sleep(interval/10);
|
||||
assertTrue(controlSubThread.isStopped());
|
||||
Awaitility.await()
|
||||
.atMost(interval/ 10, TimeUnit.MILLISECONDS)
|
||||
.until(controlSubThread::isStopped);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.concurrent.waitandnotify;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NetworkIntegrationTest {
|
||||
|
||||
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
|
||||
private String expected;
|
||||
|
||||
@Before
|
||||
public void setUpStreams() {
|
||||
System.setOut(new PrintStream(outContent));
|
||||
System.setErr(new PrintStream(errContent));
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUpExpectedOutput() {
|
||||
StringWriter expectedStringWriter = new StringWriter();
|
||||
|
||||
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
|
||||
printWriter.println("First packet");
|
||||
printWriter.println("Second packet");
|
||||
printWriter.println("Third packet");
|
||||
printWriter.println("Fourth packet");
|
||||
printWriter.close();
|
||||
|
||||
expected = expectedStringWriter.toString();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanUpStreams() {
|
||||
System.setOut(null);
|
||||
System.setErr(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
|
||||
Data data = new Data();
|
||||
Thread sender = new Thread(new Sender(data));
|
||||
Thread receiver = new Thread(new Receiver(data));
|
||||
|
||||
sender.start();
|
||||
receiver.start();
|
||||
|
||||
//wait for sender and receiver to finish before we test against expected
|
||||
try {
|
||||
sender.join();
|
||||
receiver.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
assertEquals(expected, outContent.toString());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,6 @@
|
|||
=========
|
||||
|
||||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
|
@ -0,0 +1,489 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-sun</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java-sun</name>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>net.sourceforge.collections</groupId>
|
||||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
<!-- marshalling -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- logging -->
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>1.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.javamoney</groupId>
|
||||
<artifactId>moneta</artifactId>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
<artifactId>esapi</artifactId>
|
||||
<version>2.1.0.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.sun.messaging.mq</groupId>
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun</groupId>
|
||||
<artifactId>tools</artifactId>
|
||||
<version>1.8.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classifier>spring-boot</classifier>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
|
||||
<arguments>
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*ManualTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<classpathScope>test</classpathScope>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.8.5</jackson.version>
|
||||
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>23.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<fscontext.version>4.6-b01</fscontext.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>2.8.9</mockito.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java)
|
|
@ -0,0 +1,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
|
|
@ -119,4 +119,6 @@
|
|||
- [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)
|
||||
|
||||
|
|
|
@ -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>
|
|
@ -1,491 +1,496 @@
|
|||
<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</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
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</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>core-java</name>
|
||||
<name>core-java</name>
|
||||
|
||||
<dependencies>
|
||||
<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>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
<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>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>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<plugins>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
|
||||
</configuration>
|
||||
</plugin>
|
||||
<dependency>
|
||||
<groupId>org.decimal4j</groupId>
|
||||
<artifactId>decimal4j</artifactId>
|
||||
<version>${decimal4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
<version>${bouncycastle.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>org.unix4j</groupId>
|
||||
<artifactId>unix4j-command</artifactId>
|
||||
<version>${unix4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>com.googlecode.grep4j</groupId>
|
||||
<artifactId>grep4j</artifactId>
|
||||
<version>${grep4j.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
<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>
|
||||
<!-- marshalling -->
|
||||
|
||||
<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>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<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>
|
||||
<!-- 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>
|
||||
|
||||
<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>
|
||||
<!-- 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.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>1.4.196</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.messaging.mq</groupId>
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.5.8.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
</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>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
</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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<!-- 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>
|
||||
<!-- util -->
|
||||
<guava.version>22.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<unix4j.version>0.4</unix4j.version>
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<fscontext.version>4.6-b01</fscontext.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
|
||||
<!-- 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>
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>2.8.9</mockito.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,130 @@
|
|||
package com.baeldung.array;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class SearchArrayTest {
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
public void searchArrayLoop() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
searchLoop(strings, "T");
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
public void searchArrayAllocNewList() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
searchList(strings, "W");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
public void searchArrayAllocNewSet() {
|
||||
|
||||
int count = 1000;
|
||||
String[] strings = seedArray(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
searchSet(strings, "S");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
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
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
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
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@Warmup(iterations = 5)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -11,7 +11,7 @@ public class PolygonFactory {
|
|||
if(numberOfSides == 5) {
|
||||
return new Pentagon();
|
||||
}
|
||||
if(numberOfSides == 4) {
|
||||
if(numberOfSides == 7) {
|
||||
return new Heptagon();
|
||||
}
|
||||
else if(numberOfSides == 8) {
|
||||
|
@ -19,4 +19,4 @@ public class PolygonFactory {
|
|||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.interfaces;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class CommaSeparatedCustomers implements Customer.List {
|
||||
|
||||
private List<Customer> customers = new ArrayList<Customer>();
|
||||
|
||||
@Override
|
||||
public void Add(Customer customer) {
|
||||
customers.add(customer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCustomerNames() {
|
||||
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.interfaces;
|
||||
|
||||
public class Customer {
|
||||
public interface List {
|
||||
void Add(Customer customer);
|
||||
|
||||
String getCustomerNames();
|
||||
}
|
||||
|
||||
private String name;
|
||||
|
||||
public Customer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.jdbcrowset;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import javax.sql.rowset.JdbcRowSet;
|
||||
import javax.sql.rowset.RowSetFactory;
|
||||
import javax.sql.rowset.RowSetProvider;
|
||||
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
public class DatabaseConfiguration {
|
||||
|
||||
|
||||
public static Connection geth2Connection() throws Exception {
|
||||
Class.forName("org.h2.Driver");
|
||||
System.out.println("Driver Loaded.");
|
||||
String url = "jdbc:h2:mem:testdb";
|
||||
return DriverManager.getConnection(url, "sa", "");
|
||||
}
|
||||
|
||||
public static void initDatabase(Statement stmt) throws SQLException{
|
||||
int iter = 1;
|
||||
while(iter<=5){
|
||||
String customer = "Customer"+iter;
|
||||
String sql ="INSERT INTO customers(id, name) VALUES ("+iter+ ",'"+customer+"');";
|
||||
System.out.println("here is sql statmeent for execution: " + sql);
|
||||
stmt.executeUpdate(sql);
|
||||
iter++;
|
||||
}
|
||||
|
||||
int iterb = 1;
|
||||
while(iterb<=5){
|
||||
String associate = "Associate"+iter;
|
||||
String sql = "INSERT INTO associates(id, name) VALUES("+iterb+",'"+associate+"');";
|
||||
System.out.println("here is sql statement for associate:"+ sql);
|
||||
stmt.executeUpdate(sql);
|
||||
iterb++;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.jdbcrowset;
|
||||
|
||||
import javax.sql.RowSetEvent;
|
||||
import javax.sql.RowSetListener;
|
||||
|
||||
public class ExampleListener implements RowSetListener {
|
||||
|
||||
|
||||
public void cursorMoved(RowSetEvent event) {
|
||||
System.out.println("ExampleListener alerted of cursorMoved event");
|
||||
System.out.println(event.toString());
|
||||
}
|
||||
|
||||
public void rowChanged(RowSetEvent event) {
|
||||
System.out.println("ExampleListener alerted of rowChanged event");
|
||||
System.out.println(event.toString());
|
||||
}
|
||||
|
||||
public void rowSetChanged(RowSetEvent event) {
|
||||
System.out.println("ExampleListener alerted of rowSetChanged event");
|
||||
System.out.println(event.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.jdbcrowset;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.sql.RowSet;
|
||||
import javax.sql.rowset.Predicate;
|
||||
|
||||
public class FilterExample implements Predicate {
|
||||
|
||||
private Pattern pattern;
|
||||
|
||||
public FilterExample(String regexQuery) {
|
||||
if (regexQuery != null && !regexQuery.isEmpty()) {
|
||||
pattern = Pattern.compile(regexQuery);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean evaluate(RowSet rs) {
|
||||
try {
|
||||
if (!rs.isAfterLast()) {
|
||||
String name = rs.getString("name");
|
||||
System.out.println(String.format(
|
||||
"Searching for pattern '%s' in %s", pattern.toString(),
|
||||
name));
|
||||
Matcher matcher = pattern.matcher(name);
|
||||
return matcher.matches();
|
||||
} else
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean evaluate(Object value, int column) throws SQLException {
|
||||
throw new UnsupportedOperationException("This operation is unsupported.");
|
||||
}
|
||||
|
||||
public boolean evaluate(Object value, String columnName)
|
||||
throws SQLException {
|
||||
throw new UnsupportedOperationException("This operation is unsupported.");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,139 @@
|
|||
package com.baeldung.jdbcrowset;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import com.sun.rowset.*;
|
||||
|
||||
import javax.sql.rowset.CachedRowSet;
|
||||
import javax.sql.rowset.FilteredRowSet;
|
||||
import javax.sql.rowset.JdbcRowSet;
|
||||
import javax.sql.rowset.JoinRowSet;
|
||||
import javax.sql.rowset.RowSetFactory;
|
||||
import javax.sql.rowset.RowSetProvider;
|
||||
import javax.sql.rowset.WebRowSet;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class JdbcRowsetApplication {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SpringApplication.run(JdbcRowsetApplication.class, args);
|
||||
Statement stmt = null;
|
||||
try {
|
||||
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||
|
||||
String drop = "DROP TABLE IF EXISTS customers, associates;";
|
||||
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
|
||||
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
|
||||
|
||||
stmt = conn.createStatement();
|
||||
stmt.executeUpdate(drop);
|
||||
stmt.executeUpdate(schema);
|
||||
stmt.executeUpdate(schemapartb);
|
||||
// insert data
|
||||
DatabaseConfiguration.initDatabase(stmt);
|
||||
// JdbcRowSet Example
|
||||
String sql = "SELECT * FROM customers";
|
||||
JdbcRowSet jdbcRS;
|
||||
jdbcRS = new JdbcRowSetImpl(conn);
|
||||
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
|
||||
jdbcRS.setCommand(sql);
|
||||
jdbcRS.execute();
|
||||
jdbcRS.addRowSetListener(new ExampleListener());
|
||||
|
||||
while (jdbcRS.next()) {
|
||||
// each call to next, generates a cursorMoved event
|
||||
System.out.println("id=" + jdbcRS.getString(1));
|
||||
System.out.println("name=" + jdbcRS.getString(2));
|
||||
}
|
||||
|
||||
// CachedRowSet Example
|
||||
String username = "sa";
|
||||
String password = "";
|
||||
String url = "jdbc:h2:mem:testdb";
|
||||
CachedRowSet crs = new CachedRowSetImpl();
|
||||
crs.setUsername(username);
|
||||
crs.setPassword(password);
|
||||
crs.setUrl(url);
|
||||
crs.setCommand(sql);
|
||||
crs.execute();
|
||||
crs.addRowSetListener(new ExampleListener());
|
||||
while (crs.next()) {
|
||||
if (crs.getInt("id") == 1) {
|
||||
System.out.println("CRS found customer1 and will remove the record.");
|
||||
crs.deleteRow();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// WebRowSet example
|
||||
WebRowSet wrs = new WebRowSetImpl();
|
||||
wrs.setUsername(username);
|
||||
wrs.setPassword(password);
|
||||
wrs.setUrl(url);
|
||||
wrs.setCommand(sql);
|
||||
wrs.execute();
|
||||
FileOutputStream ostream = new FileOutputStream("customers.xml");
|
||||
wrs.writeXml(ostream);
|
||||
|
||||
// JoinRowSet example
|
||||
CachedRowSetImpl customers = new CachedRowSetImpl();
|
||||
customers.setUsername(username);
|
||||
customers.setPassword(password);
|
||||
customers.setUrl(url);
|
||||
customers.setCommand(sql);
|
||||
customers.execute();
|
||||
|
||||
CachedRowSetImpl associates = new CachedRowSetImpl();
|
||||
associates.setUsername(username);
|
||||
associates.setPassword(password);
|
||||
associates.setUrl(url);
|
||||
String associatesSQL = "SELECT * FROM associates";
|
||||
associates.setCommand(associatesSQL);
|
||||
associates.execute();
|
||||
|
||||
JoinRowSet jrs = new JoinRowSetImpl();
|
||||
final String ID = "id";
|
||||
final String NAME = "name";
|
||||
jrs.addRowSet(customers, ID);
|
||||
jrs.addRowSet(associates, ID);
|
||||
jrs.last();
|
||||
System.out.println("Total rows: " + jrs.getRow());
|
||||
jrs.beforeFirst();
|
||||
while (jrs.next()) {
|
||||
|
||||
String string1 = jrs.getString(ID);
|
||||
String string2 = jrs.getString(NAME);
|
||||
System.out.println("ID: " + string1 + ", NAME: " + string2);
|
||||
}
|
||||
|
||||
// FilteredRowSet example
|
||||
RowSetFactory rsf = RowSetProvider.newFactory();
|
||||
FilteredRowSet frs = rsf.createFilteredRowSet();
|
||||
frs.setCommand("select * from customers");
|
||||
frs.execute(conn);
|
||||
frs.setFilter(new FilterExample("^[A-C].*"));
|
||||
|
||||
ResultSetMetaData rsmd = frs.getMetaData();
|
||||
int columncount = rsmd.getColumnCount();
|
||||
while (frs.next()) {
|
||||
for (int i = 1; i <= columncount; i++) {
|
||||
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
|
||||
}
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.loops;
|
||||
|
||||
public class LoopsInJava {
|
||||
|
||||
public int[] simple_for_loop() {
|
||||
int[] arr = new int[5];
|
||||
for (int i = 0; i < 5; i++) {
|
||||
arr[i] = i;
|
||||
System.out.println("Simple for loop: i - " + i);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public int[] enhanced_for_each_loop() {
|
||||
int[] intArr = { 0, 1, 2, 3, 4 };
|
||||
int[] arr = new int[5];
|
||||
for (int num : intArr) {
|
||||
arr[num] = num;
|
||||
System.out.println("Enhanced for-each loop: i - " + num);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public int[] while_loop() {
|
||||
int i = 0;
|
||||
int[] arr = new int[5];
|
||||
while (i < 5) {
|
||||
arr[i] = i;
|
||||
System.out.println("While loop: i - " + i++);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public int[] do_while_loop() {
|
||||
int i = 0;
|
||||
int[] arr = new int[5];
|
||||
do {
|
||||
arr[i] = i;
|
||||
System.out.println("Do-While loop: i - " + i++);
|
||||
} while (i < 5);
|
||||
return arr;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.polymorphism;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(FileManager.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||
logger.info("File Info: \n" + file1.getFileInfo() + "\n");
|
||||
ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||
.getBytes(), "v1.0.0");
|
||||
logger.info("File Info: \n" + imageFile.getFileInfo());
|
||||
}
|
||||
|
||||
public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) {
|
||||
ImageFile imageFile = new ImageFile(name, height, width, content, version);
|
||||
logger.info("File 2 Info: \n" + imageFile.getFileInfo());
|
||||
return imageFile;
|
||||
}
|
||||
|
||||
public static GenericFile createTextFile(String name, String content, String version) {
|
||||
GenericFile file1 = new TextFile(name, content, version);
|
||||
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||
return file1;
|
||||
}
|
||||
|
||||
public static TextFile createTextFile2(String name, String content, String version) {
|
||||
TextFile file1 = new TextFile(name, content, version);
|
||||
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||
return file1;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.polymorphism;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class GenericFile {
|
||||
private String name;
|
||||
private String extension;
|
||||
private Date dateCreated;
|
||||
private String version;
|
||||
private byte[] content;
|
||||
|
||||
public GenericFile() {
|
||||
this.setDateCreated(new Date());
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getExtension() {
|
||||
return extension;
|
||||
}
|
||||
|
||||
public void setExtension(String extension) {
|
||||
this.extension = extension;
|
||||
}
|
||||
|
||||
public Date getDateCreated() {
|
||||
return dateCreated;
|
||||
}
|
||||
|
||||
public void setDateCreated(Date dateCreated) {
|
||||
this.dateCreated = dateCreated;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(String version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public byte[] getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(byte[] content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return String.format("File Name: %s\n" + " Extension: %s\n" + " Date Created: %s\n" + " Version: %s\n", this.getName(), this.getExtension(), this.getDateCreated(), this.getVersion());
|
||||
}
|
||||
|
||||
public Object read() {
|
||||
return content;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.polymorphism;
|
||||
|
||||
public class ImageFile extends GenericFile {
|
||||
private int height;
|
||||
private int width;
|
||||
|
||||
public ImageFile(String name, int height, int width, byte[] content, String version) {
|
||||
this.setHeight(height);
|
||||
this.setWidth(width);
|
||||
this.setContent(content);
|
||||
this.setName(name);
|
||||
this.setVersion(version);
|
||||
this.setExtension(".jpg");
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return String.format(" %s Height: %d\n Width: %d", super.getFileInfo(), this.getHeight(), this.getWidth());
|
||||
}
|
||||
|
||||
public String read() {
|
||||
return this.getContent()
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.polymorphism;
|
||||
|
||||
public class TextFile extends GenericFile {
|
||||
private int wordCount;
|
||||
|
||||
public TextFile(String name, String content, String version) {
|
||||
String[] words = content.split(" ");
|
||||
this.setWordCount(words.length > 0 ? words.length : 1);
|
||||
this.setContent(content.getBytes());
|
||||
this.setName(name);
|
||||
this.setVersion(version);
|
||||
this.setExtension(".txt");
|
||||
}
|
||||
|
||||
public int getWordCount() {
|
||||
return wordCount;
|
||||
}
|
||||
|
||||
public void setWordCount(int wordCount) {
|
||||
this.wordCount = wordCount;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return String.format(" %s Word Count: %d", super.getFileInfo(), wordCount);
|
||||
}
|
||||
|
||||
public String read() {
|
||||
return this.getContent()
|
||||
.toString();
|
||||
}
|
||||
|
||||
public String read(int limit) {
|
||||
return this.getContent()
|
||||
.toString()
|
||||
.substring(0, limit);
|
||||
}
|
||||
|
||||
public String read(int start, int stop) {
|
||||
return this.getContent()
|
||||
.toString()
|
||||
.substring(start, stop);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,216 @@
|
|||
package com.baeldung.tree;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
|
||||
public class BinaryTree {
|
||||
|
||||
Node root;
|
||||
|
||||
public void add(int value) {
|
||||
|
||||
Node newNode = new Node(value);
|
||||
|
||||
if (root == null) {
|
||||
root = newNode;
|
||||
return;
|
||||
}
|
||||
|
||||
Node parent = root;
|
||||
Node current = root;
|
||||
|
||||
while (true) {
|
||||
|
||||
if (newNode.value < parent.value) {
|
||||
current = parent.left;
|
||||
|
||||
if (current == null) {
|
||||
parent.left = newNode;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
current = parent.right;
|
||||
|
||||
if (current == null) {
|
||||
parent.right = newNode;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
parent = current;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return root == null;
|
||||
}
|
||||
|
||||
public boolean containsNode(int value) {
|
||||
|
||||
Node current = root;
|
||||
|
||||
while (current != null) {
|
||||
|
||||
if (value == current.value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value < current.value) {
|
||||
current = current.left;
|
||||
} else {
|
||||
current = current.right;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void delete(int value) {
|
||||
|
||||
Node current = root;
|
||||
Node parent = root;
|
||||
Node nodeToDelete = null;
|
||||
boolean isLeftChild = false;
|
||||
|
||||
while (nodeToDelete == null && current != null) {
|
||||
|
||||
if (value == current.value) {
|
||||
nodeToDelete = current;
|
||||
} else if (value < current.value) {
|
||||
parent = current;
|
||||
current = current.left;
|
||||
isLeftChild = true;
|
||||
} else {
|
||||
parent = current;
|
||||
current = current.right;
|
||||
isLeftChild = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (nodeToDelete == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 1: no children
|
||||
if (nodeToDelete.left == null && nodeToDelete.right == null) {
|
||||
if (nodeToDelete == root) {
|
||||
root = null;
|
||||
} else if (isLeftChild) {
|
||||
parent.left = null;
|
||||
} else {
|
||||
parent.right = null;
|
||||
}
|
||||
}
|
||||
// Case 2: only 1 child
|
||||
else if (nodeToDelete.right == null) {
|
||||
if (nodeToDelete == root) {
|
||||
root = nodeToDelete.left;
|
||||
} else if (isLeftChild) {
|
||||
parent.left = nodeToDelete.left;
|
||||
} else {
|
||||
parent.right = nodeToDelete.left;
|
||||
}
|
||||
} else if (nodeToDelete.left == null) {
|
||||
if (nodeToDelete == root) {
|
||||
root = nodeToDelete.right;
|
||||
} else if (isLeftChild) {
|
||||
parent.left = nodeToDelete.right;
|
||||
} else {
|
||||
parent.right = nodeToDelete.right;
|
||||
}
|
||||
}
|
||||
// Case 3: 2 children
|
||||
else if (nodeToDelete.left != null && nodeToDelete.right != null) {
|
||||
Node replacement = findReplacement(nodeToDelete);
|
||||
if (nodeToDelete == root) {
|
||||
root = replacement;
|
||||
} else if (isLeftChild) {
|
||||
parent.left = replacement;
|
||||
} else {
|
||||
parent.right = replacement;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Node findReplacement(Node nodeToDelete) {
|
||||
|
||||
Node replacement = nodeToDelete;
|
||||
Node parentReplacement = nodeToDelete;
|
||||
Node current = nodeToDelete.right;
|
||||
|
||||
while (current != null) {
|
||||
parentReplacement = replacement;
|
||||
replacement = current;
|
||||
current = current.left;
|
||||
}
|
||||
|
||||
if (replacement != nodeToDelete.right) {
|
||||
parentReplacement.left = replacement.right;
|
||||
replacement.right = nodeToDelete.right;
|
||||
}
|
||||
|
||||
replacement.left = nodeToDelete.left;
|
||||
|
||||
return replacement;
|
||||
}
|
||||
|
||||
public void traverseInOrder(Node node) {
|
||||
if (node != null) {
|
||||
traverseInOrder(node.left);
|
||||
System.out.print(" " + node.value);
|
||||
traverseInOrder(node.right);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrder(Node node) {
|
||||
if (node != null) {
|
||||
System.out.print(" " + node.value);
|
||||
traversePreOrder(node.left);
|
||||
traversePreOrder(node.right);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrder(Node node) {
|
||||
if (node != null) {
|
||||
traversePostOrder(node.left);
|
||||
traversePostOrder(node.right);
|
||||
|
||||
System.out.print(" " + node.value);
|
||||
}
|
||||
}
|
||||
|
||||
public void traverseLevelOrder() {
|
||||
Queue<Node> nodes = new LinkedList<>();
|
||||
nodes.add(root);
|
||||
|
||||
while (!nodes.isEmpty()) {
|
||||
|
||||
Node node = nodes.remove();
|
||||
|
||||
System.out.print(" " + node.value);
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.left);
|
||||
}
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Node {
|
||||
int value;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
Node(int value) {
|
||||
this.value = value;
|
||||
right = null;
|
||||
left = null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
|
||||
public class StreamUtils {
|
||||
|
||||
public static String getStringFromInputStream(InputStream input) throws IOException {
|
||||
StringWriter writer = new StringWriter();
|
||||
IOUtils.copy(input, writer, "UTF-8");
|
||||
return writer.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
UK
|
||||
US
|
||||
Germany
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.array;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ArrayInverterUnitTest {
|
||||
|
||||
private String[] fruits = { "apples", "tomatoes", "bananas", "guavas", "pineapples", "oranges" };
|
||||
|
||||
@Test
|
||||
public void invertArrayWithForLoop() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
inverter.invertUsingFor(fruits);
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithCollectionsReverse() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
inverter.invertUsingCollectionsReverse(fruits);
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithStreams() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingStreams(fruits));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithCommonsLang() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
inverter.invertUsingCommonsLang(fruits);
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invertArrayWithGuava() {
|
||||
ArrayInverter inverter = new ArrayInverter();
|
||||
|
||||
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingGuava(fruits));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.arraydeque;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ArrayDequeTest {
|
||||
|
||||
@Test
|
||||
public void whenOffer_addsAtLast() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.offer("first");
|
||||
deque.offer("second");
|
||||
|
||||
assertEquals("second", deque.getLast());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPoll_removesFirst() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.offer("first");
|
||||
deque.offer("second");
|
||||
|
||||
assertEquals("first", deque.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPush_addsAtFirst() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.push("first");
|
||||
deque.push("second");
|
||||
|
||||
assertEquals("second", deque.getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPop_removesLast() {
|
||||
final Deque<String> deque = new ArrayDeque<>();
|
||||
|
||||
deque.push("first");
|
||||
deque.push("second");
|
||||
|
||||
assertEquals("second", deque.pop());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,93 @@
|
|||
package com.baeldung.collection;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WhenUsingHashSet {
|
||||
|
||||
@Test
|
||||
public void whenAddingElement_shouldAddElement() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
Assert.assertTrue(hashset.add("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForElement_shouldSearchForElement() {
|
||||
Set<String> hashsetContains = new HashSet<>();
|
||||
hashsetContains.add("String Added");
|
||||
Assert.assertTrue(hashsetContains.contains("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() {
|
||||
Set<String> hashSetSize = new HashSet<>();
|
||||
hashSetSize.add("String Added");
|
||||
Assert.assertEquals(1, hashSetSize.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() {
|
||||
Set<String> emptyHashSet = new HashSet<>();
|
||||
Assert.assertTrue(emptyHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingElement_shouldRemoveElement() {
|
||||
Set<String> removeFromHashSet = new HashSet<>();
|
||||
removeFromHashSet.add("String Added");
|
||||
Assert.assertTrue(removeFromHashSet.remove("String Added"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenClearingHashSet_shouldClearHashSet() {
|
||||
Set<String> clearHashSet = new HashSet<>();
|
||||
clearHashSet.add("String Added");
|
||||
clearHashSet.clear();
|
||||
Assert.assertTrue(clearHashSet.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratingHashSet_shouldIterateHashSet() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
hashset.add("First");
|
||||
hashset.add("Second");
|
||||
hashset.add("Third");
|
||||
Iterator<String> itr = hashset.iterator();
|
||||
while (itr.hasNext()) {
|
||||
System.out.println(itr.next());
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenModifyingHashSetWhileIterating_shouldThrowException() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
hashset.add("First");
|
||||
hashset.add("Second");
|
||||
hashset.add("Third");
|
||||
Iterator<String> itr = hashset.iterator();
|
||||
while (itr.hasNext()) {
|
||||
itr.next();
|
||||
hashset.remove("Second");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
|
||||
Set<String> hashset = new HashSet<>();
|
||||
hashset.add("First");
|
||||
hashset.add("Second");
|
||||
hashset.add("Third");
|
||||
Iterator<String> itr = hashset.iterator();
|
||||
while (itr.hasNext()) {
|
||||
String element = itr.next();
|
||||
if (element.equals("Second"))
|
||||
itr.remove();
|
||||
}
|
||||
Assert.assertEquals(2, hashset.size());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.comparable;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ComparableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingComparable_thenSortedList() {
|
||||
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);
|
||||
Collections.sort(footballTeam);
|
||||
assertEquals(footballTeam.get(0)
|
||||
.getName(), "Steven");
|
||||
assertEquals(footballTeam.get(2)
|
||||
.getRanking(), 67);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.comparator;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ComparatorUnitTest {
|
||||
|
||||
List<Player> footballTeam;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRankingComparator_thenSortedList() {
|
||||
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
|
||||
Collections.sort(footballTeam, playerComparator);
|
||||
assertEquals(footballTeam.get(0)
|
||||
.getName(), "Steven");
|
||||
assertEquals(footballTeam.get(2)
|
||||
.getRanking(), 67);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingAgeComparator_thenSortedList() {
|
||||
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
|
||||
Collections.sort(footballTeam, playerComparator);
|
||||
assertEquals(footballTeam.get(0)
|
||||
.getName(), "John");
|
||||
assertEquals(footballTeam.get(2)
|
||||
.getRanking(), 45);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package com.baeldung.comparator;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8ComparatorUnitTest {
|
||||
|
||||
List<Player> footballTeam;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparing_UsingLambda_thenSorted() {
|
||||
System.out.println("************** Java 8 Comaparator **************");
|
||||
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
Collections.sort(footballTeam, byRanking);
|
||||
System.out.println("After Sorting : " + footballTeam);
|
||||
assertEquals(footballTeam.get(0)
|
||||
.getName(), "Steven");
|
||||
assertEquals(footballTeam.get(2)
|
||||
.getRanking(), 67);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparing_UsingComparatorComparing_thenSorted() {
|
||||
System.out.println("********* Comaparator.comparing method *********");
|
||||
System.out.println("********* byRanking *********");
|
||||
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
Collections.sort(footballTeam, byRanking);
|
||||
System.out.println("After Sorting : " + footballTeam);
|
||||
assertEquals(footballTeam.get(0)
|
||||
.getName(), "Steven");
|
||||
assertEquals(footballTeam.get(2)
|
||||
.getRanking(), 67);
|
||||
|
||||
System.out.println("********* byAge *********");
|
||||
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
|
||||
|
||||
System.out.println("Before Sorting : " + footballTeam);
|
||||
Collections.sort(footballTeam, byAge);
|
||||
System.out.println("After Sorting : " + footballTeam);
|
||||
assertEquals(footballTeam.get(0)
|
||||
.getName(), "Roger");
|
||||
assertEquals(footballTeam.get(2)
|
||||
.getRanking(), 45);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
package com.baeldung.file;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.CharSink;
|
||||
import com.google.common.io.FileWriteMode;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.util.StreamUtils;
|
||||
|
||||
public class FilesTest {
|
||||
|
||||
public static final String fileName = "src/main/resources/countries.properties";
|
||||
|
||||
@Before
|
||||
@After
|
||||
public void setup() throws Exception {
|
||||
PrintWriter writer = new PrintWriter(fileName);
|
||||
writer.print("UK\r\n" + "US\r\n" + "Germany\r\n");
|
||||
writer.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingGuava_thenCorrect() throws IOException {
|
||||
File file = new File(fileName);
|
||||
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
|
||||
chs.write("Spain\r\n");
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
|
||||
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFileUtils_thenCorrect() throws IOException {
|
||||
File file = new File(fileName);
|
||||
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception {
|
||||
FileOutputStream fos = new FileOutputStream(fileName, true);
|
||||
fos.write("Spain\r\n".getBytes());
|
||||
fos.close();
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException {
|
||||
FileWriter fw = new FileWriter(fileName, true);
|
||||
BufferedWriter bw = new BufferedWriter(fw);
|
||||
bw.write("Spain");
|
||||
bw.newLine();
|
||||
bw.close();
|
||||
|
||||
assertThat(
|
||||
StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.interfaces;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class InnerInterfaceTests {
|
||||
@Test
|
||||
public void whenCustomerListJoined_thenReturnsJoinedNames() {
|
||||
Customer.List customerList = new CommaSeparatedCustomers();
|
||||
customerList.Add(new Customer("customer1"));
|
||||
customerList.Add(new Customer("customer2"));
|
||||
assertEquals("customer1,customer2", customerList.getCustomerNames());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,157 @@
|
|||
package com.baeldung.jdbcrowset;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import javax.sql.rowset.CachedRowSet;
|
||||
import javax.sql.rowset.FilteredRowSet;
|
||||
import javax.sql.rowset.JdbcRowSet;
|
||||
import javax.sql.rowset.JoinRowSet;
|
||||
import javax.sql.rowset.RowSetFactory;
|
||||
import javax.sql.rowset.RowSetProvider;
|
||||
import javax.sql.rowset.WebRowSet;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.sun.rowset.CachedRowSetImpl;
|
||||
import com.sun.rowset.JdbcRowSetImpl;
|
||||
import com.sun.rowset.JoinRowSetImpl;
|
||||
import com.sun.rowset.WebRowSetImpl;
|
||||
|
||||
public class JdbcRowSetTest {
|
||||
Statement stmt = null;
|
||||
String username = "sa";
|
||||
String password = "";
|
||||
String url = "jdbc:h2:mem:testdb";
|
||||
String sql = "SELECT * FROM customers";
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||
|
||||
String drop = "DROP TABLE IF EXISTS customers, associates;";
|
||||
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
|
||||
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
|
||||
stmt = conn.createStatement();
|
||||
stmt.executeUpdate(drop);
|
||||
stmt.executeUpdate(schema);
|
||||
stmt.executeUpdate(schemapartb);
|
||||
DatabaseConfiguration.initDatabase(stmt);
|
||||
|
||||
}
|
||||
|
||||
// JdbcRowSet Example
|
||||
@Test
|
||||
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
|
||||
|
||||
String sql = "SELECT * FROM customers";
|
||||
JdbcRowSet jdbcRS;
|
||||
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||
jdbcRS = new JdbcRowSetImpl(conn);
|
||||
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
|
||||
jdbcRS.setCommand(sql);
|
||||
jdbcRS.execute();
|
||||
jdbcRS.addRowSetListener(new ExampleListener());
|
||||
|
||||
while (jdbcRS.next()) {
|
||||
// each call to next, generates a cursorMoved event
|
||||
System.out.println("id=" + jdbcRS.getString(1));
|
||||
System.out.println("name=" + jdbcRS.getString(2));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// CachedRowSet Example
|
||||
@Test
|
||||
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
|
||||
|
||||
CachedRowSet crs = new CachedRowSetImpl();
|
||||
crs.setUsername(username);
|
||||
crs.setPassword(password);
|
||||
crs.setUrl(url);
|
||||
crs.setCommand(sql);
|
||||
crs.execute();
|
||||
crs.addRowSetListener(new ExampleListener());
|
||||
while (crs.next()) {
|
||||
if (crs.getInt("id") == 1) {
|
||||
System.out.println("CRS found customer1 and will remove the record.");
|
||||
crs.deleteRow();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WebRowSet example
|
||||
@Test
|
||||
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
|
||||
|
||||
WebRowSet wrs = new WebRowSetImpl();
|
||||
wrs.setUsername(username);
|
||||
wrs.setPassword(password);
|
||||
wrs.setUrl(url);
|
||||
wrs.setCommand(sql);
|
||||
wrs.execute();
|
||||
FileOutputStream ostream = new FileOutputStream("customers.xml");
|
||||
wrs.writeXml(ostream);
|
||||
}
|
||||
|
||||
// JoinRowSet example
|
||||
@Test
|
||||
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
|
||||
|
||||
CachedRowSetImpl customers = new CachedRowSetImpl();
|
||||
customers.setUsername(username);
|
||||
customers.setPassword(password);
|
||||
customers.setUrl(url);
|
||||
customers.setCommand(sql);
|
||||
customers.execute();
|
||||
|
||||
CachedRowSetImpl associates = new CachedRowSetImpl();
|
||||
associates.setUsername(username);
|
||||
associates.setPassword(password);
|
||||
associates.setUrl(url);
|
||||
String associatesSQL = "SELECT * FROM associates";
|
||||
associates.setCommand(associatesSQL);
|
||||
associates.execute();
|
||||
|
||||
JoinRowSet jrs = new JoinRowSetImpl();
|
||||
final String ID = "id";
|
||||
final String NAME = "name";
|
||||
jrs.addRowSet(customers, ID);
|
||||
jrs.addRowSet(associates, ID);
|
||||
jrs.last();
|
||||
System.out.println("Total rows: " + jrs.getRow());
|
||||
jrs.beforeFirst();
|
||||
while (jrs.next()) {
|
||||
|
||||
String string1 = jrs.getString(ID);
|
||||
String string2 = jrs.getString(NAME);
|
||||
System.out.println("ID: " + string1 + ", NAME: " + string2);
|
||||
}
|
||||
}
|
||||
|
||||
// FilteredRowSet example
|
||||
@Test
|
||||
public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception {
|
||||
RowSetFactory rsf = RowSetProvider.newFactory();
|
||||
FilteredRowSet frs = rsf.createFilteredRowSet();
|
||||
frs.setCommand("select * from customers");
|
||||
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||
frs.execute(conn);
|
||||
frs.setFilter(new FilterExample("^[A-C].*"));
|
||||
|
||||
ResultSetMetaData rsmd = frs.getMetaData();
|
||||
int columncount = rsmd.getColumnCount();
|
||||
while (frs.next()) {
|
||||
for (int i = 1; i <= columncount; i++) {
|
||||
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
package com.baeldung.loops;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WhenUsingLoops {
|
||||
|
||||
private LoopsInJava loops = new LoopsInJava();
|
||||
private static List<String> list = new ArrayList<>();
|
||||
private static Set<String> set = new HashSet<>();
|
||||
private static Map<String, Integer> map = new HashMap<>();
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
list.add("One");
|
||||
list.add("Two");
|
||||
list.add("Three");
|
||||
|
||||
set.add("Four");
|
||||
set.add("Five");
|
||||
set.add("Six");
|
||||
|
||||
map.put("One", 1);
|
||||
map.put("Two", 2);
|
||||
map.put("Three", 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRunForLoop() {
|
||||
int[] expected = { 0, 1, 2, 3, 4 };
|
||||
int[] actual = loops.simple_for_loop();
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRunEnhancedForeachLoop() {
|
||||
int[] expected = { 0, 1, 2, 3, 4 };
|
||||
int[] actual = loops.enhanced_for_each_loop();
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRunWhileLoop() {
|
||||
int[] expected = { 0, 1, 2, 3, 4 };
|
||||
int[] actual = loops.while_loop();
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldRunDoWhileLoop() {
|
||||
int[] expected = { 0, 1, 2, 3, 4 };
|
||||
int[] actual = loops.do_while_loop();
|
||||
Assert.assertArrayEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSimpleFor_shouldIterateList() {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
System.out.println(list.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEnhancedFor_shouldIterateList() {
|
||||
for (String item : list) {
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEnhancedFor_shouldIterateSet() {
|
||||
for (String item : set) {
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingEnhancedFor_shouldIterateMap() {
|
||||
for (Entry<String, Integer> entry : map.entrySet()) {
|
||||
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
|
||||
aa: for (int i = 1; i <= 3; i++) {
|
||||
if (i == 1)
|
||||
continue;
|
||||
bb: for (int j = 1; j <= 3; j++) {
|
||||
if (i == 2 && j == 2) {
|
||||
break aa;
|
||||
}
|
||||
System.out.println(i + " " + j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.nestedclass;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
abstract class SimpleAbstractClass {
|
||||
abstract void run();
|
||||
}
|
||||
|
||||
public class AnonymousInner {
|
||||
|
||||
@Test
|
||||
public void run() {
|
||||
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
|
||||
void run() {
|
||||
System.out.println("Running Anonymous Class...");
|
||||
}
|
||||
};
|
||||
simpleAbstractClass.run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.nestedclass;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Enclosing {
|
||||
|
||||
private static int x = 1;
|
||||
|
||||
public static class StaticNested {
|
||||
|
||||
private void run() {
|
||||
System.out.println("x = " + x);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
Enclosing.StaticNested nested = new Enclosing.StaticNested();
|
||||
nested.run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.nestedclass;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NewEnclosing {
|
||||
|
||||
private void run() {
|
||||
class Local {
|
||||
void run() {
|
||||
System.out.println("Welcome to Baeldung!");
|
||||
}
|
||||
}
|
||||
Local local = new Local();
|
||||
local.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
NewEnclosing newEnclosing = new NewEnclosing();
|
||||
newEnclosing.run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.nestedclass;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NewOuter {
|
||||
|
||||
int a = 1;
|
||||
static int b = 2;
|
||||
|
||||
public class InnerClass {
|
||||
int a = 3;
|
||||
static final int b = 4;
|
||||
|
||||
public void run() {
|
||||
System.out.println("a = " + a);
|
||||
System.out.println("b = " + b);
|
||||
System.out.println("NewOuter.this.a = " + NewOuter.this.a);
|
||||
System.out.println("NewOuter.b = " + NewOuter.b);
|
||||
System.out.println("NewOuter.this.b = " + NewOuter.this.b);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
NewOuter outer = new NewOuter();
|
||||
NewOuter.InnerClass inner = outer.new InnerClass();
|
||||
inner.run();
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.nestedclass;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Outer {
|
||||
|
||||
public class Inner {
|
||||
|
||||
public void run() {
|
||||
System.out.println("Calling test...");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
Outer outer = new Outer();
|
||||
Outer.Inner inner = outer.new Inner();
|
||||
inner.run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.polymorphism;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PolymorphismUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenImageFile_whenFileCreated_shouldSucceed() {
|
||||
ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||
.getBytes(), "v1.0.0");
|
||||
assertEquals(200, imageFile.getHeight());
|
||||
}
|
||||
|
||||
// Downcasting then Upcasting
|
||||
@Test
|
||||
public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() {
|
||||
GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||
TextFile textFile2 = (TextFile) textFile;
|
||||
assertEquals(6, textFile2.getWordCount());
|
||||
}
|
||||
|
||||
// Downcasting
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() {
|
||||
GenericFile genericFile = new GenericFile();
|
||||
TextFile textFile = (TextFile) genericFile;
|
||||
System.out.println(textFile.getWordCount());
|
||||
}
|
||||
}
|
|
@ -223,4 +223,4 @@ public class StringTest {
|
|||
|
||||
assertEquals("200", String.valueOf(l));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
package com.baeldung.tree;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryTreeTest {
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(!bt.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(6));
|
||||
assertTrue(bt.containsNode(4));
|
||||
|
||||
assertFalse(bt.containsNode(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(9));
|
||||
bt.delete(9);
|
||||
assertFalse(bt.containsNode(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseInOrder(bt.root);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePreOrder(bt.root);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePostOrder(bt.root);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseLevelOrder();
|
||||
}
|
||||
|
||||
private BinaryTree createBinaryTree() {
|
||||
BinaryTree bt = new BinaryTree();
|
||||
|
||||
bt.add(6);
|
||||
bt.add(4);
|
||||
bt.add(8);
|
||||
bt.add(3);
|
||||
bt.add(5);
|
||||
bt.add(7);
|
||||
bt.add(9);
|
||||
|
||||
return bt;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.varargs;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
public class FormatterTest {
|
||||
|
||||
private final static String FORMAT = "%s %s %s";
|
||||
|
||||
@Test
|
||||
public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() {
|
||||
String actualResult = format();
|
||||
|
||||
assertThat(actualResult, is("empty "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneArgument_thenResultHasTwoTrailingSpace() {
|
||||
String actualResult = format("baeldung");
|
||||
|
||||
assertThat(actualResult, is("baeldung "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoArguments_thenOneTrailingSpaceExists() {
|
||||
String actualResult = format("baeldung", "rocks");
|
||||
|
||||
assertThat(actualResult, is("baeldung rocks "));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() {
|
||||
String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring");
|
||||
|
||||
assertThat(actualResult, is("baeldung rocks java"));
|
||||
}
|
||||
|
||||
public String format() {
|
||||
return format("empty", "");
|
||||
}
|
||||
|
||||
public String format(String value) {
|
||||
return format(value, "");
|
||||
}
|
||||
|
||||
public String format(String val1, String val2) {
|
||||
return String.format(FORMAT, val1, val2, "");
|
||||
}
|
||||
|
||||
public String formatWithVarArgs(String... values) {
|
||||
if (values.length == 0) {
|
||||
return "no arguments given";
|
||||
}
|
||||
|
||||
return String.format(FORMAT, values);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.kotlin
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class ExtensionMethods {
|
||||
@Test
|
||||
fun simpleExtensionMethod() {
|
||||
fun String.escapeForXml() : String {
|
||||
return this
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
}
|
||||
|
||||
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
|
||||
Assert.assertEquals("<Tag>", "<Tag>".escapeForXml())
|
||||
Assert.assertEquals("a&b", "a&b".escapeForXml())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun genericExtensionMethod() {
|
||||
fun <T> T.concatAsString(b: T) : String {
|
||||
return this.toString() + b.toString()
|
||||
}
|
||||
|
||||
Assert.assertEquals("12", "1".concatAsString("2"))
|
||||
Assert.assertEquals("12", 1.concatAsString(2))
|
||||
// This doesn't compile
|
||||
// Assert.assertEquals("12", 1.concatAsString(2.0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun infixExtensionMethod() {
|
||||
infix fun Number.toPowerOf(exponent: Number): Double {
|
||||
return Math.pow(this.toDouble(), exponent.toDouble())
|
||||
}
|
||||
|
||||
Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1)
|
||||
Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun operatorExtensionMethod() {
|
||||
operator fun List<Int>.times(by: Int): List<Int> {
|
||||
return this.map { it * by }
|
||||
}
|
||||
|
||||
Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Intro to Dubbo](http://www.baeldung.com/dubbo-intro)
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
<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>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>dubbo</artifactId>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<dubbo.version>2.5.7</dubbo.version>
|
||||
<zookeeper.version>3.4.11</zookeeper.version>
|
||||
<zkclient.version>0.10</zkclient.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>dubbo</artifactId>
|
||||
<version>${dubbo.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>${zookeeper.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.101tec</groupId>
|
||||
<artifactId>zkclient</artifactId>
|
||||
<version>${zkclient.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,210 @@
|
|||
/*
|
||||
* Copyright 1999-2011 Alibaba Group.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.alibaba.dubbo.registry.simple;
|
||||
|
||||
import com.alibaba.dubbo.common.Constants;
|
||||
import com.alibaba.dubbo.common.URL;
|
||||
import com.alibaba.dubbo.common.logger.Logger;
|
||||
import com.alibaba.dubbo.common.logger.LoggerFactory;
|
||||
import com.alibaba.dubbo.common.utils.ConcurrentHashSet;
|
||||
import com.alibaba.dubbo.common.utils.NetUtils;
|
||||
import com.alibaba.dubbo.common.utils.UrlUtils;
|
||||
import com.alibaba.dubbo.registry.NotifyListener;
|
||||
import com.alibaba.dubbo.registry.RegistryService;
|
||||
import com.alibaba.dubbo.registry.support.AbstractRegistry;
|
||||
import com.alibaba.dubbo.rpc.RpcContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* SimpleRegistryService
|
||||
*
|
||||
* @author william.liangf
|
||||
*/
|
||||
public class SimpleRegistryService extends AbstractRegistry {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(SimpleRegistryService.class);
|
||||
private final ConcurrentMap<String, Set<URL>> remoteRegistered = new ConcurrentHashMap<String, Set<URL>>();
|
||||
private final ConcurrentMap<String, ConcurrentMap<URL, Set<NotifyListener>>> remoteSubscribed = new ConcurrentHashMap<String, ConcurrentMap<URL, Set<NotifyListener>>>();
|
||||
|
||||
public SimpleRegistryService() {
|
||||
super(new URL("dubbo", NetUtils.getLocalHost(), 0, RegistryService.class.getName(), "file", "N/A"));
|
||||
}
|
||||
|
||||
public boolean isAvailable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public List<URL> lookup(URL url) {
|
||||
List<URL> urls = new ArrayList<URL>();
|
||||
for (URL u : getRegistered()) {
|
||||
if (UrlUtils.isMatch(url, u)) {
|
||||
urls.add(u);
|
||||
}
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
public void register(URL url) {
|
||||
String client = RpcContext.getContext().getRemoteAddressString();
|
||||
Set<URL> urls = remoteRegistered.get(client);
|
||||
if (urls == null) {
|
||||
remoteRegistered.putIfAbsent(client, new ConcurrentHashSet<URL>());
|
||||
urls = remoteRegistered.get(client);
|
||||
}
|
||||
urls.add(url);
|
||||
super.register(url);
|
||||
registered(url);
|
||||
}
|
||||
|
||||
public void unregister(URL url) {
|
||||
String client = RpcContext.getContext().getRemoteAddressString();
|
||||
Set<URL> urls = remoteRegistered.get(client);
|
||||
if (urls != null && urls.size() > 0) {
|
||||
urls.remove(url);
|
||||
}
|
||||
super.unregister(url);
|
||||
unregistered(url);
|
||||
}
|
||||
|
||||
public void subscribe(URL url, NotifyListener listener) {
|
||||
if (getUrl().getPort() == 0) {
|
||||
URL registryUrl = RpcContext.getContext().getUrl();
|
||||
if (registryUrl != null && registryUrl.getPort() > 0
|
||||
&& RegistryService.class.getName().equals(registryUrl.getPath())) {
|
||||
super.setUrl(registryUrl);
|
||||
super.register(registryUrl);
|
||||
}
|
||||
}
|
||||
String client = RpcContext.getContext().getRemoteAddressString();
|
||||
ConcurrentMap<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
|
||||
if (clientListeners == null) {
|
||||
remoteSubscribed.putIfAbsent(client, new ConcurrentHashMap<URL, Set<NotifyListener>>());
|
||||
clientListeners = remoteSubscribed.get(client);
|
||||
}
|
||||
Set<NotifyListener> listeners = clientListeners.get(url);
|
||||
if (listeners == null) {
|
||||
clientListeners.putIfAbsent(url, new ConcurrentHashSet<NotifyListener>());
|
||||
listeners = clientListeners.get(url);
|
||||
}
|
||||
listeners.add(listener);
|
||||
super.subscribe(url, listener);
|
||||
subscribed(url, listener);
|
||||
}
|
||||
|
||||
public void unsubscribe(URL url, NotifyListener listener) {
|
||||
if (!Constants.ANY_VALUE.equals(url.getServiceInterface())
|
||||
&& url.getParameter(Constants.REGISTER_KEY, true)) {
|
||||
unregister(url);
|
||||
}
|
||||
String client = RpcContext.getContext().getRemoteAddressString();
|
||||
Map<URL, Set<NotifyListener>> clientListeners = remoteSubscribed.get(client);
|
||||
if (clientListeners != null && clientListeners.size() > 0) {
|
||||
Set<NotifyListener> listeners = clientListeners.get(url);
|
||||
if (listeners != null && listeners.size() > 0) {
|
||||
listeners.remove(listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void registered(URL url) {
|
||||
for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) {
|
||||
URL key = entry.getKey();
|
||||
if (UrlUtils.isMatch(key, url)) {
|
||||
List<URL> list = lookup(key);
|
||||
for (NotifyListener listener : entry.getValue()) {
|
||||
listener.notify(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void unregistered(URL url) {
|
||||
for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) {
|
||||
URL key = entry.getKey();
|
||||
if (UrlUtils.isMatch(key, url)) {
|
||||
List<URL> list = lookup(key);
|
||||
for (NotifyListener listener : entry.getValue()) {
|
||||
listener.notify(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void subscribed(final URL url, final NotifyListener listener) {
|
||||
if (Constants.ANY_VALUE.equals(url.getServiceInterface())) {
|
||||
new Thread(new Runnable() {
|
||||
public void run() {
|
||||
Map<String, List<URL>> map = new HashMap<String, List<URL>>();
|
||||
for (URL u : getRegistered()) {
|
||||
if (UrlUtils.isMatch(url, u)) {
|
||||
String service = u.getServiceInterface();
|
||||
List<URL> list = map.get(service);
|
||||
if (list == null) {
|
||||
list = new ArrayList<URL>();
|
||||
map.put(service, list);
|
||||
}
|
||||
list.add(u);
|
||||
}
|
||||
}
|
||||
for (List<URL> list : map.values()) {
|
||||
try {
|
||||
listener.notify(list);
|
||||
} catch (Throwable e) {
|
||||
logger.warn("Discard to notify " + url.getServiceKey() + " to listener " + listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, "DubboMonitorNotifier").start();
|
||||
} else {
|
||||
List<URL> list = lookup(url);
|
||||
try {
|
||||
listener.notify(list);
|
||||
} catch (Throwable e) {
|
||||
logger.warn("Discard to notify " + url.getServiceKey() + " to listener " + listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
String client = RpcContext.getContext().getRemoteAddressString();
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Disconnected " + client);
|
||||
}
|
||||
Set<URL> urls = remoteRegistered.get(client);
|
||||
if (urls != null && urls.size() > 0) {
|
||||
for (URL url : urls) {
|
||||
unregister(url);
|
||||
}
|
||||
}
|
||||
Map<URL, Set<NotifyListener>> listeners = remoteSubscribed.get(client);
|
||||
if (listeners != null && listeners.size() > 0) {
|
||||
for (Map.Entry<URL, Set<NotifyListener>> entry : listeners.entrySet()) {
|
||||
URL url = entry.getKey();
|
||||
for (NotifyListener listener : entry.getValue()) {
|
||||
unsubscribe(url, listener);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.dubbo.remote;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class GreetingsFailoverServiceImpl implements GreetingsService {
|
||||
|
||||
@Override
|
||||
public String sayHi(String name) {
|
||||
System.out.println("failover implementation");
|
||||
return "hi, failover " + name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.dubbo.remote;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public interface GreetingsService {
|
||||
|
||||
String sayHi(String name);
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.dubbo.remote;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class GreetingsServiceImpl implements GreetingsService {
|
||||
|
||||
@Override
|
||||
public String sayHi(String name) {
|
||||
System.out.println("default implementation");
|
||||
return "hi, " + name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.dubbo.remote;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class GreetingsServiceSpecialImpl implements GreetingsService {
|
||||
|
||||
@Override
|
||||
public String sayHi(String name) {
|
||||
try {
|
||||
System.out.println("specially called");
|
||||
SECONDS.sleep(5);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return "hi, " + name;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package com.baeldung.dubbo;
|
||||
|
||||
import com.alibaba.dubbo.config.ApplicationConfig;
|
||||
import com.alibaba.dubbo.config.ReferenceConfig;
|
||||
import com.alibaba.dubbo.config.RegistryConfig;
|
||||
import com.alibaba.dubbo.config.ServiceConfig;
|
||||
import com.baeldung.dubbo.remote.GreetingsService;
|
||||
import com.baeldung.dubbo.remote.GreetingsServiceImpl;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class APIConfigurationLiveTest {
|
||||
|
||||
@Before
|
||||
public void initProvider() {
|
||||
ApplicationConfig application = new ApplicationConfig();
|
||||
application.setName("demo-provider");
|
||||
application.setVersion("1.0");
|
||||
|
||||
RegistryConfig registryConfig = new RegistryConfig();
|
||||
registryConfig.setAddress("multicast://224.1.1.1:9090");
|
||||
|
||||
ServiceConfig<GreetingsService> service = new ServiceConfig<>();
|
||||
service.setApplication(application);
|
||||
service.setRegistry(registryConfig);
|
||||
service.setInterface(GreetingsService.class);
|
||||
service.setRef(new GreetingsServiceImpl());
|
||||
|
||||
service.export();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProviderConsumer_whenSayHi_thenGotResponse() {
|
||||
ApplicationConfig application = new ApplicationConfig();
|
||||
application.setName("demo-consumer");
|
||||
application.setVersion("1.0");
|
||||
|
||||
RegistryConfig registryConfig = new RegistryConfig();
|
||||
registryConfig.setAddress("multicast://224.1.1.1:9090");
|
||||
|
||||
ReferenceConfig<GreetingsService> reference = new ReferenceConfig<>();
|
||||
reference.setApplication(application);
|
||||
reference.setRegistry(registryConfig);
|
||||
reference.setInterface(GreetingsService.class);
|
||||
|
||||
GreetingsService greetingsService = reference.get();
|
||||
String hiMessage = greetingsService.sayHi("baeldung");
|
||||
|
||||
assertEquals("hi, baeldung", hiMessage);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
package com.baeldung.dubbo;
|
||||
|
||||
import com.baeldung.dubbo.remote.GreetingsService;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class ClusterDynamicLoadBalanceLiveTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
@Before
|
||||
public void initRemote() {
|
||||
executorService = Executors.newFixedThreadPool(2);
|
||||
executorService.submit(() -> {
|
||||
ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-default.xml");
|
||||
remoteContext.start();
|
||||
});
|
||||
executorService.submit(() -> {
|
||||
SECONDS.sleep(2);
|
||||
ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml");
|
||||
backupRemoteContext.start();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProviderCluster_whenConsumerSaysHi_thenResponseBalanced() throws InterruptedException {
|
||||
ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-lb.xml");
|
||||
localContext.start();
|
||||
GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService");
|
||||
List<Long> elapseList = new ArrayList<>(6);
|
||||
for (int i = 0; i < 6; i++) {
|
||||
long current = System.currentTimeMillis();
|
||||
String hiMessage = greetingsService.sayHi("baeldung");
|
||||
assertNotNull(hiMessage);
|
||||
elapseList.add(System.currentTimeMillis() - current);
|
||||
SECONDS.sleep(1);
|
||||
}
|
||||
|
||||
OptionalDouble avgElapse = elapseList
|
||||
.stream()
|
||||
.mapToLong(e -> e)
|
||||
.average();
|
||||
assertTrue(avgElapse.isPresent());
|
||||
assertTrue(avgElapse.getAsDouble() > 1666.0);
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void destroy() {
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.dubbo;
|
||||
|
||||
import com.baeldung.dubbo.remote.GreetingsService;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class ClusterFailoverLiveTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
@Before
|
||||
public void initRemote() {
|
||||
executorService = Executors.newFixedThreadPool(2);
|
||||
executorService.submit(() -> {
|
||||
ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml");
|
||||
backupRemoteContext.start();
|
||||
});
|
||||
executorService.submit(() -> {
|
||||
ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-failover.xml");
|
||||
remoteContext.start();
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProviderCluster_whenConsumerSaysHi_thenGotFailoverResponse() {
|
||||
ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-failtest.xml");
|
||||
localContext.start();
|
||||
GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService");
|
||||
String hiMessage = greetingsService.sayHi("baeldung");
|
||||
|
||||
assertNotNull(hiMessage);
|
||||
assertEquals("hi, failover baeldung", hiMessage);
|
||||
}
|
||||
|
||||
@After
|
||||
public void destroy() {
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.dubbo;
|
||||
|
||||
import com.baeldung.dubbo.remote.GreetingsService;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class ClusterFailsafeLiveTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
@Before
|
||||
public void initRemote() {
|
||||
executorService = Executors.newFixedThreadPool(1);
|
||||
executorService.submit(() -> {
|
||||
ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special-failsafe.xml");
|
||||
remoteContext.start();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProviderCluster_whenConsumerSaysHi_thenGotFailsafeResponse() {
|
||||
ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-failtest.xml");
|
||||
localContext.start();
|
||||
GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService");
|
||||
String hiMessage = greetingsService.sayHi("baeldung");
|
||||
|
||||
assertNull(hiMessage);
|
||||
}
|
||||
|
||||
@After
|
||||
public void destroy() {
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.dubbo;
|
||||
|
||||
import com.baeldung.dubbo.remote.GreetingsService;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class ClusterLoadBalanceLiveTest {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
@Before
|
||||
public void initRemote() {
|
||||
executorService = Executors.newFixedThreadPool(2);
|
||||
executorService.submit(() -> {
|
||||
ClassPathXmlApplicationContext remoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-default.xml");
|
||||
remoteContext.start();
|
||||
});
|
||||
executorService.submit(() -> {
|
||||
ClassPathXmlApplicationContext backupRemoteContext = new ClassPathXmlApplicationContext("cluster/provider-app-special.xml");
|
||||
backupRemoteContext.start();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProviderCluster_whenConsumerSaysHi_thenResponseBalanced() {
|
||||
ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("cluster/consumer-app-lb.xml");
|
||||
localContext.start();
|
||||
GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService");
|
||||
List<Long> elapseList = new ArrayList<>(6);
|
||||
for (int i = 0; i < 6; i++) {
|
||||
long current = System.currentTimeMillis();
|
||||
String hiMessage = greetingsService.sayHi("baeldung");
|
||||
assertNotNull(hiMessage);
|
||||
elapseList.add(System.currentTimeMillis() - current);
|
||||
}
|
||||
|
||||
OptionalDouble avgElapse = elapseList
|
||||
.stream()
|
||||
.mapToLong(e -> e)
|
||||
.average();
|
||||
assertTrue(avgElapse.isPresent());
|
||||
System.out.println(avgElapse.getAsDouble());
|
||||
assertTrue(avgElapse.getAsDouble() > 2500.0);
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void destroy() {
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.dubbo;
|
||||
|
||||
import com.baeldung.dubbo.remote.GreetingsService;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class MulticastRegistryLiveTest {
|
||||
|
||||
private ClassPathXmlApplicationContext remoteContext;
|
||||
|
||||
@Before
|
||||
public void initRemote() {
|
||||
remoteContext = new ClassPathXmlApplicationContext("multicast/provider-app.xml");
|
||||
remoteContext.start();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProvider_whenConsumerSaysHi_thenGotResponse() {
|
||||
ClassPathXmlApplicationContext localContext = new ClassPathXmlApplicationContext("multicast/consumer-app.xml");
|
||||
localContext.start();
|
||||
GreetingsService greetingsService = (GreetingsService) localContext.getBean("greetingsService");
|
||||
String hiMessage = greetingsService.sayHi("baeldung");
|
||||
|
||||
assertNotNull(hiMessage);
|
||||
assertEquals("hi, baeldung", hiMessage);
|
||||
}
|
||||
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue