Merge branch 'master' of https://github.com/abh1navv/tutorials into BAEL-3201

This commit is contained in:
Abhinav Pandey 2022-07-17 08:52:52 +00:00 committed by GitHub
commit 170c8990a9
597 changed files with 5698 additions and 1563 deletions

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-modules</artifactId>
<name>akka-modules</name>

View File

@ -8,6 +8,8 @@ import java.util.List;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
class CustomerToDataFrameConverterAppUnitTest {
@ -59,4 +61,9 @@ class CustomerToDataFrameConverterAppUnitTest {
assertEquals( "Male", row2.getAs("gender"));
assertEquals( 1200, (int)row2.getAs("transaction_amount"));
}
@AfterEach
public void cleanup() {
SparkSession.getActiveSession().get().close();
}
}

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
<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>

View File

@ -21,5 +21,3 @@
</modules>
</project>

View File

@ -11,3 +11,4 @@ This module contains articles about Java 14.
- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access)
- [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword)
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)
- [Java 14 Record vs. Lombok](https://www.baeldung.com/java-record-vs-lombok)

View File

@ -14,6 +14,15 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>

View File

@ -0,0 +1,18 @@
package com.baeldung.java14.recordvslombok;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class ColorData {
private int red;
private int green;
private int blue;
public String getHexString() {
return String.format("#%02X%02X%02X", red, green, blue);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.java14.recordvslombok;
public record ColorRecord(int red, int green, int blue) {
public String getHexString() {
return String.format("#%02X%02X%02X", red, green, blue);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.java14.recordvslombok;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Value;
@Value
@Getter(AccessLevel.NONE)
public class ColorValueObject {
int red;
int green;
int blue;
public String getHexString() {
return String.format("#%02X%02X%02X", red, green, blue);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.java14.recordvslombok;
import lombok.Value;
@Value
public class MonochromeColor extends ColorData {
public MonochromeColor(int grayScale) {
super(grayScale, grayScale, grayScale);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.java14.recordvslombok;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class StudentBuilder {
private String firstName;
private String lastName;
private Long studentId;
private String email;
private String phoneNumber;
private String address;
private String country;
private int age;
}

View File

@ -0,0 +1,4 @@
package com.baeldung.java14.recordvslombok;
public record StudentRecord(String firstName, String lastName, Long studentId, String email, String phoneNumber, String address, String country, int age) {
}

View File

@ -0,0 +1,43 @@
package com.baeldung.java14.recordvslombok;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class RecordVsLombokUntTest {
@Test
public void givenAColorRecord_hexStringIsCorrect() {
var red = new ColorRecord(255, 0, 0);
assertThat(red.getHexString()).isEqualTo("#FF0000");
}
@Test
public void givenAColorValueObject_hexStringIsCorrect() {
var red = new ColorValueObject(255, 0, 0);
assertThat(red.getHexString()).isEqualTo("#FF0000");
}
@Test
public void givenRecordWithManyAttributes_firstNameShouldBeJohn() {
StudentRecord john = new StudentRecord("John", "Doe", null, "john@doe.com", null, null, "England", 20);
assertThat(john.firstName()).isEqualTo("John");
}
@Test
public void givenBuilderWithManyAttributes_firstNameShouldBeJohn() {
StudentBuilder john = StudentBuilder.builder()
.firstName("John")
.lastName("Doe")
.email("john@doe.com")
.country("England")
.age(20)
.build();
assertThat(john.getFirstName()).isEqualTo("John");
}
}

View File

@ -5,4 +5,3 @@ This module contains articles about Java 15.
### Relevant articles
- [Hidden Classes in Java 15](https://www.baeldung.com/java-hidden-classes)
- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces)

View File

@ -10,7 +10,7 @@ public class BlogPost {
private BlogPostType type;
private int likes;
record AuthPostTypesLikes(String author, BlogPostType type, int likes) {};
record PostcountTitlesLikesStats(long postCount, String titles, IntSummaryStatistics likesStats){};
record PostCountTitlesLikesStats(long postCount, String titles, IntSummaryStatistics likesStats){};
record TitlesBoundedSumOfLikes(String titles, int boundedSumOfLikes) {};
public BlogPost(String title, String author, BlogPostType type, int likes) {

View File

@ -257,7 +257,7 @@ public class JavaGroupingByCollectorUnitTest {
@Test
public void givenListOfPosts_whenGroupedByAuthor_thenGetAMapUsingCollectingAndThen() {
Map<String, BlogPost.PostcountTitlesLikesStats> postsPerAuthor = posts.stream()
Map<String, BlogPost.PostCountTitlesLikesStats> postsPerAuthor = posts.stream()
.collect(groupingBy(BlogPost::getAuthor, collectingAndThen(toList(), list -> {
long count = list.stream()
.map(BlogPost::getTitle)
@ -267,10 +267,10 @@ public class JavaGroupingByCollectorUnitTest {
.collect(joining(" : "));
IntSummaryStatistics summary = list.stream()
.collect(summarizingInt(BlogPost::getLikes));
return new BlogPost.PostcountTitlesLikesStats(count, titles, summary);
return new BlogPost.PostCountTitlesLikesStats(count, titles, summary);
})));
BlogPost.PostcountTitlesLikesStats result = postsPerAuthor.get("Author 1");
BlogPost.PostCountTitlesLikesStats result = postsPerAuthor.get("Author 1");
assertThat(result.postCount()).isEqualTo(3L);
assertThat(result.titles()).isEqualTo("News item 1 : Programming guide : Tech review 2");
assertThat(result.likesStats().getMax()).isEqualTo(20);

View File

@ -5,3 +5,4 @@
- [Introduction to HexFormat in Java 17](https://www.baeldung.com/java-hexformat)
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)
- [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators)
- [Sealed Classes and Interfaces in Java 17](https://www.baeldung.com/java-sealed-classes-interfaces)

View File

@ -21,7 +21,7 @@ public class VehicleUnitTest {
public void givenCar_whenUsingReflectionAPI_thenSuperClassIsSealed() {
Assertions.assertThat(car.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(car.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(car.getClass().getSuperclass().permittedSubclasses())
Assertions.assertThat(car.getClass().getSuperclass().getPermittedSubclasses())
.contains(ClassDesc.of(car.getClass().getCanonicalName()));
}
@ -29,7 +29,7 @@ public class VehicleUnitTest {
public void givenTruck_whenUsingReflectionAPI_thenSuperClassIsSealed() {
Assertions.assertThat(truck.getClass().isSealed()).isEqualTo(false);
Assertions.assertThat(truck.getClass().getSuperclass().isSealed()).isEqualTo(true);
Assertions.assertThat(truck.getClass().getSuperclass().permittedSubclasses())
Assertions.assertThat(truck.getClass().getSuperclass().getPermittedSubclasses())
.contains(ClassDesc.of(truck.getClass().getCanonicalName()));
}

View File

@ -20,7 +20,7 @@ public class InputStreamToOutputStreamUnitTest {
void copy(InputStream source, OutputStream target) throws IOException {
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
while ((length = source.read(buf)) != -1) {
target.write(buf, 0, length);
}
}

View File

@ -25,4 +25,5 @@
<properties>
<commons-lang.version>2.2</commons-lang.version>
</properties>
</project>

View File

@ -45,18 +45,19 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-commons.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache-commons.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<trove4j.version>3.0.2</trove4j.version>
<fastutil.version>8.1.0</fastutil.version>

View File

@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class AccountUnitTest {
public class AccountManualTest {
private Account account;

View File

@ -4,3 +4,4 @@
### Relevant Articles:
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
- [Use Cases for Static Methods in Java](https://www.baeldung.com/java-static-methods-use-cases)

View File

@ -14,6 +14,26 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</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-inline</artifactId>
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-function</finalName>
<resources>
@ -24,4 +44,10 @@
</resources>
</build>
<properties>
<mockito-inline.version>3.8.0</mockito-inline.version>
<assertj.version>3.22.0</assertj.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.staticmethods;
public final class CustomStringUtils {
private CustomStringUtils() {}
public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; }
}

View File

@ -0,0 +1,15 @@
package com.baeldung.staticmethods;
public class StaticCounter {
private static int counter = 0;
public static int incrementCounter() {
return ++counter;
}
public static int getCounterValue() {
return counter;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.staticmethods;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class CollectionUtilsUnitTest {
@Test
void givenListOfNumbers_whenReverseStaticMethodIsCalled_thenNumbersInReversedOrderAreReturned() {
List<String> list = Arrays.asList("1", "2", "3");
Collections.reverse(list);
assertThat(list).containsExactly("3", "2", "1");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.staticmethods;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class CustomStringUtilsUnitTest {
@Test
void givenNonEmptyString_whenIsEmptyMethodIsCalled_thenFalseIsReturned() {
boolean empty = CustomStringUtils.isEmpty("baeldung");
assertThat(empty).isFalse();
}
@Test
void givenEmptyString_whenIsEmptyMethodIsCalled_thenTrueIsReturned() {
boolean empty = CustomStringUtils.isEmpty("");
assertThat(empty).isTrue();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.staticmethods;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StaticCounterUnitTest {
@Test
void givenStaticCounter_whenIncrementCounterIsCalled_thenValueIsIncresedByOne() {
int oldValue = StaticCounter.getCounterValue();
int newValue = StaticCounter.incrementCounter();
assertThat(newValue).isEqualTo(oldValue + 1);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.staticmethods;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StringUtilsUnitTest {
@Test
void givenSimpleString_whenCapitalizeStaticMethodIsCalled_thenCapitalizedStringIsReturned() {
String str = StringUtils.capitalize("baeldung");
assertThat(str).isEqualTo("Baeldung");
}
}

View File

@ -9,4 +9,5 @@ This module contains articles about core Java input/output(IO) conversions.
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [How to Convert InputStream to Base64 String](https://www.baeldung.com/java-inputstream-to-base64-string)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)

View File

@ -10,3 +10,5 @@ This module contains articles about JAR files
- [Get Names of Classes Inside a JAR File](https://www.baeldung.com/jar-file-get-class-names)
- [Find All Jars Containing Given Class](https://baeldung.com/find-all-jars-containing-given-class/)
- [Creating JAR Files Programmatically](https://www.baeldung.com/jar-create-programatically)
- [Guide to Creating Jar Executables and Windows Executables from Java](https://www.baeldung.com/jar-windows-executables)
- [Get the Full Path of a JAR File From a Class](https://www.baeldung.com/java-full-path-of-jar-from-class)

View File

@ -54,6 +54,12 @@
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -266,6 +272,7 @@
<!-- util -->
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<mockito.version>4.6.1</mockito.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>

View File

@ -0,0 +1,31 @@
package com.baeldung.jar;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MySampleGUIAppn extends JFrame {
public MySampleGUIAppn() {
if (!GraphicsEnvironment.isHeadless()) {
setSize(300,300);
setTitle("MySampleGUIAppn");
Button b = new Button("Click Me!");
b.setBounds(30,100,80,30);
add(b);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
else {
System.exit(0);
}
}
public static void main(String[] args) {
MySampleGUIAppn app=new MySampleGUIAppn();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jarfile;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class JarFilePathResolver {
public String getJarFilePath(Class clazz) {
try {
return byGetProtectionDomain(clazz);
} catch (Exception e) {
// cannot get jar file path using byGetProtectionDomain
// Exception handling omitted
}
return byGetResource(clazz);
}
String byGetProtectionDomain(Class clazz) throws URISyntaxException {
URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
return Paths.get(url.toURI()).toString();
}
String byGetResource(Class clazz) {
final URL classResource = clazz.getResource(clazz.getSimpleName() + ".class");
if (classResource == null) {
throw new RuntimeException("class resource is null");
}
final String url = classResource.toString();
if (url.startsWith("jar:file:")) {
// extract 'file:......jarName.jar' part from the url string
String path = url.replaceAll("^jar:(file:.*[.]jar)!/.*", "$1");
try {
return Paths.get(new URL(path).toURI()).toString();
} catch (Exception e) {
throw new RuntimeException("Invalid Jar File URL String");
}
}
throw new RuntimeException("Invalid Jar File URL String");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.jar;
import java.io.IOException;
import org.junit.jupiter.api.Test;
class MySampleGUIAppnUnitTest {
@Test
void testMain() throws IOException {
System.setProperty("java.awt.headless", "true");
String [] args = null;
System.exit(0);
MySampleGUIAppn.main(args);
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.jarfile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.base.Ascii;
import java.io.File;
import java.net.URISyntaxException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class JarFilePathResolverUnitTest {
@Spy
JarFilePathResolver jarFilePathResolver;
@Test
void givenClassObjectWhenCallingByGetProtectionDomainShouldGetExpectedPath() throws Exception {
String jarPath = jarFilePathResolver.byGetProtectionDomain(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();
}
@Test
void givenClassObjectWhenCallingByGetResourceShouldGetExpectedPath() {
String jarPath = jarFilePathResolver.byGetResource(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();
}
@Test
void givenClassObjectWhenNoSecurityExceptionRaisedShouldGetExpectedPath() throws URISyntaxException {
String jarPath = jarFilePathResolver.getJarFilePath(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();
verify(jarFilePathResolver, times(1)).byGetProtectionDomain(Ascii.class);
verify(jarFilePathResolver, never()).byGetResource(Ascii.class);
}
@Test
void givenClassObjectWhenSecurityExceptionRaisedShouldGetExpectedPath() throws URISyntaxException {
when(jarFilePathResolver.byGetProtectionDomain(Ascii.class)).thenThrow(new SecurityException("not allowed"));
String jarPath = jarFilePathResolver.getJarFilePath(Ascii.class);
assertThat(jarPath).endsWith(".jar").contains("guava");
assertThat(new File(jarPath)).exists();
verify(jarFilePathResolver, times(1)).byGetProtectionDomain(Ascii.class);
verify(jarFilePathResolver, times(1)).byGetResource(Ascii.class);
}
}

View File

@ -5,3 +5,4 @@ This module contains articles about core features in the Java language
### Relevant Articles:
- [Difference Between == and equals() in Java](https://www.baeldung.com/java-equals-method-operator-difference)
- [Advantages and Disadvantages of Using Java Wildcard Imports](https://www.baeldung.com/java-wildcard-imports)

View File

@ -13,7 +13,6 @@
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<finalName>core-java-lang-5</finalName>
<resources>
@ -23,5 +22,4 @@
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.imports.specific;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class Book {
private UUID id;
private String name;
private Date datePublished;
private List<String> authors;
}

View File

@ -0,0 +1,15 @@
package com.baeldung.imports.wildcard;
import java.util.*;
public class Book {
private UUID id;
private String name;
private Date datePublished;
private List<String> authors;
}

View File

@ -0,0 +1,17 @@
package com.baeldung.imports.wildcard;
import java.awt.*;
import java.util.*;
import java.util.List;
public class BookView extends Frame {
private UUID id;
private String name;
private Date datePublished;
private List<String> authors;
}

View File

@ -0,0 +1,19 @@
package com.baeldung.imports.wildcard;
import java.util.*;
import java.sql.*;
import java.sql.Date;
public class Library {
private UUID id;
private String name;
private Time openingTime;
private Time closingTime;
private List<Date> datesClosed;
}

View File

@ -6,3 +6,4 @@ This module contains articles about types in Java
- [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array)
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)

View File

@ -7,7 +7,6 @@
- [Automorphic Numbers in Java](https://www.baeldung.com/java-automorphic-numbers)
- [Convert Byte Size Into a Human-Readable Format in Java](https://www.baeldung.com/java-human-readable-byte-size)
- [Convert boolean to int in Java](https://www.baeldung.com/java-boolean-to-int)
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
- [Reverse a Number in Java](https://www.baeldung.com/java-reverse-number)
- [Check if BigDecimal Value Is Zero](https://www.baeldung.com/java-bigdecimal-zero)
- More articles: [[<-- prev]](../core-java-numbers-3) [[next -->]](../core-java-numbers-5)

View File

@ -9,7 +9,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;

View File

@ -0,0 +1,60 @@
package com.baeldung.streams.parallel;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
@State(Scope.Benchmark)
public class FileSearchCost {
private final static String FILE_NAME = "src/main/resources/Test";
@Setup(Level.Trial)
public void setup() throws IOException {
for (int i = 0; i < 1500; i++) {
File targetFile = new File(FILE_NAME + i);
FileUtils.writeStringToFile(targetFile, "Test", "UTF8");
}
}
@TearDown(Level.Trial)
public void tearDown() {
for (int i = 0; i < 1500; i++) {
File fileToDelete = new File(FILE_NAME + i);
fileToDelete.delete();
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void textFileSearchSequential() throws IOException {
Files.walk(Paths.get("src/main/resources/")).map(Path::normalize).filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt")).collect(Collectors.toList());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void textFileSearchParallel() throws IOException {
Files.walk(Paths.get("src/main/resources/")).parallel().map(Path::normalize).filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt")).collect(Collectors.toList());
}
}

View File

@ -1,3 +1,4 @@
## Relevant Articles:
- [Count Occurrences Using Java groupingBy Collector](https://www.baeldung.com/java-groupingby-count)
- [How to Split a Stream into Multiple Streams](https://www.baeldung.com/java-split-stream)

View File

@ -43,7 +43,6 @@
<version>3.23.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -11,3 +11,4 @@ This module contains articles about string APIs.
- [StringBuilder vs StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Getting a Character by Index From a String in Java](https://www.baeldung.com/java-character-at-position)
- [Clearing a StringBuilder or StringBuffer](https://www.baeldung.com/java-clear-stringbuilder-stringbuffer)

View File

@ -0,0 +1,32 @@
package com.baeldung.clearstringbuilderorstringbuffer;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@State(Scope.Benchmark)
public static class MyState {
final String HELLO = "Hello World";
final StringBuilder sb = new StringBuilder().append(HELLO);
}
@Benchmark
public void evaluateSetLength(Blackhole blackhole, MyState state) {
state.sb.setLength(0);
blackhole.consume(state.sb.toString());
}
@Benchmark
public void evaluateDelete(Blackhole blackhole, MyState state) {
state.sb.delete(0, state.sb.length());
blackhole.consume(state.sb.toString());
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.clearstringbuilderorstringbuffer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClearStringBuilderOrStringBufferUnitTest {
@Test
void whenSetLengthToZero_ThenStringBuilderIsCleared() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello World");
int initialCapacity = stringBuilder.capacity();
stringBuilder.setLength(0);
assertEquals("", stringBuilder.toString());
assertEquals(initialCapacity, stringBuilder.capacity());
}
@Test
void whenDeleteAll_ThenStringBuilderIsCleared() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello World");
int initialCapacity = stringBuilder.capacity();
stringBuilder.delete(0, stringBuilder.length());
assertEquals("", stringBuilder.toString());
assertEquals(initialCapacity, stringBuilder.capacity());
}
@Test
void whenSetLengthToZero_ThenStringBufferIsCleared() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Hello World");
int initialCapacity = stringBuffer.capacity();
stringBuffer.setLength(0);
assertEquals("", stringBuffer.toString());
assertEquals(initialCapacity, stringBuffer.capacity());
}
@Test
void whenDeleteAll_ThenStringBufferIsCleared() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Hello World");
int initialCapacity = stringBuffer.capacity();
stringBuffer.delete(0, stringBuffer.length());
assertEquals("", stringBuffer.toString());
assertEquals(initialCapacity, stringBuffer.capacity());
}
// Note: It did not make the cut to the article, but here is another way to reset a StringBuilder
@Test
void whenAssignedToNewStringBuilder_ThenStringBuilderIsCleared() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello World");
stringBuilder = new StringBuilder();
assertEquals("", stringBuilder.toString());
}
@Test
void whenAssignedToNewStringBuffer_ThenStringBufferIsCleared() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Hello World");
stringBuffer = new StringBuffer();
assertEquals("", stringBuffer.toString());
}
}

View File

@ -7,4 +7,4 @@
- [String equals() Vs contentEquals() in Java](https://www.baeldung.com/java-string-equals-vs-contentequals)
- [Check if a String Ends with a Certain Pattern in Java](https://www.baeldung.com/java-string-ends-pattern)
- [Check if a Character is a Vowel in Java](https://www.baeldung.com/java-check-character-vowel)
- [How to Truncate a String in Java](https://www.baeldung.com/java-truncating-strings)

View File

@ -0,0 +1,105 @@
package com.baeldung.truncate;
import java.util.Optional;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Splitter;
public class TruncateString {
private static final String EMPTY = "";
public static String usingSubstringMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
if (text.length() <= length) {
return text;
} else {
return text.substring(0, length);
}
}
public static String usingSplitMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
String[] results = text.split("(?<=\\G.{" + length + "})");
return results[0];
}
public static String usingPattern(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Optional<String> result = Pattern.compile(".{1," + length + "}")
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : EMPTY;
}
public static String usingCodePointsMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
return text.codePoints()
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
public static String usingLeftMethod(String text, int length) {
return StringUtils.left(text, length);
}
public static String usingTruncateMethod(String text, int length) {
return StringUtils.truncate(text, length);
}
public static String usingSplitter(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Iterable<String> parts = Splitter.fixedLength(length)
.split(text);
return parts.iterator()
.next();
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.truncate;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class TruncateStringUnitTest {
private static final String TEXT = "Welcome to baeldung.com";
@Test
public void givenStringAndLength_whenUsingSubstringMethod_thenTruncate() {
assertEquals(TruncateString.usingSubstringMethod(TEXT, 10), "Welcome to");
}
@Test
public void givenStringAndLength_whenUsingSplitMethod_thenTruncate() {
assertEquals(TruncateString.usingSplitMethod(TEXT, 13), "Welcome to ba");
}
@Test
public void givenStringAndLength_whenUsingPattern_thenTruncate() {
assertEquals(TruncateString.usingPattern(TEXT, 19), "Welcome to baeldung");
}
@Test
public void givenStringAndLength_whenUsingCodePointsMethod_thenTruncate() {
assertEquals(TruncateString.usingCodePointsMethod(TEXT, 6), "Welcom");
}
@Test
public void givenStringAndLength_whenUsingLeftMethod_thenTruncate() {
assertEquals(TruncateString.usingLeftMethod(TEXT, 15), "Welcome to bael");
}
@Test
public void givenStringAndLength_whenUsingTruncateMethod_thenTruncate() {
assertEquals(TruncateString.usingTruncateMethod(TEXT, 20), "Welcome to baeldung.");
}
@Test
public void givenStringAndLength_whenUsingSplitter_thenTruncate() {
assertEquals(TruncateString.usingSplitter(TEXT, 3), "Wel");
}
}

View File

@ -96,7 +96,23 @@ public class Java8EncodeDecodeUnitTest {
assertNotNull(decodedMime);
}
//
@Test
public void whenEncodedStringHasValidCharacters_thenStringCanBeDecoded() {
final String encodedString = "dGVzdCMkaW5wdXQ+";
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
final String decodedString = new String(decodedBytes);
assertNotNull(decodedString);
}
@Test(expected = IllegalArgumentException.class)
public void whenEncodedStringHasInvalidCharacters_thenIllegalArgumentException() {
final String encodedString = "dGVzdCMkaW5wdXQ#";
final byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
final String decodedString = new String(decodedBytes);
assertNotNull(decodedString);
}
private static StringBuilder getMimeBuffer() {
final StringBuilder buffer = new StringBuilder();

View File

@ -0,0 +1,4 @@
FROM openjdk:11
MAINTAINER baeldung.com
COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

View File

@ -0,0 +1,14 @@
services:
db:
image: postgres:latest
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
web-app:
image: web-app:latest
ports:
- 8080:8080
depends_on:
- db

View File

@ -0,0 +1,14 @@
services:
db:
image: postgres:latest
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
web-app:
image: web-app:latest
ports:
- 8080:8080
links:
- db

View File

@ -0,0 +1,36 @@
services:
db:
image: postgres:latest
restart: always
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
volumes:
- db:/var/lib/postgresql/data
networks:
- mynet
web-app:
image: web-app:latest
depends_on:
- db
networks:
- mynet
ports:
- 8080:8080
environment:
DB_HOST: db
DB_PORT: 5432
DB_USER: postgres
DB_PASSWORD: postgres
DB_NAME: postgres
networks:
mynet:
driver: bridge
volumes:
db:
driver: local

View File

@ -6,7 +6,7 @@
<artifactId>docker-compose</artifactId>
<description>Demo project for Spring Boot and Docker</description>
<parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -22,7 +22,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -35,6 +34,16 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.docker.app.DockAppApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

View File

@ -0,0 +1,10 @@
FROM alpine:latest
ARG name
ENV env_name $name
COPY greetings.sh .
RUN chmod +x /greetings.sh
CMD ["/greetings.sh"]

View File

@ -0,0 +1,3 @@
## Relevant Articles:
- [How to Pass Environment Variable Value into Dockerfile](https://www.baeldung.com/ops/dockerfile-env-variable)

View File

@ -0,0 +1,3 @@
#!/bin/sh
echo Hello $env_name

View File

@ -22,7 +22,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@ -0,0 +1,4 @@
FROM openjdk:11
MAINTAINER baeldung.com
COPY target/docker-java-jar-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>docker-java-jar</artifactId>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<mainClass>com.baeldung.HelloWorld</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung;
public class HelloWorld {
public static void main(String[] args){
System.out.println("Welcome to our application");
}
}

View File

@ -7,7 +7,7 @@
<name>docker-spring-boot</name>
<description>Demo project showing Spring Boot and Docker</description>
<parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>

View File

@ -23,6 +23,7 @@
<module>docker-images</module>
<module>docker-spring-boot</module>
<module>docker-spring-boot-postgres</module>
<module>docker-java-jar</module>
</modules>
<properties>

View File

@ -14,12 +14,6 @@
<relativePath>../parent-boot-2</relativePath>
</parent>
<properties>
<java.version>1.8</java.version>
<feign.version>11.8</feign.version>
<wsdl4j.version>1.6.3</wsdl4j.version>
</properties>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
@ -121,4 +115,10 @@
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<feign.version>11.8</feign.version>
<wsdl4j.version>1.6.3</wsdl4j.version>
</properties>
</project>

3
gradle-modules/README.md Normal file
View File

@ -0,0 +1,3 @@
## Gradle Modules
This module contains submodules of Gradle.

View File

@ -1,4 +1,4 @@
rootProject.name='gradle-5-articles'
rootProject.name='gradle-5'
include 'java-exec'
include 'unused-dependencies'
include 'source-sets'

Some files were not shown because too many files have changed in this diff Show More