Merge branch 'master' of github.com:eugenp/tutorials into master
This commit is contained in:
@@ -74,6 +74,7 @@
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
|
||||
+1
@@ -10,5 +10,6 @@ public class CopyListServiceUnitTest {
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenModifyCopyOfList_thenThrowsException() {
|
||||
List<Integer> copyList = List.copyOf(Arrays.asList(1, 2, 3, 4));
|
||||
copyList.add(4);
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.array.arraystoreexception;
|
||||
|
||||
public class ArrayStoreExampleCE {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//String array[] = new String[5]; //This will lead to compile-time error at line-8 when uncommented
|
||||
//array[0] = 2;
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.array.arraystoreexception;
|
||||
|
||||
public class ArrayStoreExceptionExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
Object array[] = new String[5];
|
||||
array[0] = 2;
|
||||
} catch (ArrayStoreException e) {
|
||||
// handle the exception
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="WARN">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.algorithms.largestpowerof2;
|
||||
|
||||
import org.nd4j.linalg.io.Assert;
|
||||
|
||||
public class LargestPowerOf2 {
|
||||
public long findLargestPowerOf2LessThanTheGivenNumber(long input) {
|
||||
Assert.isTrue(input > 1, "Invalid input");
|
||||
|
||||
long firstPowerOf2 = 1;
|
||||
long nextPowerOf2 = 2;
|
||||
|
||||
while (nextPowerOf2 < input) {
|
||||
firstPowerOf2 = nextPowerOf2;
|
||||
nextPowerOf2 = nextPowerOf2 * 2;
|
||||
}
|
||||
return firstPowerOf2;
|
||||
}
|
||||
|
||||
public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) {
|
||||
Assert.isTrue(input > 1, "Invalid input");
|
||||
|
||||
long temp = input;
|
||||
if (input % 2 == 0) {
|
||||
temp = input - 1;
|
||||
}
|
||||
|
||||
// Find log base 2 of a given number
|
||||
long power = (long) (Math.log(temp) / Math.log(2));
|
||||
long result = (long) Math.pow(2, power);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) {
|
||||
Assert.isTrue(input > 1, "Invalid input");
|
||||
long result = 1;
|
||||
for (long i = input - 1; i > 1; i--) {
|
||||
if ((i & (i - 1)) == 0) {
|
||||
result = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) {
|
||||
Assert.isTrue(input > 1, "Invalid input");
|
||||
long result = 1;
|
||||
long powerOf2;
|
||||
|
||||
for (long i = 0; i < Long.BYTES * 8; i++) {
|
||||
powerOf2 = 1 << i;
|
||||
if (powerOf2 >= input) {
|
||||
break;
|
||||
}
|
||||
result = powerOf2;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.algorithms.largestpowerof2;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
|
||||
@RunWith(Parameterized.class)
|
||||
public class LargestPowerOf2UnitTest {
|
||||
private long input;
|
||||
private long expectedResult;
|
||||
|
||||
public LargestPowerOf2UnitTest(long input, long expectedResult) {
|
||||
this.input = input;
|
||||
this.expectedResult = expectedResult;
|
||||
}
|
||||
|
||||
@Parameterized.Parameters(name = "{index}: verifyLargestPowerOf2LessThanTheGivenNumber({0}) = {1}")
|
||||
public static Collection<Object[]> data() {
|
||||
return Arrays.asList(new Object[][] { { 2, 1 }, { 4, 2 }, { 500, 256 }, { 512, 256 }, { 1050, 1024 } });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumber() {
|
||||
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
|
||||
|
||||
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(input);
|
||||
|
||||
Assert.assertEquals(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberUsingLogBase2() {
|
||||
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
|
||||
|
||||
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(input);
|
||||
|
||||
Assert.assertEquals(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitwiseAnd() {
|
||||
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
|
||||
|
||||
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(input);
|
||||
|
||||
Assert.assertEquals(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInput_verifyLargestPowerOf2LessThanTheGivenNumberBitShiftApproach() {
|
||||
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
|
||||
|
||||
long result = largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(input);
|
||||
|
||||
Assert.assertEquals(expectedResult, result);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenInvalidInput_ShouldThrowException() {
|
||||
LargestPowerOf2 largestPowerOf2 = new LargestPowerOf2();
|
||||
largestPowerOf2.findLargestPowerOf2LessThanTheGivenNumber(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
## Core Kotlin Collections
|
||||
|
||||
This module contains articles about core Kotlin collections.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?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>core-kotlin-collections-2</artifactId>
|
||||
<name>core-kotlin-collections-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.3.30</kotlin.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.baeldung.aggregate
|
||||
|
||||
class AggregateOperations {
|
||||
private val numbers = listOf(1, 15, 3, 8)
|
||||
|
||||
fun countList(): Int {
|
||||
return numbers.count()
|
||||
}
|
||||
|
||||
fun sumList(): Int {
|
||||
return numbers.sum()
|
||||
}
|
||||
|
||||
fun averageList(): Double {
|
||||
return numbers.average()
|
||||
}
|
||||
|
||||
fun maximumInList(): Int? {
|
||||
return numbers.max()
|
||||
}
|
||||
|
||||
fun minimumInList(): Int? {
|
||||
return numbers.min()
|
||||
}
|
||||
|
||||
fun maximumByList(): Int? {
|
||||
return numbers.maxBy { it % 5 }
|
||||
}
|
||||
|
||||
fun minimumByList(): Int? {
|
||||
return numbers.minBy { it % 5 }
|
||||
}
|
||||
|
||||
fun maximumWithList(): String? {
|
||||
val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona")
|
||||
return strings.maxWith(compareBy { it.length % 4 })
|
||||
}
|
||||
|
||||
fun minimumWithList(): String? {
|
||||
val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona")
|
||||
return strings.minWith(compareBy { it.length % 4 })
|
||||
}
|
||||
|
||||
fun sumByList(): Int {
|
||||
return numbers.sumBy { it * 5 }
|
||||
}
|
||||
|
||||
fun sumByDoubleList(): Double {
|
||||
return numbers.sumByDouble { it.toDouble() / 8 }
|
||||
}
|
||||
|
||||
fun foldList(): Int {
|
||||
return numbers.fold(100) { total, it ->
|
||||
println("total = $total, it = $it")
|
||||
total - it
|
||||
} // ((((100 - 1)-15)-3)-8) = 73
|
||||
}
|
||||
|
||||
fun foldRightList(): Int {
|
||||
return numbers.foldRight(100) { it, total ->
|
||||
println("total = $total, it = $it")
|
||||
total - it
|
||||
} // ((((100-8)-3)-15)-1) = 73
|
||||
}
|
||||
|
||||
fun foldIndexedList(): Int {
|
||||
return numbers.foldIndexed(100) { index, total, it ->
|
||||
println("total = $total, it = $it, index = $index")
|
||||
if (index.minus(2) >= 0) total - it else total
|
||||
} // ((100 - 3)-8) = 89
|
||||
}
|
||||
|
||||
fun foldRightIndexedList(): Int {
|
||||
return numbers.foldRightIndexed(100) { index, it, total ->
|
||||
println("total = $total, it = $it, index = $index")
|
||||
if (index.minus(2) >= 0) total - it else total
|
||||
} // ((100 - 8)-3) = 89
|
||||
}
|
||||
|
||||
fun reduceList(): Int {
|
||||
return numbers.reduce { total, it ->
|
||||
println("total = $total, it = $it")
|
||||
total - it
|
||||
} // (((1 - 15)-3)-8) = -25
|
||||
}
|
||||
|
||||
fun reduceRightList(): Int {
|
||||
return numbers.reduceRight() { it, total ->
|
||||
println("total = $total, it = $it")
|
||||
total - it
|
||||
} // ((8-3)-15)-1) = -11
|
||||
}
|
||||
|
||||
fun reduceIndexedList(): Int {
|
||||
return numbers.reduceIndexed { index, total, it ->
|
||||
println("total = $total, it = $it, index = $index")
|
||||
if (index.minus(2) >= 0) total - it else total
|
||||
} // ((1-3)-8) = -10
|
||||
}
|
||||
|
||||
fun reduceRightIndexedList(): Int {
|
||||
return numbers.reduceRightIndexed { index, it, total ->
|
||||
println("total = $total, it = $it, index = $index")
|
||||
if (index.minus(2) >= 0) total - it else total
|
||||
} // ((8-3) = 5
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.baeldung.aggregate
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class AggregateOperationsUnitTest {
|
||||
|
||||
private val classUnderTest: AggregateOperations = AggregateOperations()
|
||||
|
||||
@Test
|
||||
fun whenCountOfList_thenReturnsValue() {
|
||||
assertEquals(4, classUnderTest.countList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSumOfList_thenReturnsTotalValue() {
|
||||
assertEquals(27, classUnderTest.sumList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenAverageOfList_thenReturnsValue() {
|
||||
assertEquals(6.75, classUnderTest.averageList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMaximumOfList_thenReturnsMaximumValue() {
|
||||
assertEquals(15, classUnderTest.maximumInList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMinimumOfList_thenReturnsMinimumValue() {
|
||||
assertEquals(1, classUnderTest.minimumInList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMaxByList_thenReturnsLargestValue() {
|
||||
assertEquals(3, classUnderTest.maximumByList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMinByList_thenReturnsSmallestValue() {
|
||||
assertEquals(15, classUnderTest.minimumByList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMaxWithList_thenReturnsLargestValue(){
|
||||
assertEquals("Kolkata", classUnderTest.maximumWithList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMinWithList_thenReturnsSmallestValue(){
|
||||
assertEquals("Barcelona", classUnderTest.minimumWithList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSumByList_thenReturnsIntegerValue(){
|
||||
assertEquals(135, classUnderTest.sumByList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenSumByDoubleList_thenReturnsDoubleValue(){
|
||||
assertEquals(3.375, classUnderTest.sumByDoubleList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFoldList_thenReturnsValue(){
|
||||
assertEquals(73, classUnderTest.foldList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFoldRightList_thenReturnsValue(){
|
||||
assertEquals(73, classUnderTest.foldRightList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFoldIndexedList_thenReturnsValue(){
|
||||
assertEquals(89, classUnderTest.foldIndexedList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFoldRightIndexedList_thenReturnsValue(){
|
||||
assertEquals(89, classUnderTest.foldRightIndexedList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReduceList_thenReturnsValue(){
|
||||
assertEquals(-25, classUnderTest.reduceList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReduceRightList_thenReturnsValue(){
|
||||
assertEquals(-11, classUnderTest.reduceRightList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReduceIndexedList_thenReturnsValue(){
|
||||
assertEquals(-10, classUnderTest.reduceIndexedList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenReduceRightIndexedList_thenReturnsValue(){
|
||||
assertEquals(5, classUnderTest.reduceRightIndexedList())
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
<module>core-kotlin-advanced</module>
|
||||
<module>core-kotlin-annotations</module>
|
||||
<module>core-kotlin-collections</module>
|
||||
<module>core-kotlin-collections-2</module>
|
||||
<module>core-kotlin-concurrency</module>
|
||||
<module>core-kotlin-date-time</module>
|
||||
<module>core-kotlin-design-patterns</module>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
### Relevant Article:
|
||||
|
||||
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)
|
||||
@@ -6,3 +6,4 @@ This module contains articles about Drools
|
||||
|
||||
- [Introduction to Drools](https://www.baeldung.com/drools)
|
||||
- [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining)
|
||||
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
rootProject.name='gradle-5-articles'
|
||||
include 'java-exec'
|
||||
include 'unused-dependencies'
|
||||
include 'unused-dependencies'
|
||||
include 'source-sets'
|
||||
@@ -0,0 +1 @@
|
||||
/build/
|
||||
@@ -0,0 +1,67 @@
|
||||
|
||||
apply plugin: "eclipse"
|
||||
apply plugin: "java"
|
||||
|
||||
description = "Source Sets example"
|
||||
|
||||
task printSourceSetInformation(){
|
||||
description = "Print source set information"
|
||||
|
||||
doLast{
|
||||
sourceSets.each { srcSet ->
|
||||
println "["+srcSet.name+"]"
|
||||
print "-->Source directories: "+srcSet.allJava.srcDirs+"\n"
|
||||
print "-->Output directories: "+srcSet.output.classesDirs.files+"\n"
|
||||
print "-->Compile classpath:\n"
|
||||
srcSet.compileClasspath.files.each {
|
||||
print " "+it.path+"\n"
|
||||
}
|
||||
println ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets{
|
||||
itest {
|
||||
compileClasspath += sourceSets.main.output
|
||||
runtimeClasspath += sourceSets.main.output
|
||||
java {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
testLogging {
|
||||
events "passed","skipped", "failed"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation('org.apache.httpcomponents:httpclient:4.5.12')
|
||||
testImplementation('junit:junit:4.12')
|
||||
itestImplementation('com.google.guava:guava:29.0-jre')
|
||||
}
|
||||
|
||||
task itest(type: Test) {
|
||||
description = "Run integration tests"
|
||||
group = "verification"
|
||||
testClassesDirs = sourceSets.itest.output.classesDirs
|
||||
classpath = sourceSets.itest.runtimeClasspath
|
||||
}
|
||||
|
||||
itest {
|
||||
testLogging {
|
||||
events "passed","skipped", "failed"
|
||||
}
|
||||
}
|
||||
|
||||
configurations {
|
||||
itestImplementation.extendsFrom(testImplementation)
|
||||
itestRuntimeOnly.extendsFrom(testRuntimeOnly)
|
||||
}
|
||||
|
||||
eclipse {
|
||||
classpath {
|
||||
plusConfigurations+=[configurations.itestCompileClasspath]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.itest;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.main.SourceSetsObject;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
public class SourceSetsItest {
|
||||
|
||||
@Test
|
||||
public void givenImmutableList_whenRun_ThenSuccess() {
|
||||
|
||||
SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum");
|
||||
List<String> someStrings = ImmutableList.of("Baeldung", "is", "cool");
|
||||
|
||||
assertThat(underTest.getUser(), is("lorem"));
|
||||
assertThat(underTest.getPassword(), is("ipsum"));
|
||||
assertThat(someStrings.size(), is(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.main;
|
||||
|
||||
public class SourceSetsMain {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hell..oh...world!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.main;
|
||||
|
||||
public class SourceSetsObject {
|
||||
|
||||
private final String user;
|
||||
private final String password;
|
||||
|
||||
public SourceSetsObject(String user, String password) {
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.main.SourceSetsObject;
|
||||
|
||||
public class SourceSetsTest {
|
||||
|
||||
@Test
|
||||
public void whenRun_ThenSuccess() {
|
||||
|
||||
SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum");
|
||||
|
||||
assertThat(underTest.getUser(), is("lorem"));
|
||||
assertThat(underTest.getPassword(), is("ipsum"));
|
||||
}
|
||||
}
|
||||
@@ -237,6 +237,26 @@
|
||||
<build>
|
||||
<defaultGoal>spring-boot:run</defaultGoal>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>properties-maven-plugin</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>set-system-properties</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<properties>
|
||||
<property>
|
||||
<name>org.slf4j.simpleLogger.log.com.github.eirslett</name>
|
||||
<value>error</value>
|
||||
</property>
|
||||
</properties>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<!-- Jhipster project is autogenerated and upgrading it will need a newly generated project.
|
||||
Also, we already have jhipster-5 which has new version of boot-2. So, this project should be left as a legacy version. -->
|
||||
<artifactId>parent-boot-1</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
@@ -14,29 +14,24 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.security.oauth</groupId>
|
||||
<artifactId>spring-security-oauth2</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.scribejava</groupId>
|
||||
<artifactId>scribejava-apis</artifactId>
|
||||
<version>${scribejava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.crypto.tink</groupId>
|
||||
<artifactId>tink</artifactId>
|
||||
@@ -72,6 +67,16 @@
|
||||
<artifactId>jasypt</artifactId>
|
||||
<version>${jasypt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jcraft</groupId>
|
||||
<artifactId>jsch</artifactId>
|
||||
<version>${jsch.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.sshd</groupId>
|
||||
<artifactId>sshd-core</artifactId>
|
||||
<version>${apache-mina.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -81,6 +86,8 @@
|
||||
<cryptacular.version>1.2.2</cryptacular.version>
|
||||
<jasypt.version>1.9.2</jasypt.version>
|
||||
<bouncycastle.version>1.58</bouncycastle.version>
|
||||
<jsch.version>0.1.55</jsch.version>
|
||||
<apache-mina.version>2.5.1</apache-mina.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.ssh.apachesshd;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.EnumSet;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.sshd.client.SshClient;
|
||||
import org.apache.sshd.client.channel.ClientChannel;
|
||||
import org.apache.sshd.client.channel.ClientChannelEvent;
|
||||
import org.apache.sshd.client.session.ClientSession;
|
||||
import org.apache.sshd.common.channel.Channel;
|
||||
|
||||
public class SshdDemo {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String username = "demo";
|
||||
String password = "password";
|
||||
String host = "test.rebex.net";
|
||||
int port = 22;
|
||||
long defaultTimeoutSeconds = 10l;
|
||||
String command = "ls\n";
|
||||
|
||||
listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command);
|
||||
}
|
||||
|
||||
public static String listFolderStructure(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) throws Exception {
|
||||
SshClient client = SshClient.setUpDefaultClient();
|
||||
client.start();
|
||||
try (ClientSession session = client.connect(username, host, port)
|
||||
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS)
|
||||
.getSession()) {
|
||||
session.addPasswordIdentity(password);
|
||||
session.auth()
|
||||
.verify(5L, TimeUnit.SECONDS);
|
||||
try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream();
|
||||
ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
|
||||
channel.setOut(responseStream);
|
||||
channel.setErr(errorResponseStream);
|
||||
try {
|
||||
channel.open()
|
||||
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS);
|
||||
try (OutputStream pipedIn = channel.getInvertedIn()) {
|
||||
pipedIn.write(command.getBytes());
|
||||
pipedIn.flush();
|
||||
}
|
||||
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));
|
||||
String errorString = new String(errorResponseStream.toByteArray());
|
||||
if(!errorString.isEmpty()) {
|
||||
throw new Exception(errorString);
|
||||
}
|
||||
String responseString = new String(responseStream.toByteArray());
|
||||
return responseString;
|
||||
} finally {
|
||||
channel.close(false);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.ssh.jsch;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
import com.jcraft.jsch.ChannelExec;
|
||||
import com.jcraft.jsch.JSch;
|
||||
import com.jcraft.jsch.Session;
|
||||
|
||||
public class JschDemo {
|
||||
|
||||
public static void main(String args[]) throws Exception {
|
||||
String username = "demo";
|
||||
String password = "password";
|
||||
String host = "test.rebex.net";
|
||||
int port = 22;
|
||||
String command = "ls";
|
||||
listFolderStructure(username, password, host, port, command);
|
||||
}
|
||||
|
||||
public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception {
|
||||
Session session = null;
|
||||
ChannelExec channel = null;
|
||||
String response = null;
|
||||
try {
|
||||
session = new JSch().getSession(username, host, port);
|
||||
session.setPassword(password);
|
||||
session.setConfig("StrictHostKeyChecking", "no");
|
||||
session.connect();
|
||||
channel = (ChannelExec) session.openChannel("exec");
|
||||
channel.setCommand(command);
|
||||
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream();
|
||||
channel.setOutputStream(responseStream);
|
||||
channel.setErrStream(errorResponseStream);
|
||||
channel.connect();
|
||||
while (channel.isConnected()) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
String errorResponse = new String(errorResponseStream.toByteArray());
|
||||
response = new String(responseStream.toByteArray());
|
||||
if(!errorResponse.isEmpty()) {
|
||||
throw new Exception(errorResponse);
|
||||
}
|
||||
} finally {
|
||||
if (session != null)
|
||||
session.disconnect();
|
||||
if (channel != null)
|
||||
channel.disconnect();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.ssh;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.ssh.apachesshd.SshdDemo;
|
||||
|
||||
public class ApacheMinaSshdLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception {
|
||||
String username = "demo";
|
||||
String password = "password";
|
||||
String host = "test.rebex.net";
|
||||
int port = 22;
|
||||
long defaultTimeoutSeconds = 10l;
|
||||
String command = "ls\n";
|
||||
String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command);
|
||||
|
||||
assertNotNull(responseString);
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception {
|
||||
String username = "invalidUsername";
|
||||
String password = "password";
|
||||
String host = "test.rebex.net";
|
||||
int port = 22;
|
||||
long defaultTimeoutSeconds = 10l;
|
||||
String command = "ls\n";
|
||||
String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command);
|
||||
|
||||
assertNull(responseString);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.ssh;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.ssh.jsch.JschDemo;
|
||||
|
||||
public class JSchLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception {
|
||||
String username = "demo";
|
||||
String password = "password";
|
||||
String host = "test.rebex.net";
|
||||
int port = 22;
|
||||
String command = "ls";
|
||||
String responseString = JschDemo.listFolderStructure(username, password, host, port, command);
|
||||
|
||||
assertNotNull(responseString);
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception {
|
||||
String username = "invalidUsername";
|
||||
String password = "password";
|
||||
String host = "test.rebex.net";
|
||||
int port = 22;
|
||||
String command = "ls";
|
||||
String responseString = JschDemo.listFolderStructure(username, password, host, port, command);
|
||||
|
||||
assertNull(responseString);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
### Relevant Articles:
|
||||
- TBD
|
||||
- [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback)
|
||||
- [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j)
|
||||
- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel)
|
||||
|
||||
### References
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user