Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.algorithms.linkedlist;
|
||||
|
||||
public class LinkedListReversal {
|
||||
|
||||
ListNode reverseList(ListNode head) {
|
||||
ListNode previous = null;
|
||||
ListNode current = head;
|
||||
while (current != null) {
|
||||
ListNode nextElement = current.getNext();
|
||||
current.setNext(previous);
|
||||
previous = current;
|
||||
current = nextElement;
|
||||
}
|
||||
return previous;
|
||||
}
|
||||
|
||||
ListNode reverseListRecursive(ListNode head) {
|
||||
if (head == null) {
|
||||
return null;
|
||||
}
|
||||
if (head.getNext() == null) {
|
||||
return head;
|
||||
}
|
||||
ListNode node = reverseListRecursive(head.getNext());
|
||||
head.getNext().setNext(head);
|
||||
head.setNext(null);
|
||||
return node;
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.algorithms.linkedlist;
|
||||
|
||||
public class ListNode {
|
||||
|
||||
private int data;
|
||||
private ListNode next;
|
||||
|
||||
ListNode(int data) {
|
||||
this.data = data;
|
||||
this.next = null;
|
||||
}
|
||||
|
||||
public int getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public ListNode getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setData(int data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public void setNext(ListNode next) {
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.algorithms.linkedlist;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class LinkedListReversalUnitTest {
|
||||
@Test
|
||||
public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
|
||||
ListNode head = constructLinkedList();
|
||||
ListNode node = head;
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
assertNotNull(node);
|
||||
assertEquals(i, node.getData());
|
||||
node = node.getNext();
|
||||
}
|
||||
LinkedListReversal reversal = new LinkedListReversal();
|
||||
node = reversal.reverseList(head);
|
||||
for (int i = 5; i >= 1; i--) {
|
||||
assertNotNull(node);
|
||||
assertEquals(i, node.getData());
|
||||
node = node.getNext();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
|
||||
ListNode head = constructLinkedList();
|
||||
ListNode node = head;
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
assertNotNull(node);
|
||||
assertEquals(i, node.getData());
|
||||
node = node.getNext();
|
||||
}
|
||||
LinkedListReversal reversal = new LinkedListReversal();
|
||||
node = reversal.reverseListRecursive(head);
|
||||
for (int i = 5; i >= 1; i--) {
|
||||
assertNotNull(node);
|
||||
assertEquals(i, node.getData());
|
||||
node = node.getNext();
|
||||
}
|
||||
}
|
||||
|
||||
private ListNode constructLinkedList() {
|
||||
ListNode head = null;
|
||||
ListNode tail = null;
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
ListNode node = new ListNode(i);
|
||||
if (head == null) {
|
||||
head = node;
|
||||
} else {
|
||||
tail.setNext(node);
|
||||
}
|
||||
tail = node;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,11 @@
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>${zookeeper.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.lastmodifiedfile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileFilter;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.apache.commons.io.comparator.LastModifiedFileComparator;
|
||||
import org.apache.commons.io.filefilter.FileFilterUtils;
|
||||
|
||||
public class LastModifiedFileApp {
|
||||
|
||||
public static File findUsingIOApi(String sdir) {
|
||||
File dir = new File(sdir);
|
||||
if (dir.isDirectory()) {
|
||||
Optional<File> opFile = Arrays.stream(dir.listFiles(File::isFile))
|
||||
.max((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
|
||||
|
||||
if (opFile.isPresent()) {
|
||||
return opFile.get();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Path findUsingNIOApi(String sdir) throws IOException {
|
||||
Path dir = Paths.get(sdir);
|
||||
if (Files.isDirectory(dir)) {
|
||||
Optional<Path> opPath = Files.list(dir)
|
||||
.filter(p -> !Files.isDirectory(p))
|
||||
.sorted((p1, p2) -> Long.valueOf(p2.toFile().lastModified())
|
||||
.compareTo(p1.toFile().lastModified()))
|
||||
.findFirst();
|
||||
|
||||
if (opPath.isPresent()) {
|
||||
return opPath.get();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static File findUsingCommonsIO(String sdir) {
|
||||
File dir = new File(sdir);
|
||||
if (dir.isDirectory()) {
|
||||
File[] dirFiles = dir.listFiles((FileFilter) FileFilterUtils.fileFileFilter());
|
||||
if (dirFiles != null && dirFiles.length > 0) {
|
||||
Arrays.sort(dirFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
|
||||
return dirFiles[0];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.lastmodifiedfile;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class LastModifiedFileAppUnitTest {
|
||||
|
||||
private final static String SOURCEDIRECTORY = "src/test/resources/lastmodfiles";
|
||||
|
||||
@BeforeAll
|
||||
public static void setUpFiles() throws IOException, InterruptedException {
|
||||
File srcDir = new File(SOURCEDIRECTORY);
|
||||
if (!srcDir.exists()) {
|
||||
srcDir.mkdir();
|
||||
}
|
||||
|
||||
FileUtils.cleanDirectory(srcDir);
|
||||
|
||||
File file01 = new File(SOURCEDIRECTORY + "/file01.txt");
|
||||
file01.createNewFile();
|
||||
|
||||
Thread.sleep(2000);
|
||||
|
||||
File file02 = new File(SOURCEDIRECTORY + "/file02.txt");
|
||||
file02.createNewFile();
|
||||
|
||||
Thread.sleep(2000);
|
||||
|
||||
File file03 = new File(SOURCEDIRECTORY + "/file03.txt");
|
||||
file03.createNewFile();
|
||||
|
||||
Thread.sleep(2000);
|
||||
|
||||
Files.write(Paths.get(SOURCEDIRECTORY + "/file02.txt"), "Hello File02".getBytes());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirectory_whenUsingIoApi_thenFindLastModfile() throws IOException {
|
||||
File lastModFile = LastModifiedFileApp.findUsingIOApi(SOURCEDIRECTORY);
|
||||
|
||||
assertThat(lastModFile).isNotNull();
|
||||
assertThat(lastModFile.getName()).isEqualTo("file02.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirectory_whenUsingNioApi_thenFindLastModfile() throws IOException {
|
||||
Path lastModPath = LastModifiedFileApp.findUsingNIOApi(SOURCEDIRECTORY);
|
||||
|
||||
assertThat(lastModPath).isNotNull();
|
||||
assertThat(lastModPath.toFile().getName()).isEqualTo("file02.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDirectory_whenUsingApacheCommons_thenFindLastModfile() throws IOException {
|
||||
File lastModFile = LastModifiedFileApp.findUsingCommonsIO(SOURCEDIRECTORY);
|
||||
|
||||
assertThat(lastModFile).isNotNull();
|
||||
assertThat(lastModFile.getName()).isEqualTo("file02.txt");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public static void cleanUp() throws IOException {
|
||||
File srcDir = new File(SOURCEDIRECTORY);
|
||||
FileUtils.deleteDirectory(srcDir);
|
||||
}
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.getclassobject;
|
||||
|
||||
public class Animal {
|
||||
protected int numberOfEyes;
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.getclassobject;
|
||||
|
||||
public class Monkey extends Animal {
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.getclassobject;
|
||||
|
||||
public abstract class SomeAbstractClass {
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.getclassobject;
|
||||
|
||||
interface SomeInterface {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.getclassobject;
|
||||
|
||||
public class SomeUtils {
|
||||
private SomeUtils() {
|
||||
throw new RuntimeException("This Util class is not allowed to be instantiated!");
|
||||
}
|
||||
// public static utilMethods
|
||||
// ...
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.getclassobject;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class GetClassObjectUnitTest {
|
||||
@Test
|
||||
public void givenObjectAndType_whenGettingClassObject_thenTwoMethodsHaveTheSameResult() {
|
||||
String str = "I am an object of the String class";
|
||||
Class fromStrObject = str.getClass();
|
||||
Class clazz = String.class;
|
||||
assertSame(fromStrObject, clazz);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassInheritance_whenGettingRuntimeTypeAndStaticType_thenGetDifferentResult() {
|
||||
Animal animal = new Monkey();
|
||||
Class runtimeType = animal.getClass();
|
||||
Class staticType = Animal.class;
|
||||
//Not equals
|
||||
assertNotEquals(staticType, runtimeType);
|
||||
|
||||
Class monkeyClass = Monkey.class;
|
||||
assertSame(runtimeType, monkeyClass);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveType_whenGettingClassObject_thenOnlyStaticTypeWorks() {
|
||||
int number = 7;
|
||||
// Class numberClass = number.getClass(); <-- compilation error
|
||||
Class intType = int.class;
|
||||
|
||||
assertNotNull(intType);
|
||||
assertEquals("int", intType.getName());
|
||||
assertTrue(intType.isPrimitive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTypeCannotInstantiate_whenGetTypeStatically_thenGetTypesSuccefully() {
|
||||
Class interfaceType = SomeInterface.class;
|
||||
Class abstractClassType = SomeAbstractClass.class;
|
||||
Class utilClassType = SomeUtils.class;
|
||||
|
||||
assertNotNull(interfaceType);
|
||||
assertTrue(interfaceType.isInterface());
|
||||
assertEquals("SomeInterface", interfaceType.getSimpleName());
|
||||
|
||||
assertNotNull(abstractClassType);
|
||||
assertEquals("SomeAbstractClass", abstractClassType.getSimpleName());
|
||||
|
||||
assertNotNull(utilClassType);
|
||||
assertEquals("SomeUtils", utilClassType.getSimpleName());
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.trustedcert;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.PKIXParameters;
|
||||
import java.security.cert.TrustAnchor;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CertificatesUnitTest {
|
||||
|
||||
private static final String GODADDY_CA_ALIAS = "godaddyrootg2ca [jdk]";
|
||||
|
||||
@Test
|
||||
public void whenLoadingCacertsKeyStore_thenCertificatesArePresent() throws Exception {
|
||||
KeyStore keyStore = loadKeyStore();
|
||||
PKIXParameters params = new PKIXParameters(keyStore);
|
||||
|
||||
Set<TrustAnchor> trustAnchors = params.getTrustAnchors();
|
||||
List<Certificate> certificates = trustAnchors.stream()
|
||||
.map(TrustAnchor::getTrustedCert)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertFalse(certificates.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadingDefaultKeyStore_thenCertificatesArePresent() throws Exception {
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
trustManagerFactory.init((KeyStore)null);
|
||||
|
||||
List<TrustManager> trustManagers = Arrays.asList(trustManagerFactory.getTrustManagers());
|
||||
List<X509Certificate> certificates = trustManagers.stream()
|
||||
.filter(X509TrustManager.class::isInstance)
|
||||
.map(X509TrustManager.class::cast)
|
||||
.map(trustManager -> Arrays.asList(trustManager.getAcceptedIssuers()))
|
||||
.flatMap(Collection::stream)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertFalse(certificates.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadingKeyStore_thenGoDaddyCALabelIsPresent() throws Exception {
|
||||
KeyStore keyStore = loadKeyStore();
|
||||
|
||||
Enumeration<String> aliasEnumeration = keyStore.aliases();
|
||||
List<String> aliases = Collections.list(aliasEnumeration);
|
||||
|
||||
assertTrue(aliases.contains(GODADDY_CA_ALIAS));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLoadingKeyStore_thenGoDaddyCertificateIsPresent() throws Exception {
|
||||
KeyStore keyStore = loadKeyStore();
|
||||
|
||||
Certificate goDaddyCertificate = keyStore.getCertificate(GODADDY_CA_ALIAS);
|
||||
|
||||
assertNotNull(goDaddyCertificate);
|
||||
}
|
||||
|
||||
private KeyStore loadKeyStore() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
|
||||
String relativeCacertsPath = "/lib/security/cacerts".replace("/", File.separator);
|
||||
String filename = System.getProperty("java.home") + relativeCacertsPath;
|
||||
FileInputStream is = new FileInputStream(filename);
|
||||
|
||||
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
String password = "changeit";
|
||||
keystore.load(is, password.toCharArray());
|
||||
|
||||
return keystore;
|
||||
}
|
||||
}
|
||||
+1
-19
@@ -16,11 +16,6 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-core</artifactId>
|
||||
<version>${feign.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.openfeign</groupId>
|
||||
<artifactId>feign-okhttp</artifactId>
|
||||
@@ -44,21 +39,8 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<feign.version>9.4.0</feign.version>
|
||||
<spring-boot-maven-plugin.version>1.4.2.RELEASE</spring-boot-maven-plugin.version>
|
||||
<feign.version>10.11</feign.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -6,8 +6,6 @@ import com.baeldung.feign.models.BookResource;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -22,7 +20,6 @@ import static org.junit.Assert.assertTrue;
|
||||
* Consumes https://github.com/Baeldung/spring-hypermedia-api
|
||||
*/
|
||||
@Slf4j
|
||||
@RunWith(JUnit4.class)
|
||||
public class BookClientLiveTest {
|
||||
private BookClient bookClient;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>httpclient-2</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>httpclient-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@@ -13,6 +14,7 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- http client -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
@@ -24,6 +26,19 @@
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- rest template -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -34,10 +49,24 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source.version}</source>
|
||||
<target>${maven.compiler.target.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<httpclient.version>4.5.8</httpclient.version>
|
||||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.httpclient.cookies;
|
||||
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.cookie.Cookie;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.cookie.BasicClientCookie;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class HttpClientGettingCookieValueUnitTest {
|
||||
private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class);
|
||||
|
||||
private static final String SAMPLE_URL = "http://www.baeldung.com/";
|
||||
|
||||
@Test
|
||||
public final void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException {
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore());
|
||||
|
||||
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
|
||||
try (CloseableHttpResponse response = httpClient.execute(new HttpGet(SAMPLE_URL), context)) {
|
||||
CookieStore cookieStore = context.getCookieStore();
|
||||
Cookie customCookie = cookieStore.getCookies()
|
||||
.stream()
|
||||
.peek(cookie -> log.info("cookie name:{}", cookie.getName()))
|
||||
.filter(cookie -> "custom_cookie".equals(cookie.getName()))
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
|
||||
assertEquals("test_value", customCookie.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BasicCookieStore createCustomCookieStore() {
|
||||
BasicCookieStore cookieStore = new BasicCookieStore();
|
||||
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
|
||||
cookie.setDomain("baeldung.com");
|
||||
cookie.setPath("/");
|
||||
cookieStore.addCookie(cookie);
|
||||
return cookieStore;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.httpclient.readresponsebodystring;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class ApacheHttpClientUnitTest {
|
||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||
|
||||
@Test
|
||||
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
||||
HttpGet request = new HttpGet(DUMMY_URL);
|
||||
|
||||
try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) {
|
||||
HttpEntity entity = response.getEntity();
|
||||
String result = EntityUtils.toString(entity);
|
||||
System.out.println("Response -> " + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.httpclient.readresponsebodystring;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
public class HttpClientUnitTest {
|
||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||
|
||||
@Test
|
||||
public void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build();
|
||||
|
||||
// synchronous response
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
System.out.println(response.body());
|
||||
|
||||
// asynchronous response
|
||||
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
||||
.thenApply(HttpResponse::body)
|
||||
.thenAccept(System.out::println)
|
||||
.join();
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.httpclient.readresponsebodystring;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class HttpUrlConnectionUnitTest {
|
||||
|
||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||
|
||||
@Test
|
||||
public void whenUseHttpUrlConnection_thenCorrect() throws IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
|
||||
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
|
||||
StringBuilder response = new StringBuilder();
|
||||
String currentLine;
|
||||
|
||||
while ((currentLine = in.readLine()) != null)
|
||||
response.append(currentLine);
|
||||
|
||||
in.close();
|
||||
Assert.assertNotNull(response.toString());
|
||||
System.out.println("Response -> " + response.toString());
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.httpclient.readresponsebodystring;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
public class SpringRestTemplateUnitTest {
|
||||
|
||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||
|
||||
@Test
|
||||
public void whenUseRestTemplate_thenCorrect() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
String response = restTemplate.getForObject(DUMMY_URL, String.class);
|
||||
System.out.println(response);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,6 +23,13 @@
|
||||
<artifactId>jackson-datatype-joda</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+2
-5
@@ -60,8 +60,6 @@ public class CustomDeserializationUnitTest {
|
||||
String converted = objectMapper.writeValueAsString(now);
|
||||
// restore an instance of ZonedDateTime from String
|
||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||
System.out.println("serialized: " + now);
|
||||
System.out.println("restored: " + restored);
|
||||
assertThat(now, is(not(restored)));
|
||||
}
|
||||
|
||||
@@ -70,15 +68,14 @@ public class CustomDeserializationUnitTest {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.findAndRegisterModules();
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
|
||||
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
|
||||
// construct a new instance of ZonedDateTime
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
||||
String converted = objectMapper.writeValueAsString(now);
|
||||
// restore an instance of ZonedDateTime from String
|
||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||
System.out.println("serialized: " + now);
|
||||
System.out.println("restored: " + restored);
|
||||
assertThat(now, is(restored));
|
||||
assertThat(restored, is(now));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-3
@@ -24,7 +24,6 @@ public class CustomSerializationUnitTest {
|
||||
public final void whenSerializing_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException {
|
||||
final Item myItem = new Item(1, "theItem", new User(2, "theUser"));
|
||||
final String serialized = new ObjectMapper().writeValueAsString(myItem);
|
||||
System.out.println(serialized);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -38,7 +37,6 @@ public class CustomSerializationUnitTest {
|
||||
mapper.registerModule(simpleModule);
|
||||
|
||||
final String serialized = mapper.writeValueAsString(myItem);
|
||||
System.out.println(serialized);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -46,7 +44,6 @@ public class CustomSerializationUnitTest {
|
||||
final ItemWithSerializer myItem = new ItemWithSerializer(1, "theItem", new User(2, "theUser"));
|
||||
|
||||
final String serialized = new ObjectMapper().writeValueAsString(myItem);
|
||||
System.out.println(serialized);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-2
@@ -37,7 +37,6 @@ public class IgnoreFieldsWithFilterUnitTest {
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
assertThat(dtoAsString, containsString("stringValue"));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -83,7 +82,6 @@ public class IgnoreFieldsWithFilterUnitTest {
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
assertThat(dtoAsString, containsString("stringValue"));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-8
@@ -51,8 +51,6 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||
assertTrue(result.contains("john"));
|
||||
assertTrue(result.contains("address"));
|
||||
assertTrue(result.contains("usa"));
|
||||
|
||||
System.out.println("Not Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,8 +63,6 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||
assertTrue(result.contains("john"));
|
||||
assertFalse(result.contains("address"));
|
||||
assertFalse(result.contains("usa"));
|
||||
|
||||
System.out.println("Address Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -76,8 +72,6 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.length() == 0);
|
||||
|
||||
System.out.println("All Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -90,7 +84,5 @@ public class JacksonDynamicIgnoreUnitTest {
|
||||
final Person p3 = new Person("adam", ad3, false);
|
||||
|
||||
final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3));
|
||||
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -53,12 +53,12 @@
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>2.11.0</version>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.11.0</version>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.io-informatics.oss</groupId>
|
||||
|
||||
+22
-6
@@ -7,22 +7,38 @@ import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
|
||||
import au.com.dius.pact.model.RequestResponsePact;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PactConsumerDrivenContractUnitTest {
|
||||
|
||||
private static int getAvailablePort() {
|
||||
return new Random()
|
||||
.ints(6000, 9000)
|
||||
.filter(PactConsumerDrivenContractUnitTest::isFree)
|
||||
.findFirst()
|
||||
.orElse(8080);
|
||||
}
|
||||
|
||||
private static boolean isFree(int port) {
|
||||
try {
|
||||
new ServerSocket(port).close();
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Rule
|
||||
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
|
||||
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("test_provider", "localhost", getAvailablePort(), this);
|
||||
|
||||
@Pact(consumer = "test_consumer")
|
||||
public RequestResponsePact createPact(PactDslWithProvider builder) {
|
||||
|
||||
@@ -107,6 +107,12 @@
|
||||
<artifactId>renjin-script-engine</artifactId>
|
||||
<version>${renjin.version}</version>
|
||||
</dependency>
|
||||
<!-- libphonenumber -->
|
||||
<dependency>
|
||||
<groupId>com.googlecode.libphonenumber</groupId>
|
||||
<artifactId>libphonenumber</artifactId>
|
||||
<version>${libphonenumber.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
@@ -150,6 +156,7 @@
|
||||
<renjin.version>RELEASE</renjin.version>
|
||||
<rcaller.version>3.0</rcaller.version>
|
||||
<rserve.version>1.8.1</rserve.version>
|
||||
<libphonenumber.version>8.12.9</libphonenumber.version>
|
||||
</properties>
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.libphonenumber;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
|
||||
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
|
||||
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
|
||||
|
||||
public class LibPhoneNumberUnitTest {
|
||||
|
||||
private static final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenValid_thenOK() throws Exception {
|
||||
|
||||
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", CountryCodeSource.UNSPECIFIED.name());
|
||||
|
||||
assertTrue(phoneNumberUtil.isValidNumber(phone));
|
||||
assertTrue(phoneNumberUtil.isValidNumberForRegion(phone, "IN"));
|
||||
assertFalse(phoneNumberUtil.isValidNumberForRegion(phone, "US"));
|
||||
assertTrue(phoneNumberUtil.isValidNumber(phoneNumberUtil.getExampleNumber("IN")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenAlphaNumber_thenValid() {
|
||||
assertTrue(phoneNumberUtil.isAlphaNumber("325-CARS"));
|
||||
assertTrue(phoneNumberUtil.isAlphaNumber("0800 REPAIR"));
|
||||
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE"));
|
||||
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE.."));
|
||||
assertFalse(phoneNumberUtil.isAlphaNumber("+876 1234-1234"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenPossibleForType_thenValid() {
|
||||
PhoneNumber number = new PhoneNumber();
|
||||
number.setCountryCode(54);
|
||||
|
||||
number.setNationalNumber(123456);
|
||||
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
|
||||
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
|
||||
|
||||
number.setNationalNumber(12345678901L);
|
||||
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
|
||||
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
|
||||
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenPossible_thenValid() {
|
||||
PhoneNumber number = new PhoneNumber();
|
||||
number.setCountryCode(1)
|
||||
.setNationalNumber(123000L);
|
||||
assertFalse(phoneNumberUtil.isPossibleNumber(number));
|
||||
assertFalse(phoneNumberUtil.isPossibleNumber("+1 343 253 00000", "US"));
|
||||
assertFalse(phoneNumberUtil.isPossibleNumber("(343) 253-00000", "US"));
|
||||
assertFalse(phoneNumberUtil.isPossibleNumber("dial p for pizza", "US"));
|
||||
assertFalse(phoneNumberUtil.isPossibleNumber("123-000", "US"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenNumberGeographical_thenValid() throws NumberParseException {
|
||||
|
||||
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", "IN");
|
||||
assertTrue(phoneNumberUtil.isNumberGeographical(phone));
|
||||
|
||||
phone = new PhoneNumber().setCountryCode(1)
|
||||
.setNationalNumber(2530000L);
|
||||
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
|
||||
|
||||
phone = new PhoneNumber().setCountryCode(800)
|
||||
.setNationalNumber(12345678L);
|
||||
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user