Merge remote-tracking branch 'upstream/master' into BAEL-1754

This commit is contained in:
mherbaghinyan 2018-05-12 11:11:39 +04:00
commit 333168fce1
486 changed files with 7678 additions and 2040 deletions

View File

@ -34,3 +34,9 @@ CI - Jenkins
================================
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
### Relevant Articles:
================================
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)

View File

@ -20,4 +20,5 @@
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum)

View File

@ -2,3 +2,4 @@
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)

View File

@ -18,10 +18,29 @@
<artifactId>auto-value</artifactId>
<version>${auto-value.version}</version>
</dependency>
<dependency>
<groupId>com.google.auto.factory</groupId>
<artifactId>auto-factory</artifactId>
<version>${auto-factory.version}</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>${guice.version}</version>
</dependency>
</dependencies>
<properties>
<auto-value.version>1.3</auto-value.version>
<auto-factory.version>1.0-beta5</auto-factory.version>
<guice.version>4.2.0</guice.version>
</properties>
</project>

View File

@ -0,0 +1,21 @@
package com.baeldung.autofactory;
import com.baeldung.autofactory.model.Camera;
import com.baeldung.autofactory.model.Phone;
import com.baeldung.autofactory.model.PhoneFactory;
import com.baeldung.autofactory.modules.SonyCameraModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class App {
public static void main(String[] args) {
PhoneFactory phoneFactory = new PhoneFactory(() -> new Camera("Unknown", "XXX"));
Phone simplePhone = phoneFactory.create("other parts");
Injector injector = Guice.createInjector(new SonyCameraModule());
PhoneFactory injectedFactory = injector.getInstance(PhoneFactory.class);
Phone xperia = injectedFactory.create("Xperia");
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.autofactory;
import com.baeldung.autofactory.custom.SmartPhone;
/**
* @author aiet
*/
public interface CustomStorage {
SmartPhone customROMInGB(int romSize);
}

View File

@ -0,0 +1,10 @@
package com.baeldung.autofactory.custom;
/**
* @author aiet
*/
public abstract class AbstractFactory {
abstract CustomPhone newInstance(String brand);
}

View File

@ -0,0 +1,16 @@
package com.baeldung.autofactory.custom;
import com.google.auto.factory.AutoFactory;
/**
* @author aiet
*/
@AutoFactory(extending = AbstractFactory.class)
public class CustomPhone {
private final String brand;
public CustomPhone(String brand) {
this.brand = brand;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.autofactory.custom;
import com.baeldung.autofactory.CustomStorage;
import com.google.auto.factory.AutoFactory;
/**
* @author aiet
*/
@AutoFactory(className = "SamsungFactory", allowSubclasses = true, implementing = CustomStorage.class)
public class SmartPhone {
private int romSize;
public SmartPhone(int romSize) {
this.romSize = romSize;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.autofactory.model;
/**
* @author aiet
*/
public class Camera {
private final String manufacturer;
private final String serial;
public Camera(String manufacturer, String serial) {
this.manufacturer = manufacturer;
this.serial = serial;
}
public String getManufacturer() {
return manufacturer;
}
public String getSerial() {
return serial;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.autofactory.model;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
/**
* @author aiet
*/
public class ClassicPhone {
private final String dialpad;
private final String ringer;
private String otherParts;
@AutoFactory
public ClassicPhone(@Provided String dialpad, @Provided String ringer) {
this.dialpad = dialpad;
this.ringer = ringer;
}
@AutoFactory
public ClassicPhone(String otherParts) {
this("defaultDialPad", "defaultRinger");
this.otherParts = otherParts;
}
public String getDialpad() {
return dialpad;
}
public String getRinger() {
return ringer;
}
public String getOtherParts() {
return otherParts;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.autofactory.model;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
import javax.inject.Named;
/**
* @author aiet
*/
@AutoFactory
public class Phone {
private Camera camera;
private String otherParts;
public Phone(@Provided @Named("Sony") Camera camera, String otherParts) {
this.camera = camera;
this.otherParts = otherParts;
}
/* required when used as a base class for AutoFactory */
public Phone() {
}
public Camera getCamera() {
return camera;
}
public String getOtherParts() {
return otherParts;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.autofactory.modules;
import com.baeldung.autofactory.model.Camera;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import javax.inject.Named;
/**
* @author aiet
*/
public class SonyCameraModule extends AbstractModule {
private static int SONY_CAMERA_SERIAL = 1;
@Named("Sony")
@Provides
Camera cameraProvider() {
return new Camera("Sony", String.format("%03d", SONY_CAMERA_SERIAL++));
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.autofactory.provided;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
import javafx.scene.Camera;
import javax.inject.Provider;
/**
* @author aiet
*/
@AutoFactory
public class IntermediateAssembler {
private final Provider<Camera> camera;
private final String otherParts;
public IntermediateAssembler(@Provided Provider<Camera> camera, String otherParts) {
this.camera = camera;
this.otherParts = otherParts;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.autofactory.provider;
import com.baeldung.autofactory.model.Camera;
import com.google.inject.Provider;
/**
* @author aiet
*/
public class SonyCameraProvider implements Provider<Camera> {
private static int sonyCameraSerial = 1;
@Override
public Camera get() {
return new Camera("Sony", String.format("%03d", sonyCameraSerial++));
}
}

View File

@ -5,4 +5,8 @@
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
- [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload)
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)

View File

@ -1,2 +1,3 @@
## Relevant articles:
- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso)
- [Code Analysis with SonarQube](http://www.baeldung.com/sonar-qube)

View File

@ -8,16 +8,12 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>

View File

@ -28,12 +28,6 @@
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>

View File

@ -0,0 +1,61 @@
package com.baeldung.java10;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class Java10FeaturesUnitTest {
private List<Integer> someIntList;
@Before
public void setup() {
someIntList = new ArrayList<>();
someIntList.add(1);
someIntList.add(2);
someIntList.add(3);
}
@Test
public void whenVarInitWithString_thenGetStringTypeVar() {
var message = "Hello, Java 10";
assertTrue(message instanceof String);
}
@Test
public void whenVarInitWithAnonymous_thenGetAnonymousType() {
var obj = new Object() {};
assertFalse(obj.getClass().equals(Object.class));
}
@Test(expected = UnsupportedOperationException.class)
public void whenModifyCopyOfList_thenThrowsException() {
List<Integer> copyList = List.copyOf(someIntList);
copyList.add(4);
}
@Test(expected = UnsupportedOperationException.class)
public void whenModifyToUnmodifiableList_thenThrowsException() {
List<Integer> evenList = someIntList.stream()
.filter(i -> i % 2 == 0)
.collect(Collectors.toUnmodifiableList());
evenList.add(4);
}
@Test
public void whenListContainsInteger_OrElseThrowReturnsInteger() {
Integer firstEven = someIntList.stream()
.filter(i -> i % 2 == 0)
.findFirst()
.orElseThrow();
is(firstEven).equals(Integer.valueOf(2));
}
}

View File

@ -44,3 +44,10 @@
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)

View File

@ -9,17 +9,12 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</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>

View File

@ -23,3 +23,4 @@
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)

View File

@ -8,10 +8,11 @@
<name>core-java-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
@ -25,11 +26,6 @@
<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>
@ -55,7 +51,6 @@
</dependencies>
<properties>
<guava.version>22.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>

View File

@ -9,17 +9,12 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</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>

View File

@ -25,3 +25,5 @@
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)

View File

@ -9,8 +9,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
@ -20,11 +21,6 @@
<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>

View File

@ -8,8 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
@ -19,11 +20,6 @@
<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>

View File

@ -116,7 +116,7 @@
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [The Observer Pattern in Java](https://github.com/eugenp/tutorials/tree/master/core-java)
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
@ -127,4 +127,23 @@
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger)
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Sending Emails with Java](http://www.baeldung.com/java-email)
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)

View File

@ -9,17 +9,12 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
@ -438,7 +433,6 @@
<log4j.version>1.2.17</log4j.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>

View File

@ -1,5 +0,0 @@
package com.baeldung.designpatterns.creational.abstractfactory;
public interface Color {
String getColor();
}

View File

@ -1,5 +0,0 @@
package com.baeldung.designpatterns.creational.factory;
public interface Polygon {
String getType();
}

View File

@ -1,10 +1,12 @@
package com.baeldung.numberofdigits;
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
import org.apache.log4j.Logger;
public class NumberOfDigitsDriver {
private static NumberOfDigits numberOfDigits;
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
static {
numberOfDigits = new NumberOfDigits();
}

View File

@ -0,0 +1,75 @@
package com.baeldung.stringisnumeric;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class Benchmarking {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Benchmarking.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
@State(Scope.Thread)
public static class ExecutionPlan {
public String number = Integer.toString(Integer.MAX_VALUE);
public boolean isNumber = false;
public IsNumeric isNumeric= new IsNumeric();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingCoreJava(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingRegularExpressions(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
public class IsNumeric {
public boolean usingCoreJava(String strNum) {
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
public boolean usingRegularExpressions(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}
public boolean usingNumberUtils_isCreatable(String strNum) {
return NumberUtils.isCreatable(strNum);
}
public boolean usingNumberUtils_isParsable(String strNum) {
return NumberUtils.isParsable(strNum);
}
public boolean usingStringUtils_isNumeric(String strNum) {
return StringUtils.isNumeric(strNum);
}
public boolean usingStringUtils_isNumericSpace(String strNum) {
return StringUtils.isNumericSpace(strNum);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.stringisnumeric;
import org.apache.log4j.Logger;
public class IsNumericDriver {
private static IsNumeric isNumeric;
private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
static {
isNumeric =new IsNumeric();
}
public static void main(String[] args) {
LOG.info("Testing all methods...");
boolean res = isNumeric.usingCoreJava("1001");
LOG.info("Using Core Java : " + res);
res = isNumeric.usingRegularExpressions("1001");
LOG.info("Using Regular Expressions : " + res);
res =isNumeric.usingNumberUtils_isCreatable("1001");
LOG.info("Using NumberUtils.isCreatable : " + res);
res =isNumeric.usingNumberUtils_isParsable("1001");
LOG.info("Using NumberUtils.isParsable : " + res);
res =isNumeric.usingStringUtils_isNumeric("1001");
LOG.info("Using StringUtils.isNumeric : " + res);
res =isNumeric.usingStringUtils_isNumericSpace("1001");
LOG.info("Using StringUtils.isNumericSpace : " + res);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class CoreJavaIsNumericUnitTest {
public static boolean isNumeric(String strNum) {
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
@Test
public void whenUsingCoreJava_thenTrue() {
// Valid Numbers
assertThat(isNumeric("22")).isTrue();
assertThat(isNumeric("5.05")).isTrue();
assertThat(isNumeric("-200")).isTrue();
assertThat(isNumeric("10.0d")).isTrue();
assertThat(isNumeric(" 22 ")).isTrue();
// Invalid Numbers
assertThat(isNumeric(null)).isFalse();
assertThat(isNumeric("")).isFalse();
assertThat(isNumeric("abc")).isFalse();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class NumberUtilsIsCreatableUnitTest {
@Test
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
// Valid Numbers
assertThat(NumberUtils.isCreatable("22")).isTrue();
assertThat(NumberUtils.isCreatable("5.05")).isTrue();
assertThat(NumberUtils.isCreatable("-200")).isTrue();
assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
assertThat(NumberUtils.isCreatable("1000L")).isTrue();
assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
assertThat(NumberUtils.isCreatable("07")).isTrue();
assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
// Invalid Numbers
assertThat(NumberUtils.isCreatable(null)).isFalse();
assertThat(NumberUtils.isCreatable("")).isFalse();
assertThat(NumberUtils.isCreatable("abc")).isFalse();
assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
assertThat(NumberUtils.isCreatable("09")).isFalse();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;
public class NumberUtilsIsParsableUnitTest {
@Test
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
// Valid Numbers
assertThat(NumberUtils.isParsable("22")).isTrue();
assertThat(NumberUtils.isParsable("-23")).isTrue();
assertThat(NumberUtils.isParsable("2.2")).isTrue();
assertThat(NumberUtils.isParsable("09")).isTrue();
// Invalid Numbers
assertThat(NumberUtils.isParsable(null)).isFalse();
assertThat(NumberUtils.isParsable("")).isFalse();
assertThat(NumberUtils.isParsable("6.2f")).isFalse();
assertThat(NumberUtils.isParsable("9.8d")).isFalse();
assertThat(NumberUtils.isParsable("22L")).isFalse();
assertThat(NumberUtils.isParsable("0xFF")).isFalse();
assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.stringisnumeric;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class RegularExpressionsUnitTest {
public static boolean isNumeric(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}
@Test
public void whenUsingRegularExpressions_thenTrue() {
// Valid Numbers
assertThat(isNumeric("22")).isTrue();
assertThat(isNumeric("5.05")).isTrue();
assertThat(isNumeric("-200")).isTrue();
// Invalid Numbers
assertThat(isNumeric("abc")).isFalse();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringUtilsIsNumericSpaceUnitTest {
@Test
public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
// Valid Numbers
assertThat(StringUtils.isNumericSpace("123")).isTrue();
assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
assertThat(StringUtils.isNumericSpace("")).isTrue();
assertThat(StringUtils.isNumericSpace(" ")).isTrue();
assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
// Invalid Numbers
assertThat(StringUtils.isNumericSpace(null)).isFalse();
assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
assertThat(StringUtils.isNumericSpace("-123")).isFalse();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stringisnumeric;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class StringUtilsIsNumericUnitTest {
@Test
public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
// Valid Numbers
assertThat(StringUtils.isNumeric("123")).isTrue();
assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
assertThat(StringUtils.isNumeric("१२३")).isTrue();
// Invalid Numbers
assertThat(StringUtils.isNumeric(null)).isFalse();
assertThat(StringUtils.isNumeric("")).isFalse();
assertThat(StringUtils.isNumeric(" ")).isFalse();
assertThat(StringUtils.isNumeric("12 3")).isFalse();
assertThat(StringUtils.isNumeric("ab2c")).isFalse();
assertThat(StringUtils.isNumeric("12.3")).isFalse();
assertThat(StringUtils.isNumeric("-123")).isFalse();
}
}

View File

@ -25,3 +25,4 @@
- [Objects in Kotlin](http://www.baeldung.com/kotlin-objects)
- [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file)
- [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation)
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)

View File

@ -25,12 +25,6 @@
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
@ -69,6 +63,24 @@
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlinx.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-api</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-subject-extension</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.spek</groupId>
<artifactId>spek-junit-platform-engine</artifactId>
<version>1.1.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.nhaarman</groupId>
<artifactId>mockito-kotlin</artifactId>

View File

@ -0,0 +1,19 @@
package com.baeldung.filesystem
import java.io.File
class FileWriter {
fun writeFileUsingPrintWriter(fileName: String, fileContent: String) =
File(fileName).printWriter().use { out -> out.print(fileContent) }
fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) =
File(fileName).bufferedWriter().use { out -> out.write(fileContent) }
fun writeFileDirectly(fileName: String, fileContent: String) =
File(fileName).writeText(fileContent)
fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) =
File(fileName).writeBytes(fileContent.toByteArray())
}

View File

@ -0,0 +1,43 @@
package com.baeldung.filesystem
import org.junit.jupiter.api.Test
import java.io.File
import kotlin.test.assertEquals
internal class FileWriterTest {
private val fileName = "src/test/resources/Kotlin.out"
private val fileContent = "Kotlin\nConcise, Safe, Interoperable, Tool-friendly"
private val fileWriter = FileWriter()
@Test
fun whenWrittenWithPrintWriter_thenCorrect() {
fileWriter.writeFileUsingPrintWriter(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
@Test
fun whenWrittenWithBufferedWriter_thenCorrect() {
fileWriter.writeFileUsingBufferedWriter(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
@Test
fun whenWrittenDirectly_thenCorrect() {
fileWriter.writeFileDirectly(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
@Test
fun whenWrittenDirectlyAsBytes_thenCorrect() {
fileWriter.writeFileDirectlyAsBytes(fileName, fileContent)
assertEquals(fileContent, File(fileName).readText())
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.kotlin.spek
import com.baeldung.kotlin.junit5.Calculator
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.junit.jupiter.api.Assertions.assertEquals
class CalculatorSubjectTest5 : SubjectSpek<Calculator>({
subject { Calculator() }
describe("A calculator") {
describe("Addition") {
val result = subject.add(3, 5)
it("Produces the correct answer") {
assertEquals(8, result)
}
}
}
})

View File

@ -0,0 +1,32 @@
package com.baeldung.kotlin.spek
import com.baeldung.kotlin.junit5.Calculator
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.jupiter.api.Assertions.assertEquals
class CalculatorTest5 : Spek({
given("A calculator") {
val calculator = Calculator()
on("Adding 3 and 5") {
val result = calculator.add(3, 5)
it("Produces 8") {
assertEquals(8, result)
}
}
}
describe("A calculator") {
val calculator = Calculator()
describe("Addition") {
val result = calculator.add(3, 5)
it("Produces the correct answer") {
assertEquals(8, result)
}
}
}
})

View File

@ -0,0 +1,21 @@
package com.baeldung.kotlin.spek
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.jupiter.api.Assertions
class DataDrivenTest5 : Spek({
describe("A data driven test") {
mapOf(
"hello" to "HELLO",
"world" to "WORLD"
).forEach { input, expected ->
describe("Capitalising $input") {
it("Correctly returns $expected") {
Assertions.assertEquals(expected, input.toUpperCase())
}
}
}
}
})

View File

@ -0,0 +1,62 @@
package com.baeldung.kotlin.spek
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
class GroupTest5 : Spek({
describe("Outer group") {
beforeEachTest {
System.out.println("BeforeEachTest 0")
}
beforeGroup {
System.out.println("BeforeGroup 0")
}
afterEachTest {
System.out.println("AfterEachTest 0")
}
afterGroup {
System.out.println("AfterGroup 0")
}
describe("Inner group 1") {
beforeEachTest {
System.out.println("BeforeEachTest 1")
}
beforeGroup {
System.out.println("BeforeGroup 1")
}
afterEachTest {
System.out.println("AfterEachTest 1")
}
afterGroup {
System.out.println("AfterGroup 1")
}
it("Test 1") {
System.out.println("Test 1")
}
it("Test 2") {
System.out.println("Test 2")
}
}
describe("Inner group 2") {
beforeEachTest {
System.out.println("BeforeEachTest 2")
}
beforeGroup {
System.out.println("BeforeGroup 2")
}
afterEachTest {
System.out.println("AfterEachTest 2")
}
afterGroup {
System.out.println("AfterGroup 2")
}
it("Test 3") {
System.out.println("Test 3")
}
it("Test 4") {
System.out.println("Test 4")
}
}
}
})

View File

@ -5,10 +5,11 @@
<artifactId>drools</artifactId>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring</relativePath>
</parent>
<dependencies>
<dependency>
@ -47,18 +48,13 @@
<artifactId>poi-ooxml</artifactId>
<version>${apache-poi-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-core.version}</version>
</dependency>
</dependencies>
<properties>
<http-component-version>4.4.6</http-component-version>
<drools-version>7.4.1.Final</drools-version>
<apache-poi-version>3.13</apache-poi-version>
<spring-core.version>4.3.6.RELEASE</spring-core.version>
<spring.version>4.3.6.RELEASE</spring.version>
</properties>
</project>

View File

@ -2,3 +2,4 @@
### Relevant Articles:
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)
- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity)

View File

@ -8,8 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
@ -19,11 +20,6 @@
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>

View File

@ -8,19 +8,11 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>
<guava.version>18.0</guava.version>
</properties>

View File

@ -8,19 +8,11 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<properties>
<guava.version>19.0</guava.version>
</properties>

View File

@ -7,18 +7,12 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>

View File

@ -8,17 +8,13 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</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>
@ -36,6 +32,14 @@
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -56,6 +60,7 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties>
</project>

View File

@ -0,0 +1,259 @@
package org.baeldung.hamcrest;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringEndsWith.endsWith;
import static org.hamcrest.core.StringStartsWith.startsWith;
public class HamcrestCoreMatchersTest {
@Test
public void givenTestInput_WhenUsingIsForMatch() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, is("hamcrest core"));
assertThat(testString, is(equalTo("hamcrest core")));
}
@Test
public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() {
// GIVEN
Object original = 100;
// ASSERT
assertThat(original, equalToObject(100));
}
@Test
public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() {
assertThat("hamcrest", is(instanceOf(String.class)));
}
@Test
public void givenTestInput_WhenUsingIsA_ThenAssertType() {
assertThat("hamcrest core", isA(String.class));
}
@Test
public void givenTestInput_WhenUsingEqualToMatcherForEquality() {
// GIVEN
String actualString = "Hamcrest Core";
List<String> actualList = Lists.newArrayList("hamcrest", "core");
// ASSERT
assertThat(actualString, is(equalTo("Hamcrest Core")));
assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core"))));
}
@Test
public void givenTestInput_WhenUsingNotForMatch() {
// GIVEN
String testString = "hamcrest";
// ASSERT
assertThat(testString, not("hamcrest core"));
assertThat(testString, is(not(equalTo("hamcrest core"))));
assertThat(testString, is(not(instanceOf(Integer.class))));
}
@Test
public void givenTestInput_WhenUsingNullValueForNullCheck() {
// GIVEN
Integer nullObject = null;
// ASSERT
assertThat(nullObject, is(nullValue()));
assertThat(nullObject, is(nullValue(Integer.class)));
}
@Test
public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() {
// GIVEN
Integer testNumber = 123;
// ASSERT
assertThat(testNumber, is(notNullValue()));
assertThat(testNumber, is(notNullValue(Integer.class)));
}
@Test
public void givenString_WhenStartsWith_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, startsWith("hamcrest"));
}
@Test
public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, startsWithIgnoringCase("HAMCREST"));
}
@Test
public void givenString_WhenEndsWith_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, endsWith("core"));
}
@Test
public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, endsWithIgnoringCase("CORE"));
}
@Test
public void givenString_WhenContainsString_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, containsString("co"));
}
@Test
public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() {
// GIVEN
String testString = "hamcrest core";
// ASSERT
assertThat(testString, containsStringIgnoringCase("CO"));
}
@Test
public void givenTestInput_WhenUsingHasItemInCollection() {
// GIVEN
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
// ASSERT
assertThat(list, hasItem("java"));
assertThat(list, hasItem(isA(String.class)));
}
@Test
public void givenTestInput_WhenUsingHasItemsInCollection() {
// GIVEN
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
// ASSERT
assertThat(list, hasItems("java", "baeldung"));
assertThat(list, hasItems(isA(String.class), endsWith("ing")));
}
@Test
public void givenTestInput_WhenUsingAnyForClassType() {
assertThat("hamcrest", is(any(String.class)));
assertThat("hamcrest", is(any(Object.class)));
}
@Test
public void givenTestInput_WhenUsingAllOfForAllMatchers() {
// GIVEN
String testString = "Hamcrest Core";
// ASSERT
assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core")));
}
@Test
public void givenTestInput_WhenUsingAnyOfForAnyMatcher() {
// GIVEN
String testString = "Hamcrest Core";
// ASSERT
assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung")));
}
@Test
public void givenTestInput_WhenUsingBothForMatcher() {
// GIVEN
String testString = "Hamcrest Core Matchers";
// ASSERT
assertThat(testString, both(startsWith("Ham")).and(containsString("Core")));
}
@Test
public void givenTestInput_WhenUsingEitherForMatcher() {
// GIVEN
String testString = "Hamcrest Core Matchers";
// ASSERT
assertThat(testString, either(startsWith("Bael")).or(containsString("Core")));
}
@Test
public void givenTestInput_WhenUsingEveryItemForMatchInCollection() {
// GIVEN
List<String> testItems = Lists.newArrayList("Common", "Core", "Combinable");
// ASSERT
assertThat(testItems, everyItem(startsWith("Co")));
}
@Test
public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() {
// GIVEN
String string1 = "hamcrest";
String string2 = string1;
// ASSERT
assertThat(string1, is(sameInstance(string2)));
}
@Test
public void givenTwoTestInputs_WhenUsingTheInstanceForMatch() {
// GIVEN
String string1 = "hamcrest";
String string2 = string1;
// ASSERT
assertThat(string1, is(theInstance(string2)));
}
}

View File

@ -12,6 +12,7 @@ import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.emptyIterable;
import java.util.Collections;
import java.util.List;
@ -57,6 +58,12 @@ public class HamcrestExamplesUnitTest {
final List<String> collection = Lists.newArrayList();
assertThat(collection, empty());
}
@Test
public final void givenIterableIsEmpty_whenChecking_thenEmpty() {
final Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());
}
@Test
public final void givenCollectionIsNotEmpty_whenChecking_thenNotEmpty() {

View File

@ -1,2 +1,3 @@
### Relevant Articles:
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)
- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers)

View File

@ -11,11 +11,6 @@
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.0-M4</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
@ -62,4 +57,8 @@
</plugin>
</plugins>
</build>
<properties>
</properties>
</project>

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring</relativePath>
</parent>
<dependencies>

View File

@ -9,3 +9,4 @@
- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor)
- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters)
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)

View File

@ -8,17 +8,13 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</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-lang3</artifactId>

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@ -89,7 +90,7 @@ public class HttpClientAuthLiveTest {
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
final String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
@ -129,7 +130,7 @@ public class HttpClientAuthLiveTest {
private String authorizationHeader(final String username, final String password) {
final String auth = username + ":" + password;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}

View File

@ -1,7 +1,8 @@
## Influx SDK Tutorial Project
### Relevant Article:
- [Introduction to using InfluxDB with Java](http://www.baeldung.com/using-influxdb-with-java/)
- [Using InfluxDB with Java](http://www.baeldung.com/java-influxdb)
### Overview
This Maven project contains the Java code for the article linked above.

View File

@ -8,18 +8,13 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
- [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp)
- [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session)

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
@ -25,17 +26,6 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -2,3 +2,4 @@
- [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3)
- [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language)
- [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf)
- [Introduction to Primefaces](http://www.baeldung.com/jsf-primefaces)

View File

@ -4,6 +4,7 @@
### Relevant Articles:
- [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java)
- [A Guide to FastJson](http://www.baeldung.com/????????)
- [A Guide to FastJson](http://www.baeldung.com/fastjson)
- [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms)
- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath)
- [Introduction to JSON-Java (org.json)](http://www.baeldung.com/java-org-json)

View File

@ -34,12 +34,6 @@
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>

View File

@ -3,5 +3,5 @@
- [Introduction to ORMLite](http://www.baeldung.com/ormlite)
- [Introduction To Kryo](http://www.baeldung.com/kryo)
- [Introduction to KafkaStreams in Java](http://www.baeldung.com/java-kafka-streams)
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)

View File

@ -65,7 +65,7 @@
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [Asynchronous HTTP with async-http-client in Java](https://github.com/eugenp/tutorials/tree/master/libraries)
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
- [Introduction to Smooks](http://www.baeldung.com/smooks)
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
@ -74,7 +74,16 @@
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils)
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)
- [Introduction to jOOL](http://www.baeldung.com/jool)
- [Consumer Driven Contracts with Pact](http://www.baeldung.com/pact-junit-consumer-driven-contracts)
- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils)
- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map)
- [Introduction to Atlassian Fugue](http://www.baeldung.com/java-fugue)
- [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client)
- [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools)
- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils)
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -680,6 +680,12 @@
<version>${unirest.version}</version>
</dependency>
<!-- javalin -->
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
<version>1.6.0</version>
</dependency>
<!-- Atlassian Fugue -->
<dependency>
<groupId>io.atlassian.fugue</groupId>

View File

@ -0,0 +1,16 @@
package com.baeldung.javalin;
import com.baeldung.javalin.User.UserController;
import io.javalin.Javalin;
public class JavalinApp {
public static void main(String[] args) {
Javalin app = Javalin.create()
.port(7000)
.start();
app.get("/hello", ctx -> ctx.html("Hello, Javalin!"));
app.get("/users", UserController.fetchAllUsernames);
app.get("/users/:id", UserController.fetchById);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.javalin.User;
public class User {
public final int id;
public final String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.javalin.User;
import io.javalin.Handler;
import java.util.Objects;
public class UserController {
public static Handler fetchAllUsernames = ctx -> {
UserDao dao = UserDao.instance();
Iterable<String> allUsers = dao.getAllUsernames();
ctx.json(allUsers);
};
public static Handler fetchById = ctx -> {
int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id")));
UserDao dao = UserDao.instance();
User user = dao.getUserById(id);
if (user == null) {
ctx.html("Not Found");
} else {
ctx.json(user);
}
};
}

View File

@ -0,0 +1,33 @@
package com.baeldung.javalin.User;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class UserDao {
private final List<User> users = Arrays.asList(
new User(0, "Steve Rogers"),
new User(1, "Tony Stark"),
new User(2, "Carol Danvers")
);
private static UserDao userDao = null;
private UserDao() {
}
static UserDao instance() {
if (userDao == null) {
userDao = new UserDao();
}
return userDao;
}
Optional<User> getUserById(int id) { return users.stream().filter(u -> u.id == id).findFirst(); }
Iterable<String> getAllUsernames() {
return users.stream().map(user -> user.name).collect(Collectors.toList());
}
}

View File

@ -5,3 +5,4 @@
- [Creating a Custom Logback Appender](http://www.baeldung.com/custom-logback-appender)
- [Get Log Output in JSON Format](http://www.baeldung.com/java-log-json-output)
- [A Guide To Logback](http://www.baeldung.com/a-guide-to-logback)

View File

@ -9,28 +9,22 @@
<description>tutorial on logging with MDC and NDC</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-spring</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
@ -79,14 +73,14 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<springframework.version>4.3.4.RELEASE</springframework.version>
<spring.version>4.3.4.RELEASE</spring.version>
<log4j.version>1.2.17</log4j.version>
<log4j2.version>2.7</log4j2.version>
<disruptor.version>3.3.6</disruptor.version>

View File

@ -0,0 +1,19 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>log4j2-programmatic-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>modify-xml-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>modify-xml-configuration</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,29 @@
/**
This class demonstrates on modifying the loaded xml configuration by
extending XMLConfigurationFactory as defined in section 4.4 of
"Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.config;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Order;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory;
@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomXMLConfigurationFactory extends XmlConfigurationFactory {
@Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
return new MyXMLConfiguration(loggerContext, source);
}
@Override
public String[] getSupportedTypes() {
return new String[] { ".xml", "*" };
}
}

View File

@ -0,0 +1,35 @@
/**
This class demonstrates on overriding the configuration loaded through xml
as defined in section 4.4 of "Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.config;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.xml.XmlConfiguration;
import org.apache.logging.log4j.core.layout.PatternLayout;
public class MyXMLConfiguration extends XmlConfiguration {
public MyXMLConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
super(loggerContext, source);
}
@Override
protected void doConfigure() {
super.doConfigure();
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig("com");
final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null);
Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config);
loggerConfig.addAppender(appender, Level.DEBUG, null);
addAppender(appender);
}
}

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="60">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="com" additivity="false" level="info">
<AppenderRef ref="console" />
</Logger>
<Root>
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,23 @@
package com.baeldung.log4j2.logtest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.plugins.util.PluginManager;
import org.junit.Test;
public class LogTest {
static{
PluginManager.addPackage("com.baeldung.log4j2.config");
}
@Test
public void simpleProgrammaticConfiguration() {
Logger logger = LogManager.getLogger();
LoggerContext ctx = (LoggerContext) LogManager.getContext();
logger.debug("Debug log message");
logger.info("Info log message");
logger.error("Error log message");
}
}

View File

@ -0,0 +1,34 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>log4j2-programmatic-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>simple-configuration</module>
<module>set-configuration-factory</module>
<module>simple-configurator</module>
<module>simple-configuration-xml</module>
<module>modify-xml-configuration</module>
</modules>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,10 @@
<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>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>log4j2-programmatic-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>set-configuration-factory</artifactId>
</project>

View File

@ -0,0 +1,88 @@
/**
This class demonstrates how to build the components of
the configuration factory, as described in Section 3 of
"Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.config;
import java.io.IOException;
import java.net.URI;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.FilterComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
public class CustomConfigurationFactory extends ConfigurationFactory {
static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
AppenderComponentBuilder console = builder.newAppender("Stdout", "Console");
LayoutComponentBuilder layout = builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable");
console.add(layout);
FilterComponentBuilder filter = builder.newFilter("MarkerFilter", Filter.Result.ACCEPT, Filter.Result.DENY);
filter.addAttribute("marker", "FLOW");
console.add(filter);
builder.add(console);
ComponentBuilder triggeringPolicies = builder.newComponent("Policies")
.addComponent(builder.newComponent("CronTriggeringPolicy")
.addAttribute("schedule", "0 0 0 * * ?"))
.addComponent(builder.newComponent("SizeBasedTriggeringPolicy")
.addAttribute("size", "100M"));
AppenderComponentBuilder rollingFile = builder.newAppender("rolling", "RollingFile");
rollingFile.addAttribute("fileName", "target/rolling.log");
rollingFile.addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz");
rollingFile.add(layout);
rollingFile.addComponent(triggeringPolicies);
builder.add(rollingFile);
AppenderComponentBuilder file = builder.newAppender("FileSystem", "File");
file.addAttribute("fileName", "target/logging.log");
file.add(layout);
builder.add(file);
LoggerComponentBuilder logger = builder.newLogger("com", Level.DEBUG);
logger.add(builder.newAppenderRef("Stdout"));
logger.add(builder.newAppenderRef("rolling"));
logger.add(builder.newAppenderRef("FileSystem"));
logger.addAttribute("additivity", false);
builder.add(logger);
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.ERROR);
rootLogger.add(builder.newAppenderRef("Stdout"));
rootLogger.add(builder.newAppenderRef("rolling"));
rootLogger.add(builder.newAppenderRef("FileSystem"));
rootLogger.addAttribute("additivity", false);
builder.add(rootLogger);
try {
builder.writeXmlConfiguration(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.build();
}
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
return createConfiguration(name, builder);
}
@Override
protected String[] getSupportedTypes() {
return new String[] { "*" };
}
@Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
return getConfiguration(loggerContext, source.toString(), null);
}
}

View File

@ -0,0 +1,33 @@
/**
This class invokes the configuration factory with static initialization,
as defined in section 4.1 of the "Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.logtest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.baeldung.log4j2.config.CustomConfigurationFactory;
@RunWith(JUnit4.class)
public class LogTest {
static {
CustomConfigurationFactory customConfigurationFactory = new CustomConfigurationFactory();
ConfigurationFactory.setConfigurationFactory(customConfigurationFactory);
}
@Test
public void simpleProgrammaticConfiguration() {
Logger logger = LogManager.getLogger();
Marker markerContent = MarkerManager.getMarker("FLOW");
logger.debug(markerContent, "Debug log message");
logger.info(markerContent, "Info log message");
logger.error(markerContent, "Error log message");
}
}

View File

@ -0,0 +1,17 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>log4j2-programmatic-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>simple-configuration-xml</artifactId>
<name>simple-configuration-xml</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,32 @@
<?xml version="1.0" ?>
<Configuration>
<Appenders>
<Console name="Stdout">
<PatternLayout pattern="%d [%t] %-5level: %msg%n%throwable" />
<MarkerFilter onMatch="ACCEPT" onMismatch="DENY" marker="FLOW" />
</Console>
<RollingFile name="rolling" fileName="target/rolling.log"
filePattern="target/archive/rolling-%d{MM-dd-yy}.log.gz">
<PatternLayout pattern="%d [%t] %-5level: %msg%n%throwable" />
<Policies>
<CronTriggeringPolicy schedule="0 0 0 * * ?" />
<SizeBasedTriggeringPolicy size="100M" />
</Policies>
</RollingFile>
<File name="FileSystem" fileName="target/logging.log">
<PatternLayout pattern="%d [%t] %-5level: %msg%n%throwable" />
</File>
</Appenders>
<Loggers>
<Logger name="com" level="DEBUG" additivity="false">
<AppenderRef ref="Stdout" />
<AppenderRef ref="rolling" />
<AppenderRef ref="FileSystem" />
</Logger>
<Root level="ERROR" additivity="false">
<AppenderRef ref="Stdout" />
<AppenderRef ref="rolling" />
<AppenderRef ref="FileSystem" />
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,30 @@
/**
This class loads the logging configuration from the xml defined in
src/main/resources and uses the same configuration generated through
programmatic configuration as defined in simple-configuration example.
**/
package com.baeldung.log4j2.logtest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class LogTest {
@Test
public void simpleProgrammaticConfiguration(){
Logger logger = LogManager.getLogger();
Marker markerContent = MarkerManager.getMarker("FLOW");
logger.debug(markerContent, "Debug log message");
logger.info(markerContent, "Info log message");
logger.error(markerContent, "Error log message");
}
}

View File

@ -0,0 +1,10 @@
<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>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>log4j2-programmatic-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>simple-configuration</artifactId>
</project>

View File

@ -0,0 +1,94 @@
/**
This class demonstrates how to build the components of
the configuration factory, as described in Section 3 of
"Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.config;
import java.io.IOException;
import java.net.URI;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Order;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.FilterComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {
static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
AppenderComponentBuilder console = builder.newAppender("Stdout", "Console");
LayoutComponentBuilder layout = builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable");
console.add(layout);
FilterComponentBuilder filter = builder.newFilter("MarkerFilter", Filter.Result.ACCEPT, Filter.Result.DENY);
filter.addAttribute("marker", "FLOW");
console.add(filter);
builder.add(console);
ComponentBuilder triggeringPolicies = builder.newComponent("Policies")
.addComponent(builder.newComponent("CronTriggeringPolicy")
.addAttribute("schedule", "0 0 0 * * ?"))
.addComponent(builder.newComponent("SizeBasedTriggeringPolicy")
.addAttribute("size", "100M"));
AppenderComponentBuilder rollingFile = builder.newAppender("rolling", "RollingFile");
rollingFile.addAttribute("fileName", "target/rolling.log");
rollingFile.addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz");
rollingFile.add(layout);
rollingFile.addComponent(triggeringPolicies);
builder.add(rollingFile);
AppenderComponentBuilder file = builder.newAppender("FileSystem", "File");
file.addAttribute("fileName", "target/logging.log");
file.add(layout);
builder.add(file);
LoggerComponentBuilder logger = builder.newLogger("com", Level.DEBUG);
logger.add(builder.newAppenderRef("Stdout"));
logger.add(builder.newAppenderRef("rolling"));
logger.add(builder.newAppenderRef("FileSystem"));
logger.addAttribute("additivity", false);
builder.add(logger);
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.ERROR);
rootLogger.add(builder.newAppenderRef("Stdout"));
rootLogger.add(builder.newAppenderRef("rolling"));
// rootLogger.add(builder.newAppenderRef("syslogAppender"));
rootLogger.add(builder.newAppenderRef("FileSystem"));
rootLogger.addAttribute("additivity", false);
builder.add(rootLogger);
try {
builder.writeXmlConfiguration(System.out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.build();
}
@Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
return getConfiguration(loggerContext, source.toString(), null);
}
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
return createConfiguration(name, builder);
}
@Override
protected String[] getSupportedTypes() {
return new String[] { "*" };
}
}

View File

@ -0,0 +1,22 @@
/**
This class invokes the configuration factory through the run time property,
as defined in section 4.2 of the "Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.logtest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import org.junit.Test;
public class LogTest {
@Test
public void simpleProgrammaticConfiguration() {
Logger logger = LogManager.getLogger();
Marker markerContent = MarkerManager.getMarker("FLOW");
logger.debug(markerContent, "Debug log message");
logger.info(markerContent, "Info log message");
logger.error(markerContent, "Error log message");
}
}

View File

@ -0,0 +1,10 @@
<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>
<groupId>com.baeldung.log4j2</groupId>
<artifactId>log4j2-programmatic-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>simple-configurator</artifactId>
</project>

View File

@ -0,0 +1,40 @@
/**
This class demonstrates how to use ConfigurationBuilderFactory directly,
as described in Section 3 of "Programmatic Configuration with Log4j 2"
**/
package com.baeldung.log4j2.configure;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.baeldung.log4j2.logtest.LogPrinter;
@RunWith(JUnit4.class)
public class LogTest {
@Test
public void simpleProgrammaticConfiguration() {
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE")
.addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
console.add(builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
builder.add(console);
builder.add(builder.newLogger("com", Level.DEBUG)
.add(builder.newAppenderRef("Stdout"))
.addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.ERROR)
.add(builder.newAppenderRef("Stdout")));
Configurator.initialize(builder.build());
LogPrinter logPrinter = new LogPrinter();
logPrinter.printlog();
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.log4j2.logtest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LogPrinter {
private Logger logger = LogManager.getLogger();
public void printlog() {
logger.debug("Debug log message");
logger.info("Info log message");
logger.error("Error log message");
}
}

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