+4
-4
@@ -13,22 +13,22 @@ public class KadaneAlgorithm {
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
|
||||
int maxSoFar = 0, maxEndingHere = 0;
|
||||
|
||||
int maxSoFar = arr[0], maxEndingHere = arr[0];
|
||||
for (int i = 0; i < size; i++) {
|
||||
|
||||
if (arr[i] > maxEndingHere + arr[i]) {
|
||||
start = i;
|
||||
maxEndingHere = arr[i];
|
||||
} else
|
||||
} else {
|
||||
maxEndingHere = maxEndingHere + arr[i];
|
||||
}
|
||||
|
||||
if (maxSoFar < maxEndingHere) {
|
||||
maxSoFar = maxEndingHere;
|
||||
end = i;
|
||||
}
|
||||
}
|
||||
logger.info("Found Maximum Subarray between {} and {}", start, end);
|
||||
logger.info("Found Maximum Subarray between {} and {}", Math.min(start, end), end);
|
||||
return maxSoFar;
|
||||
}
|
||||
}
|
||||
|
||||
+12
-1
@@ -9,11 +9,22 @@ class KadaneAlgorithmUnitTest {
|
||||
@Test
|
||||
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
|
||||
//given
|
||||
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
|
||||
int[] arr = new int[] { -3, 1, -8, 4, -1, 2, 1, -5, 5 };
|
||||
//when
|
||||
KadaneAlgorithm algorithm = new KadaneAlgorithm();
|
||||
int maxSum = algorithm.maxSubArraySum(arr);
|
||||
//then
|
||||
assertEquals(6, maxSum);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithAllNegativeNumbersWhenMaximumSubarrayThenReturnsExpectedResult() {
|
||||
//given
|
||||
int[] arr = new int[] { -8, -7, -5, -4, -3, -1, -2 };
|
||||
//when
|
||||
KadaneAlgorithm algorithm = new KadaneAlgorithm();
|
||||
int maxSum = algorithm.maxSubArraySum(arr);
|
||||
//then
|
||||
assertEquals(-1, maxSum);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,12 @@
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.19.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
-1
@@ -2,7 +2,6 @@ package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.genericarrays;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
public class StreamToArrayUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAStream_thenCanGetArrayOfObject() {
|
||||
Object[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.toArray();
|
||||
|
||||
assertThat(strings).containsExactly("A", "AAA", "AAB");
|
||||
assertThat(strings).isNotInstanceOf(String[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStream_thenCanGetArrayOfString() {
|
||||
String[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.toArray(String[]::new);
|
||||
|
||||
assertThat(strings).containsExactly("A", "AAA", "AAB");
|
||||
assertThat(strings).isInstanceOf(String[].class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptional() {
|
||||
Stream<Optional<String>> stream = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.map(Optional::of);
|
||||
Optional<String>[] strings = stream
|
||||
.toArray(Optional[]::new);
|
||||
|
||||
assertThat(strings).containsExactly(Optional.of("A"),
|
||||
Optional.of("AAA"),
|
||||
Optional.of("AAB"));
|
||||
assertThat(strings).isInstanceOf(Optional[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptionalWithHelper() {
|
||||
Optional<String>[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
|
||||
.filter(string -> string.startsWith("A"))
|
||||
.map(Optional::of)
|
||||
.toArray(genericArray(Optional[]::new));
|
||||
|
||||
assertThat(strings).containsExactly(Optional.of("A"),
|
||||
Optional.of("AAA"),
|
||||
Optional.of("AAB"));
|
||||
assertThat(strings).isInstanceOf(Optional[].class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvalidUseOfGenericArray_thenIllegalCast() {
|
||||
assertThatThrownBy(() -> {
|
||||
ArrayList<String>[] lists = Stream.of(singletonList("A"))
|
||||
.toArray(genericArray(List[]::new));
|
||||
}).isInstanceOf(ClassCastException.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) {
|
||||
return size -> (R[])arrayCreator.apply(size);
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,6 @@
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- instrumentation -->
|
||||
<javaassist.version>3.27.0-GA</javaassist.version>
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<sun.tools.version>1.8.0</sun.tools.version>
|
||||
<jol-core.version>0.10</jol-core.version>
|
||||
<asm.version>8.0.1</asm.version>
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
This module contains articles about core features in the Java language
|
||||
|
||||
- TODO
|
||||
- [The Java final Keyword – Impact on Performance](https://www.baeldung.com/java-final-performance)
|
||||
|
||||
+6
-2
@@ -47,6 +47,7 @@ public class Outer {
|
||||
// Anonymous Inner class extending a class
|
||||
public String greet() {
|
||||
Outer anonymous = new Outer() {
|
||||
@Override
|
||||
public String greet() {
|
||||
return "Running Anonymous Class...";
|
||||
}
|
||||
@@ -58,6 +59,7 @@ public class Outer {
|
||||
public String greet(String name) {
|
||||
|
||||
HelloWorld helloWorld = new HelloWorld() {
|
||||
@Override
|
||||
public String greet(String name) {
|
||||
return "Welcome to " + name;
|
||||
}
|
||||
@@ -68,8 +70,9 @@ public class Outer {
|
||||
|
||||
// Anonymous inner class implementing nested interface
|
||||
public String greetSomeone(String name) {
|
||||
|
||||
|
||||
HelloSomeone helloSomeOne = new HelloSomeone() {
|
||||
@Override
|
||||
public String greet(String name) {
|
||||
return "Hello " + name;
|
||||
}
|
||||
@@ -94,7 +97,8 @@ interface HelloWorld {
|
||||
public String greet(String name);
|
||||
|
||||
// Nested class within an interface
|
||||
class InnerClass {
|
||||
class InnerClass implements HelloWorld {
|
||||
@Override
|
||||
public String greet(String name) {
|
||||
return "Inner class within an interface";
|
||||
}
|
||||
|
||||
@@ -148,48 +148,46 @@ public class BinaryTree {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void traverseInOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Stack<Node> stack = new Stack<>();
|
||||
Node current = root;
|
||||
|
||||
while (current != null || !stack.isEmpty()) {
|
||||
while (current != null) {
|
||||
stack.push(current);
|
||||
current = current.left;
|
||||
}
|
||||
|
||||
Node top = stack.pop();
|
||||
visit(top.value);
|
||||
current = top.right;
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
while(current.left != null) {
|
||||
current = current.left;
|
||||
stack.push(current);
|
||||
}
|
||||
|
||||
while (current != null && !stack.isEmpty()) {
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
if(current.right != null) {
|
||||
current = current.right;
|
||||
stack.push(current);
|
||||
}
|
||||
|
||||
if (current.right != null)
|
||||
stack.push(current.right);
|
||||
|
||||
if (current.left != null)
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
|
||||
if(current.right != null)
|
||||
stack.push(current.right);
|
||||
|
||||
if(current.left != null)
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Stack<Node> stack = new Stack<>();
|
||||
Node prev = root;
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
while (current != null && !stack.isEmpty()) {
|
||||
current = stack.peek();
|
||||
boolean hasChild = (current.left != null || current.right != null);
|
||||
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
|
||||
|
||||
@@ -13,7 +13,7 @@ public class BinaryTreeUnitTest {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(!bt.isEmpty());
|
||||
assertFalse(bt.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,6 +72,7 @@ public class BinaryTreeUnitTest {
|
||||
|
||||
@Test
|
||||
public void it_deletes_the_root() {
|
||||
|
||||
int value = 12;
|
||||
BinaryTree bt = new BinaryTree();
|
||||
bt.add(value);
|
||||
@@ -91,6 +92,14 @@ public class BinaryTreeUnitTest {
|
||||
bt.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnEmptyBinaryTree_WhenTraversingInOrderWithoutRecursion_ThenNoException() {
|
||||
|
||||
BinaryTree empty = new BinaryTree();
|
||||
|
||||
empty.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
|
||||
|
||||
@@ -101,6 +110,14 @@ public class BinaryTreeUnitTest {
|
||||
bt.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnEmptyBinaryTree_WhenTraversingPreOrderWithoutRecursion_ThenNoException() {
|
||||
|
||||
BinaryTree empty = new BinaryTree();
|
||||
|
||||
empty.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
|
||||
|
||||
@@ -111,6 +128,14 @@ public class BinaryTreeUnitTest {
|
||||
bt.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnEmptyBinaryTree_WhenTraversingPostOrderWithoutRecursion_ThenNoException() {
|
||||
|
||||
BinaryTree empty = new BinaryTree();
|
||||
|
||||
empty.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
|
||||
|
||||
|
||||
@@ -47,3 +47,4 @@ Available commands (assumes httpie - https://github.com/jkbrzt/httpie):
|
||||
## Relevant articles:
|
||||
|
||||
- [Supercharge Java Authentication with JSON Web Tokens (JWTs)](https://www.baeldung.com/java-json-web-tokens-jjwt)
|
||||
- [Decode a JWT Token in Java](https://www.baeldung.com/java-jwt-token-decode)
|
||||
|
||||
@@ -41,6 +41,12 @@
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package io.jsonwebtoken.jjwtfun.util;
|
||||
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator;
|
||||
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
import static io.jsonwebtoken.SignatureAlgorithm.HS256;
|
||||
|
||||
public class JWTDecoderUtil {
|
||||
|
||||
public static String decodeJWTToken(String token) {
|
||||
Base64.Decoder decoder = Base64.getDecoder();
|
||||
|
||||
String[] chunks = token.split("\\.");
|
||||
|
||||
String header = new String(decoder.decode(chunks[0]));
|
||||
String payload = new String(decoder.decode(chunks[1]));
|
||||
|
||||
return header + " " + payload;
|
||||
}
|
||||
|
||||
public static String decodeJWTToken(String token, String secretKey) throws Exception {
|
||||
Base64.Decoder decoder = Base64.getDecoder();
|
||||
|
||||
String[] chunks = token.split("\\.");
|
||||
|
||||
String header = new String(decoder.decode(chunks[0]));
|
||||
String payload = new String(decoder.decode(chunks[1]));
|
||||
|
||||
String tokenWithoutSignature = chunks[0] + "." + chunks[1];
|
||||
String signature = chunks[2];
|
||||
|
||||
SignatureAlgorithm sa = HS256;
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), sa.getJcaName());
|
||||
|
||||
DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, secretKeySpec);
|
||||
|
||||
if (!validator.isValid(tokenWithoutSignature, signature)) {
|
||||
throw new Exception("Could not verify JWT token integrity!");
|
||||
}
|
||||
|
||||
return header + " " + payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.jsonwebtoken.jjwtfun.util;
|
||||
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class JWTDecoderUtilUnitTest {
|
||||
|
||||
private final static String SIMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9";
|
||||
private final static String SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.qH7Zj_m3kY69kxhaQXTa-ivIpytKXXjZc1ZSmapZnGE";
|
||||
|
||||
@Test
|
||||
void givenSimpleToken_whenDecoding_thenStringOfHeaderPayloadAreReturned() {
|
||||
assertThat(JWTDecoderUtil.decodeJWTToken(SIMPLE_TOKEN))
|
||||
.contains(SignatureAlgorithm.HS256.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSignedToken_whenDecodingWithInvalidSecret_thenIntegrityIsNotValidated() {
|
||||
assertThatThrownBy(() -> JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "BAD_SECRET"))
|
||||
.hasMessage("Could not verify JWT token integrity!");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSignedToken_whenDecodingWithValidSecret_thenIntegrityIsValidated() throws Exception {
|
||||
assertThat(JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "MySecretKey"))
|
||||
.contains("Baeldung User");
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,8 @@ An easy way to check that everything is working as expected is issuing any *kube
|
||||
```shell
|
||||
$ kubectl get nodes
|
||||
```
|
||||
If you get a valid response, then you're good to go.
|
||||
If you get a valid response, then you're good to go.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Paging and Async Calls with the Kubernetes API](https://www.baeldung.com/java-kubernetes-paging-async)
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
<artifactId>client-java</artifactId>
|
||||
<version>11.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
import io.kubernetes.client.openapi.ApiCallback;
|
||||
import io.kubernetes.client.openapi.ApiException;
|
||||
import io.kubernetes.client.openapi.apis.CoreV1Api;
|
||||
import okhttp3.Call;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ApiInvoker<R> {
|
||||
Call apply(CoreV1Api api, ApiCallback<R> callback) throws ApiException;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.kubernetes.client.openapi.ApiCallback;
|
||||
import io.kubernetes.client.openapi.ApiException;
|
||||
import io.kubernetes.client.openapi.apis.CoreV1Api;
|
||||
import okhttp3.Call;
|
||||
|
||||
public class AsyncHelper<R> implements ApiCallback<R> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AsyncHelper.class);
|
||||
|
||||
private CoreV1Api api;
|
||||
private CompletableFuture<R> callResult;
|
||||
|
||||
private AsyncHelper(CoreV1Api api) {
|
||||
this.api = api;
|
||||
}
|
||||
|
||||
public static <T> CompletableFuture<T> doAsync(CoreV1Api api, ApiInvoker<T> invoker) {
|
||||
|
||||
AsyncHelper<T> p = new AsyncHelper<>(api);
|
||||
return p.execute(invoker);
|
||||
}
|
||||
|
||||
private CompletableFuture<R> execute( ApiInvoker<R> invoker) {
|
||||
|
||||
try {
|
||||
callResult = new CompletableFuture<>();
|
||||
log.info("[I38] Calling API...");
|
||||
final Call call = invoker.apply(api,this);
|
||||
log.info("[I41] API Succesfully invoked: method={}, url={}",
|
||||
call.request().method(),
|
||||
call.request().url());
|
||||
return callResult;
|
||||
}
|
||||
catch(ApiException aex) {
|
||||
callResult.completeExceptionally(aex);
|
||||
return callResult;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
|
||||
log.error("[E53] onFailure",e);
|
||||
callResult.completeExceptionally(e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSuccess(R result, int statusCode, Map<String, List<String>> responseHeaders) {
|
||||
log.error("[E61] onSuccess: statusCode={}",statusCode);
|
||||
callResult.complete(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
|
||||
log.info("[E61] onUploadProgress: bytesWritten={}, contentLength={}, done={}",bytesWritten,contentLength,done);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
|
||||
log.info("[E75] onDownloadProgress: bytesRead={}, contentLength={}, done={}",bytesRead,contentLength,done);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.kubernetes.client.openapi.ApiClient;
|
||||
import io.kubernetes.client.openapi.apis.CoreV1Api;
|
||||
import io.kubernetes.client.openapi.models.V1NodeList;
|
||||
import io.kubernetes.client.util.Config;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
public class ListNodesAsync {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ListNodesAsync.class);
|
||||
/**
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
// Initial setup
|
||||
ApiClient client = Config.defaultClient();
|
||||
CoreV1Api api = new CoreV1Api(client);
|
||||
|
||||
// Start async call
|
||||
CompletableFuture<V1NodeList> p = AsyncHelper.doAsync(api,(capi,cb) ->
|
||||
capi.listNodeAsync(null, null, null, null, null, null, null, null, 10, false, cb)
|
||||
);
|
||||
|
||||
p.thenAcceptAsync((nodeList) -> {
|
||||
log.info("[I40] Processing results...");
|
||||
nodeList.getItems()
|
||||
.stream()
|
||||
.forEach((node) -> System.out.println(node.getMetadata()));
|
||||
});
|
||||
|
||||
log.info("[I46] Waiting results...");
|
||||
p.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import io.kubernetes.client.openapi.ApiClient;
|
||||
import io.kubernetes.client.openapi.apis.CoreV1Api;
|
||||
import io.kubernetes.client.openapi.models.V1NodeList;
|
||||
import io.kubernetes.client.openapi.models.V1PodList;
|
||||
import io.kubernetes.client.util.Config;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
public class ListPodsPaged {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ListPodsPaged.class);
|
||||
|
||||
/**
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
ApiClient client = Config.defaultClient();
|
||||
CoreV1Api api = new CoreV1Api(client);
|
||||
String continuationToken = null;
|
||||
int limit = 2; // Just for illustration purposes. Real world values would range from ~100 to ~1000/page
|
||||
Long remaining = null;
|
||||
do {
|
||||
log.info("==========================================================================");
|
||||
log.info("Retrieving data: continuationToken={}, remaining={}", continuationToken,remaining);
|
||||
V1PodList items = api.listPodForAllNamespaces(null, continuationToken, null, null, limit, null, null, null, 10, false);
|
||||
continuationToken = items.getMetadata().getContinue();
|
||||
remaining = items.getMetadata().getRemainingItemCount();
|
||||
items.getItems()
|
||||
.stream()
|
||||
.forEach((node) -> System.out.println(node.getMetadata()));
|
||||
} while( continuationToken != null );
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ListNodesAsyncLiveTest {
|
||||
@Test
|
||||
void whenListNodes_thenSuccess() throws Exception {
|
||||
ListNodesAsync.main(new String[] {});
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.kubernetes.intro;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ListPodsPagedLiveTest {
|
||||
@Test
|
||||
void whenListPodsPage_thenSuccess() throws Exception {
|
||||
ListPodsPaged.main(new String[] {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="debug">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -82,7 +82,7 @@
|
||||
<rest-assured.version>3.3.0</rest-assured.version>
|
||||
<!-- plugins -->
|
||||
<thin.version>1.0.22.RELEASE</thin.version>
|
||||
<spring-boot.version>2.4.0</spring-boot.version>
|
||||
<spring-boot.version>2.4.3</spring-boot.version>
|
||||
<aspectjweaver.version>1.9.1</aspectjweaver.version>
|
||||
<!-- this property can be removed once we update Mockito version in the main pom.xml -->
|
||||
<mockito.version>3.4.0</mockito.version>
|
||||
|
||||
+2
-2
@@ -38,8 +38,8 @@ public class UsingOptional {
|
||||
.flatMap(list -> list.stream().findFirst());
|
||||
}
|
||||
|
||||
private Optional<List> getOptionalList() {
|
||||
return Optional.ofNullable(getList());
|
||||
private Optional<List<String>> getOptionalList() {
|
||||
return Optional.of(getList());
|
||||
}
|
||||
|
||||
private String doSomething(boolean processed) {
|
||||
|
||||
+4
-7
@@ -19,22 +19,22 @@ class UsingOptionalUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArgIsFalse_thenReturnEmptyResponse() {
|
||||
void whenArgIsFalse_thenReturnEmptyResponse() {
|
||||
Optional<Object> result = dataObject.process(false);
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArgIsTrue_thenReturnValidResponse() {
|
||||
void whenArgIsTrue_thenReturnValidResponse() {
|
||||
Optional<Object> result = dataObject.process(true);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArgIsFalse_thenChainResponseAndThrowException() {
|
||||
assertThrows(Exception.class, () -> dataObject.process(false).orElseThrow(() -> new Exception()));
|
||||
void whenArgIsFalse_thenChainResponseAndThrowException() {
|
||||
assertThrows(Exception.class, () -> dataObject.process(false).orElseThrow(Exception::new));
|
||||
}
|
||||
|
||||
@Test()
|
||||
@@ -51,7 +51,4 @@ class UsingOptionalUnitTest {
|
||||
void whenOptionalListFirst_returnsEmptyOptional() {
|
||||
assertFalse(dataObject.optionalListFirst().isPresent());
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.tableexists;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
class DatabaseConfig {
|
||||
static Connection connect() throws ClassNotFoundException, SQLException {
|
||||
Class.forName("org.h2.Driver");
|
||||
String url = "jdbc:h2:mem:testdb";
|
||||
return DriverManager.getConnection(url, "user", "password");
|
||||
}
|
||||
|
||||
static void createTables(Connection connection) throws SQLException {
|
||||
connection.createStatement().executeUpdate("create table EMPLOYEE (id int primary key auto_increment, name VARCHAR(255))");
|
||||
}
|
||||
|
||||
static void dropTables(Connection connection) throws SQLException {
|
||||
connection.createStatement().executeUpdate("drop table EMPLOYEE");
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.tableexists;
|
||||
|
||||
import java.sql.*;
|
||||
|
||||
class TableChecker {
|
||||
static void printAllTables(Connection connection, String tableName) throws SQLException {
|
||||
DatabaseMetaData databaseMetaData = connection.getMetaData();
|
||||
ResultSet resultSet = databaseMetaData.getTables(null, null, tableName, new String[] {"TABLE"});
|
||||
|
||||
while (resultSet.next()) {
|
||||
String name = resultSet.getString("TABLE_NAME");
|
||||
String schema = resultSet.getString("TABLE_SCHEM");
|
||||
System.out.println(name + " on schema " + schema);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean tableExists(Connection connection, String tableName) throws SQLException {
|
||||
DatabaseMetaData meta = connection.getMetaData();
|
||||
ResultSet resultSet = meta.getTables(null, null, tableName, new String[] {"TABLE"});
|
||||
|
||||
return resultSet.next();
|
||||
}
|
||||
|
||||
static boolean tableExistsSQL(Connection connection, String tableName) throws SQLException {
|
||||
PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) " +
|
||||
"FROM information_schema.tables " +
|
||||
"WHERE table_name = ?" +
|
||||
"LIMIT 1;");
|
||||
preparedStatement.setString(1, tableName);
|
||||
|
||||
ResultSet resultSet = preparedStatement.executeQuery();
|
||||
resultSet.next();
|
||||
return resultSet.getInt(1) != 0;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.tableexists;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class TableCheckerUnitTest {
|
||||
|
||||
@Test
|
||||
void givenCreatedTable_shouldFindTable() throws SQLException, ClassNotFoundException {
|
||||
// given
|
||||
Connection connection = DatabaseConfig.connect();
|
||||
DatabaseConfig.createTables(connection);
|
||||
|
||||
// when
|
||||
boolean tableExists = TableChecker.tableExists(connection, "EMPLOYEE");
|
||||
|
||||
// then
|
||||
TableChecker.printAllTables(connection, null);
|
||||
assertTrue(tableExists);
|
||||
|
||||
DatabaseConfig.dropTables(connection);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCreatedTable_shouldFindTableWithSQL() throws SQLException, ClassNotFoundException {
|
||||
// given
|
||||
Connection connection = DatabaseConfig.connect();
|
||||
DatabaseConfig.createTables(connection);
|
||||
|
||||
// when
|
||||
boolean tableExists = TableChecker.tableExistsSQL(connection, "EMPLOYEE");
|
||||
|
||||
// then
|
||||
TableChecker.printAllTables(connection, null);
|
||||
assertTrue(tableExists);
|
||||
|
||||
DatabaseConfig.dropTables(connection);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNoTable_shouldNotFindTable() throws SQLException, ClassNotFoundException {
|
||||
// given
|
||||
Connection connection = DatabaseConfig.connect();
|
||||
|
||||
// when
|
||||
boolean tableExists = TableChecker.tableExists(connection, "EMPLOYEE");
|
||||
|
||||
// then
|
||||
TableChecker.printAllTables(connection, null);
|
||||
assertFalse(tableExists);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNoTable_shouldNotFindTableWithSQL() throws SQLException, ClassNotFoundException {
|
||||
// given
|
||||
Connection connection = DatabaseConfig.connect();
|
||||
|
||||
// when
|
||||
boolean tableExists = TableChecker.tableExistsSQL(connection, "EMPLOYEE");
|
||||
|
||||
// then
|
||||
TableChecker.printAllTables(connection, null);
|
||||
assertFalse(tableExists);
|
||||
}
|
||||
}
|
||||
+19
@@ -162,6 +162,25 @@ public class ApplicationView {
|
||||
return betweenItems;
|
||||
}
|
||||
|
||||
// To get records having itemName in 'Skate Board', 'Paint' and 'Glue'
|
||||
public String[] inCriteria() {
|
||||
final Session session = HibernateUtil.getHibernateSession();
|
||||
final CriteriaBuilder cb = session.getCriteriaBuilder();
|
||||
final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
|
||||
final Root<Item> root = cr.from(Item.class);
|
||||
cr.select(root)
|
||||
.where(root.get("itemName").in("Skate Board", "Paint", "Glue"));
|
||||
Query<Item> query = session.createQuery(cr);
|
||||
final List<Item> inItemsList = query.getResultList();
|
||||
final String inItems[] = new String[inItemsList.size()];
|
||||
for (int i = 0; i < inItemsList.size(); i++) {
|
||||
inItems[i] = inItemsList.get(i)
|
||||
.getItemName();
|
||||
}
|
||||
session.close();
|
||||
return inItems;
|
||||
}
|
||||
|
||||
// To check if the given property is null
|
||||
public String[] nullCriteria() {
|
||||
final Session session = HibernateUtil.getHibernateSession();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user