Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -72,6 +72,13 @@ Building a single module
|
||||
To build a specific module, run the command: `mvn clean install` in the module directory.
|
||||
|
||||
|
||||
Building modules from the root of the repository
|
||||
====================
|
||||
To build specific modules from the root of the repository, run the command: `mvn clean install --pl asm,atomikos -Pdefault-first` in the root directory.
|
||||
|
||||
Here `asm` and `atomikos` are the modules that we want to build and `default-first` is the maven profile in which these modules are present.
|
||||
|
||||
|
||||
Running a Spring Boot module
|
||||
====================
|
||||
To run a Spring Boot module, run the command: `mvn spring-boot:run` in the module directory.
|
||||
|
||||
+1
-1
@@ -20,4 +20,4 @@ Two scripts are included to easily start middleware using Docker matching the pr
|
||||
- [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates)
|
||||
- [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates)
|
||||
- [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching)
|
||||
- [Persisting the Query Model](https://www.baeldung.com/persisting-the-query-model)
|
||||
- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model)
|
||||
|
||||
@@ -11,4 +11,5 @@ This module contains articles about Java 8 core features
|
||||
- [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization)
|
||||
- [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Monads in Java](https://www.baeldung.com/java-monads)
|
||||
- [[More -->]](/core-java-modules/core-java-8-2)
|
||||
|
||||
@@ -9,3 +9,6 @@ This module contains articles about the Java ArrayList collection
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
|
||||
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)
|
||||
- [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search)
|
||||
- [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple)
|
||||
- [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
## Core Java Collections List (Part 5)
|
||||
|
||||
This module contains articles about the Java List collection
|
||||
|
||||
### Relevant Articles:
|
||||
@@ -0,0 +1,35 @@
|
||||
<?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-java-collections-list-5</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-list-5</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>${commons-lang.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons-lang.version>2.2</commons-lang.version>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ListUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenAddNewFruit_thenFruitIsAdded(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
assertEquals("Unexpected number of fruits in the list, should have been 0", 0, fruits.size());
|
||||
|
||||
fruits.add("Apple");
|
||||
assertEquals("Unexpected number of fruits in the list, should have been 1", 1, fruits.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenContainsFruit_thenFruitIsInTheList(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple");
|
||||
assertTrue("Apple should be in the fruit list", fruits.contains("Apple"));
|
||||
assertFalse("Banana should not be in the fruit list", fruits.contains("Banana"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnEmptyFruitList_whenEmptyCheck_thenListIsEmpty(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
assertTrue("Fruit list should be empty", fruits.isEmpty());
|
||||
|
||||
fruits.add("Apple");
|
||||
assertFalse("Fruit list should not be empty", fruits.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenIterateOverIt_thenFruitsAreInOrder(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple"); // fruit at index 0
|
||||
fruits.add("Orange");// fruit at index 1
|
||||
fruits.add("Banana");// fruit at index 2
|
||||
int index = 0;
|
||||
for (Iterator<String> it = fruits.listIterator(); it.hasNext(); ) {
|
||||
String fruit = it.next();
|
||||
assertEquals("Fruits should be in order", fruits.get(index++), fruit);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenRemoveFruit_thenFruitIsRemoved(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple");
|
||||
fruits.add("Orange");
|
||||
assertEquals("Unexpected number of fruits in the list, should have been 2", 2, fruits.size());
|
||||
|
||||
fruits.remove("Apple");
|
||||
assertEquals("Unexpected number of fruits in the list, should have been 1", 1, fruits.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenSetFruit_thenFruitIsUpdated(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple");
|
||||
fruits.add("Orange");
|
||||
|
||||
fruits.set(0, "Banana");
|
||||
assertEquals("Fruit at index 0 should be Banana", "Banana", fruits.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenSort_thenFruitsAreSorted(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple");
|
||||
fruits.add("Orange");
|
||||
fruits.add("Banana");
|
||||
|
||||
fruits.sort(Comparator.naturalOrder());
|
||||
|
||||
assertEquals("Fruit at index 0 should be Apple", "Apple", fruits.get(0));
|
||||
assertEquals("Fruit at index 1 should be Banana", "Banana", fruits.get(1));
|
||||
assertEquals("Fruit at index 2 should be Orange", "Orange", fruits.get(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenSublist_thenWeGetASublist(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple");
|
||||
fruits.add("Orange");
|
||||
fruits.add("Banana");
|
||||
|
||||
List<String> fruitsSublist = fruits.subList(0, 2);
|
||||
assertEquals("Unexpected number of fruits in the sublist, should have been 2", 2, fruitsSublist.size());
|
||||
|
||||
assertEquals("Fruit at index 0 should be Apple", "Apple", fruitsSublist.get(0));
|
||||
assertEquals("Fruit at index 1 should be Orange", "Orange", fruitsSublist.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFruitList_whenToArray_thenWeGetAnArray(){
|
||||
List<String> fruits = new ArrayList<>();
|
||||
|
||||
fruits.add("Apple");
|
||||
fruits.add("Orange");
|
||||
fruits.add("Banana");
|
||||
|
||||
String[] fruitsArray = fruits.toArray(new String[0]);
|
||||
assertEquals("Unexpected number of fruits in the array, should have been 3", 3, fruitsArray.length);
|
||||
|
||||
assertEquals("Fruit at index 0 should be Apple", "Apple", fruitsArray[0]);
|
||||
assertEquals("Fruit at index 1 should be Orange", "Orange", fruitsArray[1]);
|
||||
assertEquals("Fruit at index 2 should be Banana", "Banana", fruitsArray[2]);
|
||||
}
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.exception.noenumconst;
|
||||
|
||||
public enum Priority {
|
||||
|
||||
HIGH("High"), MEDIUM("Medium"), LOW("Low");
|
||||
|
||||
private String name;
|
||||
|
||||
Priority(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.exception.noenumconst;
|
||||
|
||||
public class PriorityUtils {
|
||||
|
||||
public static Priority getByName(String name) {
|
||||
return Priority.valueOf(name);
|
||||
}
|
||||
|
||||
public static Priority getByUpperCaseName(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Priority.valueOf(name.toUpperCase());
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(getByName("Low"));
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.exception.noenumconst;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PriorityUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
void givenCustomName_whenUsingGetByName_thenThrowIllegalArgumentException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> PriorityUtils.getByName("Low"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCustomName_whenUsingGetByUpperCaseName_thenReturnEnumConstant() {
|
||||
assertEquals(Priority.HIGH, PriorityUtils.getByUpperCaseName("High"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInvalidCustomName_whenUsingGetByUpperCaseName_thenThrowIllegalArgumentException() {
|
||||
assertThrows(IllegalArgumentException.class, () -> PriorityUtils.getByUpperCaseName("invalid"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenEmptyName_whenUsingGetByUpperCaseName_thenReturnNull() {
|
||||
assertNull(PriorityUtils.getByUpperCaseName(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNull_whenUsingGetByUpperCaseName_thenReturnNull() {
|
||||
assertNull(PriorityUtils.getByUpperCaseName(null));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,4 +5,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
|
||||
### Relevant Articles:
|
||||
|
||||
- [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource)
|
||||
- [Compiling and Executing Code From a String in Java](https://www.baeldung.com/java-string-compile-execute-code)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm-2)
|
||||
|
||||
+30
-22
@@ -2,68 +2,76 @@ package com.baeldung.convertnumberbases;
|
||||
|
||||
public class ConvertNumberBases {
|
||||
|
||||
public static String convertNumberToNewBase(String number, int base, int newBase){
|
||||
public static String convertNumberToNewBase(String number, int base, int newBase) {
|
||||
return Integer.toString(Integer.parseInt(number, base), newBase);
|
||||
}
|
||||
|
||||
public static String convertNumberToNewBaseCustom(String num, int base, int newBase) {
|
||||
int decimalNumber = convertFromAnyBaseToDecimal(num, base);
|
||||
return convertFromDecimalToBaseX(decimalNumber, newBase);
|
||||
String targetBase = "";
|
||||
try {
|
||||
targetBase = convertFromDecimalToBaseX(decimalNumber, newBase);
|
||||
} catch (IllegalArgumentException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return targetBase;
|
||||
}
|
||||
|
||||
public static String convertFromDecimalToBaseX(int num, int newBase) {
|
||||
public static String convertFromDecimalToBaseX(int num, int newBase) throws IllegalArgumentException {
|
||||
if ((newBase < 2 || newBase > 10) && newBase != 16) {
|
||||
throw new IllegalArgumentException("New base must be from 2 - 10 or 16");
|
||||
}
|
||||
|
||||
String result = "";
|
||||
int remainder;
|
||||
while (num > 0) {
|
||||
remainder = num % newBase;
|
||||
if (newBase == 16) {
|
||||
if (remainder == 10)
|
||||
if (remainder == 10) {
|
||||
result += 'A';
|
||||
else if (remainder == 11)
|
||||
} else if (remainder == 11) {
|
||||
result += 'B';
|
||||
else if (remainder == 12)
|
||||
} else if (remainder == 12) {
|
||||
result += 'C';
|
||||
else if (remainder == 13)
|
||||
} else if (remainder == 13) {
|
||||
result += 'D';
|
||||
else if (remainder == 14)
|
||||
} else if (remainder == 14) {
|
||||
result += 'E';
|
||||
else if (remainder == 15)
|
||||
} else if (remainder == 15) {
|
||||
result += 'F';
|
||||
else
|
||||
} else {
|
||||
result += remainder;
|
||||
} else
|
||||
}
|
||||
} else {
|
||||
result += remainder;
|
||||
|
||||
}
|
||||
num /= newBase;
|
||||
}
|
||||
return new StringBuffer(result).reverse().toString();
|
||||
}
|
||||
|
||||
public static int convertFromAnyBaseToDecimal(String num, int base) {
|
||||
|
||||
if (base < 2 || (base > 10 && base != 16))
|
||||
if (base < 2 || (base > 10 && base != 16)) {
|
||||
return -1;
|
||||
|
||||
}
|
||||
int val = 0;
|
||||
int power = 1;
|
||||
|
||||
for (int i = num.length() - 1; i >= 0; i--) {
|
||||
int digit = charToDecimal(num.charAt(i));
|
||||
|
||||
if (digit < 0 || digit >= base)
|
||||
if (digit < 0 || digit >= base) {
|
||||
return -1;
|
||||
|
||||
}
|
||||
val += digit * power;
|
||||
power = power * base;
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
public static int charToDecimal(char c) {
|
||||
if (c >= '0' && c <= '9')
|
||||
if (c >= '0' && c <= '9') {
|
||||
return (int) c - '0';
|
||||
else
|
||||
} else {
|
||||
return (int) c - 'A' + 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.convertnumberbases;
|
||||
|
||||
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertFromDecimalToBaseX;
|
||||
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBase;
|
||||
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBaseCustom;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -17,4 +18,15 @@ class ConvertNumberBasesUnitTest {
|
||||
assertEquals(convertNumberToNewBaseCustom("11001000", 2, 8), "310");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInputIsOutOfRange_thenIllegalArgumentExceptionIsThrown() {
|
||||
Exception exception = assertThrows(IllegalArgumentException.class, ()-> {
|
||||
convertFromDecimalToBaseX(100, 12);
|
||||
});
|
||||
String expectedMessage = "New base must be from 2 - 10 or 16";
|
||||
String actualMessage = exception.getMessage();
|
||||
|
||||
assertTrue(actualMessage.contains(expectedMessage));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,3 +6,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
|
||||
- [Object-Oriented-Programming Concepts in Java](https://www.baeldung.com/java-oop)
|
||||
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
|
||||
- [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
|
||||
- [Check If All the Variables of an Object Are Null](https://www.baeldung.com/java-check-all-variables-object-null)
|
||||
|
||||
@@ -5,3 +5,4 @@
|
||||
- [Filter Java Stream to 1 and Only 1 Element](https://www.baeldung.com/java-filter-stream-unique-element)
|
||||
- [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition)
|
||||
- [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams)
|
||||
- [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing)
|
||||
|
||||
@@ -9,3 +9,4 @@
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
|
||||
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
|
||||
|
||||
@@ -112,6 +112,18 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||
<artifactId>httpclient5-fluent</artifactId>
|
||||
<version>${httpclient5-fluent.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
@@ -308,6 +320,7 @@
|
||||
<!-- http client & core 5 -->
|
||||
<httpcore5.version>5.2</httpcore5.version>
|
||||
<httpclient5.version>5.2</httpclient5.version>
|
||||
<httpclient5-fluent.version>5.2</httpclient5-fluent.version>
|
||||
<!-- maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
||||
+110
-73
@@ -1,74 +1,88 @@
|
||||
package com.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.fluent.Form;
|
||||
import org.apache.http.client.fluent.Request;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.http.impl.auth.BasicScheme;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.apache.hc.client5.http.auth.AuthScope;
|
||||
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.hc.client5.http.fluent.Form;
|
||||
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.HttpResponse;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.NameValuePair;
|
||||
import org.apache.hc.client5.http.fluent.Request;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import com.baeldung.handler.CustomHttpClientResponseHandler;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-rest to be running
|
||||
*/
|
||||
public class HttpClientPostingLiveTest {
|
||||
class HttpClientPostingLiveTest {
|
||||
private static final String SAMPLE_URL = "http://www.example.com";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||
private static final String DEFAULT_USER = "test";
|
||||
private static final String DEFAULT_PASS = "test";
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final List<NameValuePair> params = new ArrayList<NameValuePair>();
|
||||
params.add(new BasicNameValuePair("username", DEFAULT_USER));
|
||||
params.add(new BasicNameValuePair("password", DEFAULT_PASS));
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(params));
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
try (CloseableHttpClient client = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(httpPost, new CustomHttpClientResponseHandler())) {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException {
|
||||
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
|
||||
httpPost.setEntity(new StringEntity("test post"));
|
||||
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
||||
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
final UsernamePasswordCredentials credentials =
|
||||
new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray());
|
||||
|
||||
credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials);
|
||||
|
||||
try (CloseableHttpClient client = HttpClients.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider)
|
||||
.build();
|
||||
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(httpPost, new CustomHttpClientResponseHandler())) {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
@@ -77,68 +91,91 @@ public class HttpClientPostingLiveTest {
|
||||
httpPost.setHeader("Accept", "application/json");
|
||||
httpPost.setHeader("Content-type", "application/json");
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
try (CloseableHttpClient client = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(httpPost, new CustomHttpClientResponseHandler())) {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
|
||||
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
|
||||
void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
|
||||
Request request = Request.post(SAMPLE_URL)
|
||||
.bodyForm(Form.form()
|
||||
.add("username", DEFAULT_USER)
|
||||
.add("password", DEFAULT_PASS)
|
||||
.build());
|
||||
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
HttpResponse response = request.execute()
|
||||
.returnResponse();
|
||||
assertThat(response.getCode(), equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addTextBody("username", DEFAULT_USER);
|
||||
builder.addTextBody("password", DEFAULT_PASS);
|
||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
builder.addBinaryBody(
|
||||
"file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
|
||||
final HttpEntity multipart = builder.build();
|
||||
httpPost.setEntity(multipart);
|
||||
|
||||
try (CloseableHttpClient client = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(httpPost, new CustomHttpClientResponseHandler())) {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addBinaryBody(
|
||||
"file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
httpPost.setEntity(multipart);
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
try (CloseableHttpClient client = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(httpPost, new CustomHttpClientResponseHandler())) {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
builder.addBinaryBody(
|
||||
"file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
httpPost.setEntity(multipart);
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
|
||||
final ProgressEntityWrapper.ProgressListener pListener =
|
||||
percentage -> assertFalse(Float.compare(percentage, 100) > 0);
|
||||
|
||||
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
try (CloseableHttpClient client = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = (CloseableHttpResponse) client
|
||||
.execute(httpPost, new CustomHttpClientResponseHandler())) {
|
||||
|
||||
final int statusCode = response.getCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,8 +4,8 @@ import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.entity.HttpEntityWrapper;
|
||||
import org.apache.hc.core5.http.HttpEntity;
|
||||
import org.apache.hc.core5.http.io.entity.HttpEntityWrapper;
|
||||
|
||||
public class ProgressEntityWrapper extends HttpEntityWrapper {
|
||||
private final ProgressListener listener;
|
||||
|
||||
@@ -8,3 +8,4 @@ This module contains articles about Jackson annotations.
|
||||
- [Jackson – Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
|
||||
- [Jackson JSON Views](https://www.baeldung.com/jackson-json-view-annotation)
|
||||
- [Deduction-Based Polymorphism in Jackson 2.12](https://www.baeldung.com/jackson-deduction-based-polymorphism)
|
||||
- [@JsonIgnore vs @Transient](https://www.baeldung.com/java-jsonignore-vs-transient)
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
- [Trigger Another Job from a Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-trigger-new-job)
|
||||
- [Fixing the “No Such DSL method” Error in Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-no-such-dsl-method-error)
|
||||
- [Jenkins Pipeline – Change to Another Folder](https://www.baeldung.com/ops/jenkins-pipeline-change-to-another-folder)
|
||||
- [How to Stop a Zombie Job on Jenkins Without Restarting the Server?](https://www.baeldung.com/ops/stop-zombie-job-on-jenkins-without-restarting-the-server)
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
pipeline {
|
||||
agent any
|
||||
stages {
|
||||
stage('tryCatch') {
|
||||
steps {
|
||||
script {
|
||||
try {
|
||||
sh 'test_script.sh'
|
||||
} catch (e) {
|
||||
echo "An error occurred: ${e}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -54,4 +54,4 @@ Enjoy it :)
|
||||
- [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/ops/jenkins-and-jmeter)
|
||||
- [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file)
|
||||
- [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth)
|
||||
- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time/)
|
||||
- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
## Relevant Articles
|
||||
- [Lightweight Logging With tinylog 2](https://www.baeldung.com/java-logging-tinylog-guide)
|
||||
@@ -2,4 +2,5 @@
|
||||
|
||||
This module contains articles about RestExpress.
|
||||
|
||||
### Relevant articles
|
||||
### Relevant articles
|
||||
- [RESTful Microservices With RestExpress](https://www.baeldung.com/java-restexpress-guide)
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
- [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway)
|
||||
- [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks)
|
||||
- [Rolling Back Migrations with Flyway](https://www.baeldung.com/flyway-roll-back)
|
||||
- [Flyway Out of Order Migrations](https://www.baeldung.com/flyway-migrations)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.examples.scylladb</groupId>
|
||||
<artifactId>scylladb</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>scylladb</name>
|
||||
<description>Sample ScyllaDB Project</description>
|
||||
<properties>
|
||||
<testcontainers.version>1.17.6</testcontainers.version>
|
||||
</properties>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.scylladb</groupId>
|
||||
<artifactId>java-driver-core</artifactId>
|
||||
<version>4.14.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.scylladb</groupId>
|
||||
<artifactId>java-driver-query-builder</artifactId>
|
||||
<version>4.14.1.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers-bom</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.scylladb;
|
||||
|
||||
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.insertInto;
|
||||
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.literal;
|
||||
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.selectFrom;
|
||||
import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.createKeyspace;
|
||||
import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.createTable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.scylladb.model.User;
|
||||
import com.datastax.oss.driver.api.core.CqlSession;
|
||||
import com.datastax.oss.driver.api.core.cql.ResultSet;
|
||||
import com.datastax.oss.driver.api.core.cql.Row;
|
||||
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
|
||||
import com.datastax.oss.driver.api.core.type.DataTypes;
|
||||
import com.datastax.oss.driver.api.querybuilder.insert.InsertInto;
|
||||
import com.datastax.oss.driver.api.querybuilder.schema.CreateKeyspaceStart;
|
||||
import com.datastax.oss.driver.api.querybuilder.schema.CreateTableStart;
|
||||
import com.datastax.oss.driver.api.querybuilder.select.Select;
|
||||
|
||||
public class ScylladbApplication {
|
||||
|
||||
private String keySpaceName;
|
||||
private String tableName;
|
||||
|
||||
public ScylladbApplication(String keySpaceName, String tableName) {
|
||||
this.keySpaceName = keySpaceName;
|
||||
this.tableName = tableName;
|
||||
CreateKeyspaceStart createKeyspace = createKeyspace(keySpaceName);
|
||||
SimpleStatement keypaceStatement = createKeyspace.ifNotExists()
|
||||
.withSimpleStrategy(3)
|
||||
.build();
|
||||
|
||||
CreateTableStart createTable = createTable(keySpaceName, tableName);
|
||||
SimpleStatement tableStatement = createTable.ifNotExists()
|
||||
.withPartitionKey("id", DataTypes.BIGINT)
|
||||
.withColumn("name", DataTypes.TEXT)
|
||||
.build();
|
||||
|
||||
try (CqlSession session = CqlSession.builder().build()) {
|
||||
ResultSet rs = session.execute(keypaceStatement);
|
||||
if (null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty()) {
|
||||
rs = session.execute(tableStatement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> getAllUserNames() {
|
||||
List<String> userNames = new ArrayList<>();
|
||||
try (CqlSession session = CqlSession.builder().build()) {
|
||||
String query = String.format("select * from %s.%s",keySpaceName,tableName);
|
||||
ResultSet rs = session.execute(query);
|
||||
for (Row r : rs.all())
|
||||
userNames.add(r.getString("name"));
|
||||
}
|
||||
return userNames;
|
||||
}
|
||||
|
||||
public List<User> getUsersByUserName(String userName) {
|
||||
List<User> userList = new ArrayList<>();
|
||||
try (CqlSession session = CqlSession.builder().build()) {
|
||||
Select query = selectFrom(keySpaceName, tableName).all()
|
||||
.whereColumn("name")
|
||||
.isEqualTo(literal(userName))
|
||||
.allowFiltering();
|
||||
SimpleStatement statement = query.build();
|
||||
ResultSet rs = session.execute(statement);
|
||||
for (Row r : rs)
|
||||
userList.add(new User(r.getLong("id"), r.getString("name")));
|
||||
}
|
||||
return userList;
|
||||
}
|
||||
|
||||
public boolean addNewUser(User user) {
|
||||
boolean response = false;
|
||||
try (CqlSession session = CqlSession.builder().build()) {
|
||||
InsertInto insert = insertInto(keySpaceName, tableName);
|
||||
SimpleStatement statement = insert.value("id", literal(user.getId()))
|
||||
.value("name", literal(user.getName()))
|
||||
.build();
|
||||
ResultSet rs = session.execute(statement);
|
||||
response = null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.scylladb.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class User {
|
||||
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
datastax-java-driver:
|
||||
basic:
|
||||
contact-points: 127.0.0.1:9042
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user