Merge remote-tracking branch 'upstream/master'

This commit is contained in:
pazis 2019-08-23 21:03:01 +00:00
commit ad2fa55268
371 changed files with 3352 additions and 780 deletions

View File

@ -4,7 +4,7 @@ import org.apache.commons.lang3.StringUtils;
public class PrintTriangleExamples {
public static String printARightAngledTriangle(int N) {
public static String printARightTriangle(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
for (int j = 1; j <= r; j++) {
@ -29,6 +29,17 @@ public class PrintTriangleExamples {
return result.toString();
}
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
result.append(StringUtils.repeat(' ', N - r));
result.append(StringUtils.repeat('*', 2 * r - 1));
result.append(System.lineSeparator());
}
return result.toString();
}
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
StringBuilder result = new StringBuilder();
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
@ -41,8 +52,9 @@ public class PrintTriangleExamples {
}
public static void main(String[] args) {
System.out.println(printARightAngledTriangle(5));
System.out.println(printARightTriangle(5));
System.out.println(printAnIsoscelesTriangle(5));
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
}

View File

@ -9,9 +9,9 @@ import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class PrintTriangleExamplesUnitTest {
private static Object[][] rightAngledTriangles() {
String expected0 = "";
private static Object[][] rightTriangles() {
String expected0 = "";
String expected2 = "*" + System.lineSeparator()
+ "**" + System.lineSeparator();
@ -39,9 +39,9 @@ public class PrintTriangleExamplesUnitTest {
}
@Test
@Parameters(method = "rightAngledTriangles")
public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows);
@Parameters(method = "rightTriangles")
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
assertEquals(expected, actual);
}
@ -81,6 +81,14 @@ public class PrintTriangleExamplesUnitTest {
assertEquals(expected, actual);
}
@Test
@Parameters(method = "isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
assertEquals(expected, actual);
}
@Test
@Parameters(method = "isoscelesTriangles")

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.stringsortingbynumber;
package com.baeldung.algorithms.sort.bynumber;
import java.util.Comparator;

View File

@ -1,6 +1,6 @@
package com.baeldung.algorithms.stringsortingbynumber;
package com.baeldung.algorithms.sort.bynumber;
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators;
import org.junit.Test;
import java.util.ArrayList;

150
apache-spark/data/iris.data Normal file
View File

@ -0,0 +1,150 @@
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5.0,3.4,1.5,0.2,Iris-setosa
4.4,2.9,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.4,3.7,1.5,0.2,Iris-setosa
4.8,3.4,1.6,0.2,Iris-setosa
4.8,3.0,1.4,0.1,Iris-setosa
4.3,3.0,1.1,0.1,Iris-setosa
5.8,4.0,1.2,0.2,Iris-setosa
5.7,4.4,1.5,0.4,Iris-setosa
5.4,3.9,1.3,0.4,Iris-setosa
5.1,3.5,1.4,0.3,Iris-setosa
5.7,3.8,1.7,0.3,Iris-setosa
5.1,3.8,1.5,0.3,Iris-setosa
5.4,3.4,1.7,0.2,Iris-setosa
5.1,3.7,1.5,0.4,Iris-setosa
4.6,3.6,1.0,0.2,Iris-setosa
5.1,3.3,1.7,0.5,Iris-setosa
4.8,3.4,1.9,0.2,Iris-setosa
5.0,3.0,1.6,0.2,Iris-setosa
5.0,3.4,1.6,0.4,Iris-setosa
5.2,3.5,1.5,0.2,Iris-setosa
5.2,3.4,1.4,0.2,Iris-setosa
4.7,3.2,1.6,0.2,Iris-setosa
4.8,3.1,1.6,0.2,Iris-setosa
5.4,3.4,1.5,0.4,Iris-setosa
5.2,4.1,1.5,0.1,Iris-setosa
5.5,4.2,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.0,3.2,1.2,0.2,Iris-setosa
5.5,3.5,1.3,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
4.4,3.0,1.3,0.2,Iris-setosa
5.1,3.4,1.5,0.2,Iris-setosa
5.0,3.5,1.3,0.3,Iris-setosa
4.5,2.3,1.3,0.3,Iris-setosa
4.4,3.2,1.3,0.2,Iris-setosa
5.0,3.5,1.6,0.6,Iris-setosa
5.1,3.8,1.9,0.4,Iris-setosa
4.8,3.0,1.4,0.3,Iris-setosa
5.1,3.8,1.6,0.2,Iris-setosa
4.6,3.2,1.4,0.2,Iris-setosa
5.3,3.7,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
6.9,3.1,4.9,1.5,Iris-versicolor
5.5,2.3,4.0,1.3,Iris-versicolor
6.5,2.8,4.6,1.5,Iris-versicolor
5.7,2.8,4.5,1.3,Iris-versicolor
6.3,3.3,4.7,1.6,Iris-versicolor
4.9,2.4,3.3,1.0,Iris-versicolor
6.6,2.9,4.6,1.3,Iris-versicolor
5.2,2.7,3.9,1.4,Iris-versicolor
5.0,2.0,3.5,1.0,Iris-versicolor
5.9,3.0,4.2,1.5,Iris-versicolor
6.0,2.2,4.0,1.0,Iris-versicolor
6.1,2.9,4.7,1.4,Iris-versicolor
5.6,2.9,3.6,1.3,Iris-versicolor
6.7,3.1,4.4,1.4,Iris-versicolor
5.6,3.0,4.5,1.5,Iris-versicolor
5.8,2.7,4.1,1.0,Iris-versicolor
6.2,2.2,4.5,1.5,Iris-versicolor
5.6,2.5,3.9,1.1,Iris-versicolor
5.9,3.2,4.8,1.8,Iris-versicolor
6.1,2.8,4.0,1.3,Iris-versicolor
6.3,2.5,4.9,1.5,Iris-versicolor
6.1,2.8,4.7,1.2,Iris-versicolor
6.4,2.9,4.3,1.3,Iris-versicolor
6.6,3.0,4.4,1.4,Iris-versicolor
6.8,2.8,4.8,1.4,Iris-versicolor
6.7,3.0,5.0,1.7,Iris-versicolor
6.0,2.9,4.5,1.5,Iris-versicolor
5.7,2.6,3.5,1.0,Iris-versicolor
5.5,2.4,3.8,1.1,Iris-versicolor
5.5,2.4,3.7,1.0,Iris-versicolor
5.8,2.7,3.9,1.2,Iris-versicolor
6.0,2.7,5.1,1.6,Iris-versicolor
5.4,3.0,4.5,1.5,Iris-versicolor
6.0,3.4,4.5,1.6,Iris-versicolor
6.7,3.1,4.7,1.5,Iris-versicolor
6.3,2.3,4.4,1.3,Iris-versicolor
5.6,3.0,4.1,1.3,Iris-versicolor
5.5,2.5,4.0,1.3,Iris-versicolor
5.5,2.6,4.4,1.2,Iris-versicolor
6.1,3.0,4.6,1.4,Iris-versicolor
5.8,2.6,4.0,1.2,Iris-versicolor
5.0,2.3,3.3,1.0,Iris-versicolor
5.6,2.7,4.2,1.3,Iris-versicolor
5.7,3.0,4.2,1.2,Iris-versicolor
5.7,2.9,4.2,1.3,Iris-versicolor
6.2,2.9,4.3,1.3,Iris-versicolor
5.1,2.5,3.0,1.1,Iris-versicolor
5.7,2.8,4.1,1.3,Iris-versicolor
6.3,3.3,6.0,2.5,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
7.1,3.0,5.9,2.1,Iris-virginica
6.3,2.9,5.6,1.8,Iris-virginica
6.5,3.0,5.8,2.2,Iris-virginica
7.6,3.0,6.6,2.1,Iris-virginica
4.9,2.5,4.5,1.7,Iris-virginica
7.3,2.9,6.3,1.8,Iris-virginica
6.7,2.5,5.8,1.8,Iris-virginica
7.2,3.6,6.1,2.5,Iris-virginica
6.5,3.2,5.1,2.0,Iris-virginica
6.4,2.7,5.3,1.9,Iris-virginica
6.8,3.0,5.5,2.1,Iris-virginica
5.7,2.5,5.0,2.0,Iris-virginica
5.8,2.8,5.1,2.4,Iris-virginica
6.4,3.2,5.3,2.3,Iris-virginica
6.5,3.0,5.5,1.8,Iris-virginica
7.7,3.8,6.7,2.2,Iris-virginica
7.7,2.6,6.9,2.3,Iris-virginica
6.0,2.2,5.0,1.5,Iris-virginica
6.9,3.2,5.7,2.3,Iris-virginica
5.6,2.8,4.9,2.0,Iris-virginica
7.7,2.8,6.7,2.0,Iris-virginica
6.3,2.7,4.9,1.8,Iris-virginica
6.7,3.3,5.7,2.1,Iris-virginica
7.2,3.2,6.0,1.8,Iris-virginica
6.2,2.8,4.8,1.8,Iris-virginica
6.1,3.0,4.9,1.8,Iris-virginica
6.4,2.8,5.6,2.1,Iris-virginica
7.2,3.0,5.8,1.6,Iris-virginica
7.4,2.8,6.1,1.9,Iris-virginica
7.9,3.8,6.4,2.0,Iris-virginica
6.4,2.8,5.6,2.2,Iris-virginica
6.3,2.8,5.1,1.5,Iris-virginica
6.1,2.6,5.6,1.4,Iris-virginica
7.7,3.0,6.1,2.3,Iris-virginica
6.3,3.4,5.6,2.4,Iris-virginica
6.4,3.1,5.5,1.8,Iris-virginica
6.0,3.0,4.8,1.8,Iris-virginica
6.9,3.1,5.4,2.1,Iris-virginica
6.7,3.1,5.6,2.4,Iris-virginica
6.9,3.1,5.1,2.3,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
6.8,3.2,5.9,2.3,Iris-virginica
6.7,3.3,5.7,2.5,Iris-virginica
6.7,3.0,5.2,2.3,Iris-virginica
6.3,2.5,5.0,1.9,Iris-virginica
6.5,3.0,5.2,2.0,Iris-virginica
6.2,3.4,5.4,2.3,Iris-virginica
5.9,3.0,5.1,1.8,Iris-virginica

View File

@ -0,0 +1 @@
{"class":"org.apache.spark.mllib.classification.LogisticRegressionModel","version":"1.0","numFeatures":4,"numClasses":3}

View File

@ -1,31 +1,32 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<name>apache-spark</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<name>apache-spark</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>${org.apache.spark.spark-core.version}</version>
<scope>provided</scope>
</dependency>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>${org.apache.spark.spark-sql.version}</version>
<scope>provided</scope>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>${org.apache.spark.spark-core.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>${org.apache.spark.spark-sql.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
@ -33,6 +34,12 @@
<version>${org.apache.spark.spark-streaming.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-mllib_2.11</artifactId>
<version>${org.apache.spark.spark-mllib.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
@ -48,46 +55,47 @@
<artifactId>spark-cassandra-connector-java_2.11</artifactId>
<version>${com.datastax.spark.spark-cassandra-connector-java.version}</version>
</dependency>
</dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
<org.apache.spark.spark-streaming.version>2.3.0</org.apache.spark.spark-streaming.version>
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<properties>
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
<org.apache.spark.spark-streaming.version>2.3.0</org.apache.spark.spark-streaming.version>
<org.apache.spark.spark-mllib.version>2.3.0</org.apache.spark.spark-mllib.version>
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
</properties>
</properties>
</project>

View File

@ -0,0 +1,111 @@
package com.baeldung.ml;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.mllib.classification.LogisticRegressionModel;
import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS;
import org.apache.spark.mllib.evaluation.MulticlassMetrics;
import org.apache.spark.mllib.linalg.Matrix;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.stat.MultivariateStatisticalSummary;
import org.apache.spark.mllib.stat.Statistics;
import scala.Tuple2;
public class MachineLearningApp {
public static void main(String[] args) {
// 1. Setting the Spark Context
SparkConf conf = new SparkConf().setAppName("Main")
.setMaster("local[2]")
.set("spark.executor.memory", "3g")
.set("spark.driver.memory", "3g");
JavaSparkContext sc = new JavaSparkContext(conf);
Logger.getLogger("org")
.setLevel(Level.OFF);
Logger.getLogger("akka")
.setLevel(Level.OFF);
// 2. Loading the Data-set
String dataFile = "data\\iris.data";
JavaRDD<String> data = sc.textFile(dataFile);
// 3. Exploratory Data Analysis
// 3.1. Creating Vector of Input Data
JavaRDD<Vector> inputData = data.map(line -> {
String[] parts = line.split(",");
double[] v = new double[parts.length - 1];
for (int i = 0; i < parts.length - 1; i++) {
v[i] = Double.parseDouble(parts[i]);
}
return Vectors.dense(v);
});
// 3.2. Performing Statistical Analysis
MultivariateStatisticalSummary summary = Statistics.colStats(inputData.rdd());
System.out.println("Summary Mean:");
System.out.println(summary.mean());
System.out.println("Summary Variance:");
System.out.println(summary.variance());
System.out.println("Summary Non-zero:");
System.out.println(summary.numNonzeros());
// 3.3. Performing Correlation Analysis
Matrix correlMatrix = Statistics.corr(inputData.rdd(), "pearson");
System.out.println("Correlation Matrix:");
System.out.println(correlMatrix.toString());
// 4. Data Preparation
// 4.1. Creating Map for Textual Output Labels
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Iris-setosa", 0);
map.put("Iris-versicolor", 1);
map.put("Iris-virginica", 2);
// 4.2. Creating LabeledPoint of Input and Output Data
JavaRDD<LabeledPoint> parsedData = data.map(line -> {
String[] parts = line.split(",");
double[] v = new double[parts.length - 1];
for (int i = 0; i < parts.length - 1; i++) {
v[i] = Double.parseDouble(parts[i]);
}
return new LabeledPoint(map.get(parts[parts.length - 1]), Vectors.dense(v));
});
// 5. Data Splitting into 80% Training and 20% Test Sets
JavaRDD<LabeledPoint>[] splits = parsedData.randomSplit(new double[] { 0.8, 0.2 }, 11L);
JavaRDD<LabeledPoint> trainingData = splits[0].cache();
JavaRDD<LabeledPoint> testData = splits[1];
// 6. Modeling
// 6.1. Model Training
LogisticRegressionModel model = new LogisticRegressionWithLBFGS().setNumClasses(3)
.run(trainingData.rdd());
// 6.2. Model Evaluation
JavaPairRDD<Object, Object> predictionAndLabels = testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label()));
MulticlassMetrics metrics = new MulticlassMetrics(predictionAndLabels.rdd());
double accuracy = metrics.accuracy();
System.out.println("Model Accuracy on Test Data: " + accuracy);
// 7. Model Saving and Loading
// 7.1. Model Saving
model.save(sc.sc(), "model\\logistic-regression");
// 7.2. Model Loading
LogisticRegressionModel sameModel = LogisticRegressionModel.load(sc.sc(), "model\\logistic-regression");
// 7.3. Prediction on New Data
Vector newData = Vectors.dense(new double[] { 1, 1, 1, 1 });
double prediction = sameModel.predict(newData);
System.out.println("Model Prediction on New Data = " + prediction);
// 8. Clean-up
sc.close();
}
}

31
bazel/WORKSPACE Normal file
View File

@ -0,0 +1,31 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_jar")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
RULES_JVM_EXTERNAL_TAG = "2.0.1"
RULES_JVM_EXTERNAL_SHA = "55e8d3951647ae3dffde22b4f7f8dee11b3f70f3f89424713debd7076197eaca"
http_archive(
name = "rules_jvm_external",
strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
sha256 = RULES_JVM_EXTERNAL_SHA,
url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
)
load("@rules_jvm_external//:defs.bzl", "maven_install")
maven_install(
artifacts = [
"org.apache.commons:commons-lang3:3.9"
],
repositories = [
"https://repo1.maven.org/maven2",
]
)
http_jar (
name = "apache-commons-lang",
url = "https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar"
)

7
bazel/bazelapp/BUILD Normal file
View File

@ -0,0 +1,7 @@
java_binary (
name = "BazelApp",
srcs = glob(["src/main/java/com/baeldung/*.java"]),
main_class = "com.baeldung.BazelApp",
deps = ["//bazelgreeting:greeter", "@maven//:org_apache_commons_commons_lang3"]
)

28
bazel/bazelapp/pom.xml Normal file
View File

@ -0,0 +1,28 @@
<?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>
<artifactId>bazel</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>bazelapp</artifactId>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>bazelgreeting</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung;
import com.baeldung.Greetings;
import org.apache.commons.lang3.StringUtils;
public class BazelApp {
public static void main(String ... args) {
Greetings greetings = new Greetings();
System.out.println(greetings.greet("Bazel"));
System.out.println(StringUtils.lowerCase("Bazel"));
}
}

View File

@ -0,0 +1,6 @@
java_library (
name = "greeter",
srcs = glob(["src/main/java/com/baeldung/*.java"]),
visibility = ["//bazelapp:__pkg__"]
)

View File

@ -0,0 +1,15 @@
<?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>
<artifactId>bazel</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>bazelgreeting</artifactId>
</project>

View File

@ -0,0 +1,8 @@
package com.baeldung;
public class Greetings {
public String greet(String name) {
return "Hello ".concat(name);
}
}

20
bazel/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<?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>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>bazel</artifactId>
<packaging>pom</packaging>
<modules>
<module>bazelgreeting</module>
<module>bazelapp</module>
</modules>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.concurrent.mutex;
public class SequenceGenerator {
private int currentValue = 0;
public int getNextSequence() throws InterruptedException {
currentValue = currentValue + 1;
Thread.sleep(500);
return currentValue;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.concurrent.mutex;
import com.google.common.util.concurrent.Monitor;
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
private Monitor monitor = new Monitor();
@Override
public int getNextSequence() throws InterruptedException {
monitor.enter();
try {
return super.getNextSequence();
} finally {
monitor.leave();
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.concurrent.mutex;
import java.util.concurrent.locks.ReentrantLock;
public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
private ReentrantLock mutex = new ReentrantLock();
@Override
public int getNextSequence() throws InterruptedException {
try {
mutex.lock();
return super.getNextSequence();
} finally {
mutex.unlock();
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.concurrent.mutex;
import java.util.concurrent.Semaphore;
public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
private Semaphore mutex = new Semaphore(1);
@Override
public int getNextSequence() throws InterruptedException {
try {
mutex.acquire();
return super.getNextSequence();
} finally {
mutex.release();
}
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.concurrent.mutex;
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
@Override
public int getNextSequence() throws InterruptedException {
synchronized (this) {
return super.getNextSequence();
}
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.concurrent.mutex;
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
@Override
public synchronized int getNextSequence() throws InterruptedException {
return super.getNextSequence();
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.concurrent.mutex;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.concurrent.mutex.SequenceGenerator;
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingMonitor;
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingReentrantLock;
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSemaphore;
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedBlock;
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedMethod;
public class MutexUnitTest {
private final int RANGE = 30;
@Test
public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception {
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGenerator());
Assert.assertNotEquals(RANGE, uniqueSequences.size());
}
@Test
public void givenSequenceGeneratorUsingSynchronizedMethod_whenRaceCondition_thenSuccess() throws Exception {
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod());
Assert.assertEquals(RANGE, uniqueSequences.size());
}
@Test
public void givenSequenceGeneratorUsingSynchronizedBlock_whenRaceCondition_thenSuccess() throws Exception {
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock());
Assert.assertEquals(RANGE, uniqueSequences.size());
}
@Test
public void givenSequenceGeneratorUsingReentrantLock_whenRaceCondition_thenSuccess() throws Exception {
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingReentrantLock());
Assert.assertEquals(RANGE, uniqueSequences.size());
}
@Test
public void givenSequenceGeneratorUsingSemaphore_whenRaceCondition_thenSuccess() throws Exception {
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSemaphore());
Assert.assertEquals(RANGE, uniqueSequences.size());
}
@Test
public void givenSequenceGeneratorUsingMonitor_whenRaceCondition_thenSuccess() throws Exception {
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingMonitor());
Assert.assertEquals(RANGE, uniqueSequences.size());
}
private Set<Integer> getASetOFUniqueSequences(SequenceGenerator generator) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
Set<Integer> uniqueSequences = new HashSet<>();
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < RANGE; i++) {
futures.add(executor.submit(generator::getNextSequence));
}
for (Future<Integer> future : futures) {
uniqueSequences.add(future.get());
}
executor.awaitTermination(15, TimeUnit.SECONDS);
executor.shutdown();
return uniqueSequences;
}
}

View File

@ -1,4 +1,4 @@
package org.baeldung.java.io;
package org.baeldung.writetofile;
import static org.junit.Assert.assertEquals;

View File

@ -0,0 +1,65 @@
<?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.jndi</groupId>
<artifactId>core-java-jndi</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.9.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,60 @@
package com.baeldung.jndi;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jndi.JndiTemplate;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import javax.naming.*;
import javax.sql.DataSource;
import java.util.Enumeration;
import static org.junit.jupiter.api.Assertions.*;
class JndiUnitTest {
private static InitialContext ctx;
private static DriverManagerDataSource ds;
@BeforeAll
static void setUp() throws Exception {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
ds = new DriverManagerDataSource("jdbc:h2:mem:mydb");
builder.activate();
JndiTemplate jndiTemplate = new JndiTemplate();
ctx = (InitialContext) jndiTemplate.getContext();
}
@Test
void givenACompositeName_whenAddingAnElement_thenNameIncludesIt() throws Exception {
Name objectName = new CompositeName("java:comp/env/jdbc");
Enumeration<String> elements = objectName.getAll();
while(elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
objectName.add("example");
assertEquals("env", objectName.get(1));
assertEquals("example", objectName.get(objectName.size() - 1));
}
@Test
void givenADataSource_whenAddingDriver_thenBind() throws Exception {
ds.setDriverClassName("org.h2.Driver");
ctx.bind("java:comp/env/jdbc/datasource", ds);
}
@Test
void givenContext_whenLookupByName_thenValidDataSource() throws Exception {
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
assertNotNull(ds);
assertNotNull(ds.getConnection());
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.jndi.exceptions;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.jndi.JndiTemplate;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.NoInitialContextException;
import static org.junit.jupiter.api.Assertions.assertThrows;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class JndiExceptionsUnitTest {
@Test
@Order(1)
void givenNoContext_whenLookupObject_thenThrowNoInitialContext() {
assertThrows(NoInitialContextException.class, () -> {
JndiTemplate jndiTemplate = new JndiTemplate();
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
ctx.lookup("java:comp/env/jdbc/datasource");
}).printStackTrace();
}
@Test
@Order(2)
void givenEmptyContext_whenLookupNotBounds_thenThrowNameNotFound() {
assertThrows(NameNotFoundException.class, () -> {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.activate();
JndiTemplate jndiTemplate = new JndiTemplate();
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
ctx.lookup("badJndiName");
}).printStackTrace();
}
}

View File

@ -0,0 +1,3 @@
### Relevant Articles
- [Checking if a URL Exists in Java](https://www.baeldung.com/java-check-url-exists)

130
java-jdi/pom.xml Normal file
View File

@ -0,0 +1,130 @@
<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>
<artifactId>java-jdi</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-jdi</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<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>com.sun</groupId>
<artifactId>tools</artifactId>
<version>${tools.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>
<finalName>java-jdi</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.6.1</assertj.version>
<tool.version>1.8</tool.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<tools.version>1.8</tools.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.jdi;
public class JDIExample {
public static void main(String[] args) {
String jpda = "Java Platform Debugger Architecture";
System.out.println("Hi Everyone, Welcome to " + jpda); //add a break point here
String jdi = "Java Debug Interface"; //add a break point here and also stepping in here
String text = "Today, we'll dive into " + jdi;
System.out.println(text);
}
}

View File

@ -0,0 +1,171 @@
package com.baeldung.jdi;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.Bootstrap;
import com.sun.jdi.ClassType;
import com.sun.jdi.IncompatibleThreadStateException;
import com.sun.jdi.LocalVariable;
import com.sun.jdi.Location;
import com.sun.jdi.StackFrame;
import com.sun.jdi.VMDisconnectedException;
import com.sun.jdi.Value;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.connect.LaunchingConnector;
import com.sun.jdi.connect.VMStartException;
import com.sun.jdi.event.BreakpointEvent;
import com.sun.jdi.event.ClassPrepareEvent;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.EventSet;
import com.sun.jdi.event.LocatableEvent;
import com.sun.jdi.event.StepEvent;
import com.sun.jdi.request.BreakpointRequest;
import com.sun.jdi.request.ClassPrepareRequest;
import com.sun.jdi.request.StepRequest;
public class JDIExampleDebugger {
private Class debugClass;
private int[] breakPointLines;
public Class getDebugClass() {
return debugClass;
}
public void setDebugClass(Class debugClass) {
this.debugClass = debugClass;
}
public int[] getBreakPointLines() {
return breakPointLines;
}
public void setBreakPointLines(int[] breakPointLines) {
this.breakPointLines = breakPointLines;
}
/**
* Sets the debug class as the main argument in the connector and launches the VM
* @return VirtualMachine
* @throws IOException
* @throws IllegalConnectorArgumentsException
* @throws VMStartException
*/
public VirtualMachine connectAndLaunchVM() throws IOException, IllegalConnectorArgumentsException, VMStartException {
LaunchingConnector launchingConnector = Bootstrap.virtualMachineManager().defaultConnector();
Map<String, Connector.Argument> arguments = launchingConnector.defaultArguments();
arguments.get("main").setValue(debugClass.getName());
VirtualMachine vm = launchingConnector.launch(arguments);
return vm;
}
/**
* Creates a request to prepare the debug class, add filter as the debug class and enables it
* @param vm
*/
public void enableClassPrepareRequest(VirtualMachine vm) {
ClassPrepareRequest classPrepareRequest = vm.eventRequestManager().createClassPrepareRequest();
classPrepareRequest.addClassFilter(debugClass.getName());
classPrepareRequest.enable();
}
/**
* Sets the break points at the line numbers mentioned in breakPointLines array
* @param vm
* @param event
* @throws AbsentInformationException
*/
public void setBreakPoints(VirtualMachine vm, ClassPrepareEvent event) throws AbsentInformationException {
ClassType classType = (ClassType) event.referenceType();
for(int lineNumber: breakPointLines) {
Location location = classType.locationsOfLine(lineNumber).get(0);
BreakpointRequest bpReq = vm.eventRequestManager().createBreakpointRequest(location);
bpReq.enable();
}
}
/**
* Displays the visible variables
* @param event
* @throws IncompatibleThreadStateException
* @throws AbsentInformationException
*/
public void displayVariables(LocatableEvent event) throws IncompatibleThreadStateException, AbsentInformationException {
StackFrame stackFrame = event.thread().frame(0);
if(stackFrame.location().toString().contains(debugClass.getName())) {
Map<LocalVariable, Value> visibleVariables = stackFrame.getValues(stackFrame.visibleVariables());
System.out.println("Variables at " +stackFrame.location().toString() + " > ");
for (Map.Entry<LocalVariable, Value> entry : visibleVariables.entrySet()) {
System.out.println(entry.getKey().name() + " = " + entry.getValue());
}
}
}
/**
* Enables step request for a break point
* @param vm
* @param event
*/
public void enableStepRequest(VirtualMachine vm, BreakpointEvent event) {
//enable step request for last break point
if(event.location().toString().contains(debugClass.getName()+":"+breakPointLines[breakPointLines.length-1])) {
StepRequest stepRequest = vm.eventRequestManager().createStepRequest(event.thread(), StepRequest.STEP_LINE, StepRequest.STEP_OVER);
stepRequest.enable();
}
}
public static void main(String[] args) throws Exception {
JDIExampleDebugger debuggerInstance = new JDIExampleDebugger();
debuggerInstance.setDebugClass(JDIExample.class);
int[] breakPoints = {6, 9};
debuggerInstance.setBreakPointLines(breakPoints);
VirtualMachine vm = null;
try {
vm = debuggerInstance.connectAndLaunchVM();
debuggerInstance.enableClassPrepareRequest(vm);
EventSet eventSet = null;
while ((eventSet = vm.eventQueue().remove()) != null) {
for (Event event : eventSet) {
if (event instanceof ClassPrepareEvent) {
debuggerInstance.setBreakPoints(vm, (ClassPrepareEvent)event);
}
if (event instanceof BreakpointEvent) {
event.request().disable();
debuggerInstance.displayVariables((BreakpointEvent) event);
debuggerInstance.enableStepRequest(vm, (BreakpointEvent)event);
}
if (event instanceof StepEvent) {
debuggerInstance.displayVariables((StepEvent) event);
}
vm.resume();
}
}
} catch (VMDisconnectedException e) {
System.out.println("Virtual Machine is disconnected.");
} catch (Exception e) {
e.printStackTrace();
}
finally {
InputStreamReader reader = new InputStreamReader(vm.process().getInputStream());
OutputStreamWriter writer = new OutputStreamWriter(System.out);
char[] buf = new char[512];
reader.read(buf);
writer.write(buf);
writer.flush();
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.matrices;
public class HomemadeMatrix {
public static double[][] multiplyMatrices(double[][] firstMatrix, double[][] secondMatrix) {
double[][] result = new double[firstMatrix.length][secondMatrix[0].length];
for (int row = 0; row < result.length; row++) {
for (int col = 0; col < result[row].length; col++) {
result[row][col] = multiplyMatricesCell(firstMatrix, secondMatrix, row, col);
}
}
return result;
}
private static double multiplyMatricesCell(double[][] firstMatrix, double[][] secondMatrix, int row, int col) {
double cell = 0;
for (int i = 0; i < secondMatrix.length; i++) {
cell += firstMatrix[row][i] * secondMatrix[i][col];
}
return cell;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.algorithms.logarithm;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class LogarithmUnitTest {
@Test
public void givenLog10_shouldReturnValidResults() {
assertEquals(Math.log10(100), 2);
assertEquals(Math.log10(1000), 3);
}
@Test
public void givenLogE_shouldReturnValidResults() {
assertEquals(Math.log(Math.E), 1);
assertEquals(Math.log(10), 2.30258, 0.00001);
}
@Test
public void givenCustomLog_shouldReturnValidResults() {
assertEquals(customLog(2, 256), 8);
assertEquals(customLog(10, 100), 2);
}
private static double customLog(double base, double logNumber) {
return Math.log(logNumber) / Math.log(base);
}
}

View File

@ -1,9 +1,84 @@
package com.baeldung.matrices;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.linalg.Algebra;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import org.ejml.simple.SimpleMatrix;
import org.la4j.Matrix;
import org.la4j.matrix.dense.Basic2DMatrix;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
public class MatrixMultiplicationBenchmarking {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
Options opt = new OptionsBuilder()
.include(MatrixMultiplicationBenchmarking.class.getSimpleName())
.mode(Mode.AverageTime)
.forks(2)
.warmupIterations(5)
.measurementIterations(10)
.timeUnit(TimeUnit.MICROSECONDS)
.build();
new Runner(opt).run();
}
}
@Benchmark
public Object homemadeMatrixMultiplication(MatrixProvider matrixProvider) {
return HomemadeMatrix.multiplyMatrices(matrixProvider.getFirstMatrix(), matrixProvider.getSecondMatrix());
}
@Benchmark
public Object ejmlMatrixMultiplication(MatrixProvider matrixProvider) {
SimpleMatrix firstMatrix = new SimpleMatrix(matrixProvider.getFirstMatrix());
SimpleMatrix secondMatrix = new SimpleMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.mult(secondMatrix);
}
@Benchmark
public Object apacheCommonsMatrixMultiplication(MatrixProvider matrixProvider) {
RealMatrix firstMatrix = new Array2DRowRealMatrix(matrixProvider.getFirstMatrix());
RealMatrix secondMatrix = new Array2DRowRealMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.multiply(secondMatrix);
}
@Benchmark
public Object la4jMatrixMultiplication(MatrixProvider matrixProvider) {
Matrix firstMatrix = new Basic2DMatrix(matrixProvider.getFirstMatrix());
Matrix secondMatrix = new Basic2DMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.multiply(secondMatrix);
}
@Benchmark
public Object nd4jMatrixMultiplication(MatrixProvider matrixProvider) {
INDArray firstMatrix = Nd4j.create(matrixProvider.getFirstMatrix());
INDArray secondMatrix = Nd4j.create(matrixProvider.getSecondMatrix());
return firstMatrix.mmul(secondMatrix);
}
@Benchmark
public Object coltMatrixMultiplication(MatrixProvider matrixProvider) {
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
DoubleMatrix2D firstMatrix = doubleFactory2D.make(matrixProvider.getFirstMatrix());
DoubleMatrix2D secondMatrix = doubleFactory2D.make(matrixProvider.getSecondMatrix());
Algebra algebra = new Algebra();
return algebra.mult(firstMatrix, secondMatrix);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.matrices;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class MatrixProvider {
private double[][] firstMatrix;
private double[][] secondMatrix;
public MatrixProvider() {
firstMatrix =
new double[][] {
new double[] {1d, 5d},
new double[] {2d, 3d},
new double[] {1d ,7d}
};
secondMatrix =
new double[][] {
new double[] {1d, 2d, 3d, 7d},
new double[] {5d, 2d, 8d, 1d}
};
}
public double[][] getFirstMatrix() {
return firstMatrix;
}
public double[][] getSecondMatrix() {
return secondMatrix;
}
}

View File

@ -7,15 +7,10 @@ import org.openjdk.jmh.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class RealMatrixUnitTest {
class RealMatrixUnitTest {
@Test
@Benchmark
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
RealMatrix firstMatrix = new Array2DRowRealMatrix(
new double[][] {
new double[] {1d, 5d},
@ -43,5 +38,4 @@ public class RealMatrixUnitTest {
assertThat(actual).isEqualTo(expected);
}
}

View File

@ -8,15 +8,10 @@ import org.openjdk.jmh.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class DoubleMatrix2DUnitTest {
class DoubleMatrix2DUnitTest {
@Test
@Benchmark
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
DoubleMatrix2D firstMatrix = doubleFactory2D.make(
@ -48,4 +43,4 @@ public class DoubleMatrix2DUnitTest {
assertThat(actual).isEqualTo(expected);
}
}
}

View File

@ -6,15 +6,10 @@ import org.openjdk.jmh.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class SimpleMatrixUnitTest {
class SimpleMatrixUnitTest {
@Test
@Benchmark
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
SimpleMatrix firstMatrix = new SimpleMatrix(
new double[][] {
new double[] {1d, 5d},
@ -43,4 +38,4 @@ public class SimpleMatrixUnitTest {
assertThat(actual).matches(m -> m.isIdentical(expected, 0d));
}
}
}

View File

@ -5,15 +5,10 @@ import org.openjdk.jmh.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class HomemadeMatrixUnitTest {
class HomemadeMatrixUnitTest {
@Test
@Benchmark
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
double[][] firstMatrix = {
new double[]{1d, 5d},
new double[]{2d, 3d},
@ -55,4 +50,5 @@ public class HomemadeMatrixUnitTest {
}
return cell;
}
}
}

View File

@ -7,15 +7,10 @@ import org.openjdk.jmh.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class Basic2DMatrixUnitTest {
class Basic2DMatrixUnitTest {
@Test
@Benchmark
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
Matrix firstMatrix = new Basic2DMatrix(
new double[][]{
new double[]{1d, 5d},
@ -44,4 +39,4 @@ public class Basic2DMatrixUnitTest {
assertThat(actual).isEqualTo(expected);
}
}
}

View File

@ -7,14 +7,10 @@ import org.openjdk.jmh.annotations.*;
import static org.assertj.core.api.Assertions.assertThat;
@BenchmarkMode(Mode.AverageTime)
@Fork(value = 2)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
public class INDArrayUnitTest {
class INDArrayUnitTest {
@Test
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
INDArray firstMatrix = Nd4j.create(
new double[][]{
new double[]{1d, 5d},
@ -43,4 +39,4 @@ public class INDArrayUnitTest {
assertThat(actual).isEqualTo(expected);
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.lcm;
import java.math.BigInteger;
public class BigIntegerLCM {
public static BigInteger lcm(BigInteger number1, BigInteger number2) {
BigInteger gcd = number1.gcd(number2);
BigInteger absProduct = number1.multiply(number2).abs();
return absProduct.divide(gcd);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.lcm;
import java.util.Arrays;
public class EuclideanAlgorithm {
public static int gcd(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return number1 + number2;
} else {
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int biggerValue = Math.max(absNumber1, absNumber2);
int smallerValue = Math.min(absNumber1, absNumber2);
return gcd(biggerValue % smallerValue, smallerValue);
}
}
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0)
return 0;
else {
int gcd = gcd(number1, number2);
return Math.abs(number1 * number2) / gcd;
}
}
public static int lcmForArray(int[] numbers) {
int lcm = numbers[0];
for (int i = 1; i <= numbers.length - 1; i++) {
lcm = lcm(lcm, numbers[i]);
}
return lcm;
}
public static int lcmByLambda(int... numbers) {
return Arrays.stream(numbers).reduce(1, (lcmSoFar, currentNumber) -> Math.abs(lcmSoFar * currentNumber) / gcd(lcmSoFar, currentNumber));
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.lcm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PrimeFactorizationAlgorithm {
public static Map<Integer, Integer> getPrimeFactors(int number) {
int absNumber = Math.abs(number);
Map<Integer, Integer> primeFactorsMap = new HashMap<Integer, Integer>();
for (int factor = 2; factor <= absNumber; factor++) {
while (absNumber % factor == 0) {
Integer power = primeFactorsMap.get(factor);
if (power == null) {
power = 0;
}
primeFactorsMap.put(factor, power + 1);
absNumber /= factor;
}
}
return primeFactorsMap;
}
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return 0;
}
Map<Integer, Integer> primeFactorsForNum1 = getPrimeFactors(number1);
Map<Integer, Integer> primeFactorsForNum2 = getPrimeFactors(number2);
Set<Integer> primeFactorsUnionSet = new HashSet<Integer>(primeFactorsForNum1.keySet());
primeFactorsUnionSet.addAll(primeFactorsForNum2.keySet());
int lcm = 1;
for (Integer primeFactor : primeFactorsUnionSet) {
lcm *= Math.pow(primeFactor, Math.max(primeFactorsForNum1.getOrDefault(primeFactor, 0),
primeFactorsForNum2.getOrDefault(primeFactor, 0)));
}
return lcm;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.lcm;
public class SimpleAlgorithm {
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return 0;
}
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int absHigherNumber = Math.max(absNumber1, absNumber2);
int absLowerNumber = Math.min(absNumber1, absNumber2);
int lcm = absHigherNumber;
while (lcm % absLowerNumber != 0) {
lcm += absHigherNumber;
}
return lcm;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
public class BigIntegerLCMUnitTest {
@Test
public void testLCM() {
BigInteger number1 = new BigInteger("12");
BigInteger number2 = new BigInteger("18");
BigInteger expectedLCM = new BigInteger("36");
Assert.assertEquals(expectedLCM, BigIntegerLCM.lcm(number1, number2));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
public class EuclideanAlgorithmUnitTest {
@Test
public void testGCD() {
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
}
@Test
public void testLCM() {
Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18));
}
@Test
public void testLCMForArray() {
Assert.assertEquals(15, EuclideanAlgorithm.lcmForArray(new int[]{3, 5, 15}));
}
@Test
public void testLCMByLambdaForArray() {
Assert.assertEquals(15, EuclideanAlgorithm.lcmByLambda(new int[]{3, 5, 15}));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.baeldung.lcm.PrimeFactorizationAlgorithm.*;
public class PrimeFactorizationAlgorithmUnitTest {
@Test
public void testGetPrimeFactors() {
Map<Integer, Integer> expectedPrimeFactorsMapForTwelve = new HashMap<>();
expectedPrimeFactorsMapForTwelve.put(2, 2);
expectedPrimeFactorsMapForTwelve.put(3, 1);
Map<Integer, Integer> expectedPrimeFactorsMapForEighteen = new HashMap<>();
expectedPrimeFactorsMapForEighteen.put(2, 1);
expectedPrimeFactorsMapForEighteen.put(3, 2);
Assert.assertEquals(expectedPrimeFactorsMapForTwelve, getPrimeFactors(12));
Assert.assertEquals(expectedPrimeFactorsMapForEighteen, getPrimeFactors(18));
}
@Test
public void testLCM() {
Assert.assertEquals(36, PrimeFactorizationAlgorithm.lcm(12, 18));
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import static com.baeldung.lcm.SimpleAlgorithm.*;
public class SimpleAlgorithmUnitTest {
@Test
public void testLCM() {
Assert.assertEquals(36, lcm(12, 18));
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.jhipster5.security;
import com.baeldung.jhipster5.domain.User;
import com.baeldung.jhipster5.security.dto.LoginRequest;
import com.baeldung.jhipster5.security.dto.LoginResponse;
import com.baeldung.jhipster5.service.UserService;
import com.baeldung.jhipster5.service.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
@Component
public class CustomAuthenticationManager implements AuthenticationManager {
private final static Logger LOG = LoggerFactory.getLogger(CustomAuthenticationManager.class);
private final String REMOTE_LOGIN_URL = "https://example.com/login";
private final RestTemplate restTemplate = new RestTemplate();
@Autowired
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setUsername(authentication.getPrincipal().toString());
loginRequest.setPassword(authentication.getCredentials().toString());
try
{
ResponseEntity<LoginResponse> response =
restTemplate.postForEntity(
REMOTE_LOGIN_URL,
loginRequest,
LoginResponse.class);
if(response.getStatusCode().is2xxSuccessful())
{
//
// Need to create a new local user if this is the first time logging in; this
// is required so they can be issued JWTs. We can use this flow to also keep
// our local use entry up to date with data from the remote service if needed
// (for example, if the first and last name might change, this is where we would
// update the local user entry)
//
User user = userService.getUserWithAuthoritiesByLogin(authentication.getPrincipal().toString())
.orElseGet(() -> userService.createUser(createUserDTO(response.getBody(), authentication)));
return createAuthentication(authentication, user);
}
else
{
throw new BadCredentialsException("Invalid username or password");
}
}
catch (Exception e)
{
LOG.warn("Failed to authenticate", e);
throw new AuthenticationServiceException("Failed to login", e);
}
}
/**
* Creates a new authentication with basic roles
* @param auth Contains auth details that will be copied into the new one.
* @param user User object representing who is logging in
* @return Authentication
*/
private Authentication createAuthentication(Authentication auth, User user) {
//
// Honor any roles the user already has set; default is just USER role
// but could be modified after account creation
//
Collection<? extends GrantedAuthority> authorities = user
.getAuthorities()
.stream()
.map(a -> new SimpleGrantedAuthority(a.getName()))
.collect(Collectors.toSet());
UsernamePasswordAuthenticationToken token
= new UsernamePasswordAuthenticationToken(
user.getId(),
auth.getCredentials().toString(),
authorities);
return token;
}
/**
* Creates a new UserDTO with basic info.
* @param loginResponse Response from peloton login API
* @param authentication Contains user login info (namely username and password)
* @return UserDTO
*/
private UserDTO createUserDTO(LoginResponse loginResponse, Authentication authentication) {
UserDTO dto = new UserDTO();
dto.setActivated(true);
dto.setEmail(loginResponse.getEmail());
dto.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
dto.setFirstName(loginResponse.getFirstName());
dto.setLastName(loginResponse.getLastName());
return dto;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.jhipster5.security.dto;
/**
* Simple DTO representing a login request to a remote service.
*/
public class LoginRequest {
private String username;
private String password;
public LoginRequest() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.jhipster5.security.dto;
/**
* Simple DTO representing the response of logging in using a remote service.
*/
public class LoginResponse {
private String username;
private String firstName;
private String lastName;
private String email;
public LoginResponse() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@ -1,8 +1,8 @@
import { Routes } from '@angular/router';
import { activateRoute, passwordRoute, passwordResetFinishRoute, passwordResetInitRoute, registerRoute, settingsRoute } from './';
import { settingsRoute } from './';
const ACCOUNT_ROUTES = [activateRoute, passwordRoute, passwordResetFinishRoute, passwordResetInitRoute, registerRoute, settingsRoute];
const ACCOUNT_ROUTES = [settingsRoute];
export const accountState: Routes = [
{

View File

@ -114,12 +114,6 @@
<span>Settings</span>
</a>
</li>
<li *ngSwitchCase="true">
<a class="dropdown-item" routerLink="password" routerLinkActive="active" (click)="collapseNavbar()">
<fa-icon icon="clock" fixedWidth="true"></fa-icon>
<span>Password</span>
</a>
</li>
<li *ngSwitchCase="true">
<a class="dropdown-item" (click)="logout()" id="logout">
<fa-icon icon="sign-out-alt" fixedWidth="true"></fa-icon>
@ -132,12 +126,6 @@
<span>Sign in</span>
</a>
</li>
<li *ngSwitchCase="false">
<a class="dropdown-item" routerLink="register" routerLinkActive="active" (click)="collapseNavbar()">
<fa-icon icon="user-plus" fixedWidth="true"></fa-icon>
<span>Register</span>
</a>
</li>
</ul>
</li>
</ul>

View File

@ -30,14 +30,6 @@
</div>
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
<p></p>
<div class="alert alert-warning">
<a class="alert-link" (click)="requestResetPassword()">Did you forget your password?</a>
</div>
<div class="alert alert-warning">
<span>You don't have an account yet?</span>
<a class="alert-link" (click)="register()">Register a new account</a>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,54 @@
package com.baeldung.jhipster5.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Collections;
/**
* AuthenticationManager used solely by unit tests.
*/
@Component
@Primary
public class MockAuthenticationManager implements AuthenticationManager
{
private final static Collection<? extends GrantedAuthority> ROLES =
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{
UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());
if(userDetails == null || !passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword()))
{
throw new BadCredentialsException("Invalid username/password");
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
authentication.getPrincipal().toString(),
authentication.getCredentials().toString(),
ROLES);
return token;
}
}

View File

@ -0,0 +1,5 @@
### Relevant articles
- [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml)
- [Guide to JMapper](https://www.baeldung.com/jmapper)
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
- [Intro to Derive4J](https://www.baeldung.com/derive4j)

View File

@ -0,0 +1 @@
log4j.rootLogger=INFO, stdout

55
libraries-data-3/pom.xml Normal file
View File

@ -0,0 +1,55 @@
<?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>
<artifactId>libraries-data-3</artifactId>
<name>libraries-data-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.jmapper-framework</groupId>
<artifactId>jmapper-core</artifactId>
<version>${jmapper.version}</version>
</dependency>
<dependency>
<groupId>com.numericalmethod</groupId>
<artifactId>suanshu</artifactId>
<version>${suanshu.version}</version>
</dependency>
<dependency>
<groupId>org.derive4j</groupId>
<artifactId>derive4j</artifactId>
<version>${derive4j.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>nm-repo</id>
<name>Numerical Method's Maven Repository</name>
<url>http://repo.numericalmethod.com/maven/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<snakeyaml.version>1.21</snakeyaml.version>
<jmapper.version>1.6.0.1</jmapper.version>
<suanshu.version>4.0.0</suanshu.version>
<derive4j.version>1.1.0</derive4j.version>
</properties>
</project>

View File

@ -0,0 +1,10 @@
<jmapper>
<class name="com.baeldung.jmapper.UserDto">
<attribute name="id">
<value name="id"/>
</attribute>
<attribute name="username">
<value name="email"/>
</attribute>
</class>
</jmapper>

View File

@ -0,0 +1,5 @@
<jmapper>
<class name="com.baeldung.jmapper.UserDto1">
<global/>
</class>
</jmapper>

View File

@ -0,0 +1,21 @@
<jmapper>
<class name="com.baeldung.jmapper.relational.User">
<attribute name="id">
<value name="id"/>
<classes>
<class name="com.baeldung.jmapper.relational.UserDto1"/>
<class name="com.baeldung.jmapper.relational.UserDto2"/>
</classes>
</attribute>
<attribute name="email">
<attributes>
<attribute name="username"/>
<attribute name="email"/>
</attributes>
<classes>
<class name="com.baeldung.jmapper.relational.UserDto1"/>
<class name="com.baeldung.jmapper.relational.UserDto2"/>
</classes>
</attribute>
</class>
</jmapper>

View File

@ -0,0 +1,3 @@
firstName: "John"
lastName: "Doe"
age: 20

View File

@ -0,0 +1,7 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- { type: "mobile", number: 123456789}
- { type: "landline", number: 456786868}

View File

@ -0,0 +1,13 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- type: "mobile"
number: 123456789
- type: "landline"
number: 456786868
homeAddress:
line: "Xyz, DEF Street"
city: "City Y"
state: "State Y"
zip: 345657

View File

@ -0,0 +1,6 @@
firstName: "John"
lastName: "Doe"
age: 31
contactDetails:
- !contact { type: "mobile", number: 123456789}
- !contact { type: "landline", number: 456786868}

View File

@ -0,0 +1,4 @@
!!com.baeldung.snakeyaml.Customer
firstName: "John"
lastName: "Doe"
age: 20

View File

@ -0,0 +1,8 @@
---
firstName: "John"
lastName: "Doe"
age: 20
---
firstName: "Jack"
lastName: "Jones"
age: 25

View File

@ -9,7 +9,6 @@
- [Introduction to JCache](http://www.baeldung.com/jcache)
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
- [Guide to JMapper](https://www.baeldung.com/jmapper)
- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch)
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)

View File

@ -141,12 +141,7 @@
<artifactId>hazelcast</artifactId>
<version>${hazelcast.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.jmapper-framework</groupId>
<artifactId>jmapper-core</artifactId>
<version>${jmapper.version}</version>
</dependency>
<!-- crunch project -->
<dependency>
<groupId>org.apache.crunch</groupId>
@ -460,7 +455,6 @@
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
<jmapper.version>1.6.0.1</jmapper.version>
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
<ebean.version>11.22.4</ebean.version>

View File

@ -5,3 +5,7 @@
- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client)
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
- [Integrating Retrofit with RxJava](http://www.baeldung.com/retrofit-rxjava)
- [Introduction to Retrofit](http://www.baeldung.com/retrofit)
- [A Guide to Unirest](http://www.baeldung.com/unirest)
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)

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