This commit is contained in:
jsgrah-spring 2022-11-03 20:59:10 +01:00
commit 8c8a3f9a56
29 changed files with 375 additions and 13 deletions

View File

@ -4,4 +4,5 @@
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
- [Guide to In-Place Sorting Algorithm Works with a Java Implementation](https://www.baeldung.com/java-in-place-sorting)
- [Partitioning and Sorting Arrays with Many Repeated Entries with Java Examples](https://www.baeldung.com/java-sorting-arrays-with-repeated-entries)
- [Gravity/Bead Sort in Java](https://www.baeldung.com/java-gravity-bead-sort)
- More articles: [[<-- prev]](/algorithms-sorting)

View File

@ -1,3 +1,4 @@
## Relevant articles
- [Using Streams to Collect Into a TreeSet](https://www.baeldung.com/java-stream-collect-into-treeset)
- [A Guide to LinkedHashSet in Java](https://www.baeldung.com/java-linkedhashset)

View File

@ -0,0 +1,35 @@
package com.baeldung.math.standarddeviation;
import java.util.Arrays;
public class StandardDeviation {
public static double calculateStandardDeviation(double[] array) {
// get the sum of array
double sum = 0.0;
for (double i : array) {
sum += i;
}
// get the mean of array
int length = array.length;
double mean = sum / length;
// calculate the standard deviation
double standardDeviation = 0.0;
for (double num : array) {
standardDeviation += Math.pow(num - mean, 2);
}
return Math.sqrt(standardDeviation / length);
}
public static void main(String[] args) {
double[] array = {25, 5, 45, 68, 61, 46, 24, 95};
System.out.println("List of elements: " + Arrays.toString(array));
double standardDeviation = calculateStandardDeviation(array);
System.out.format("Standard Deviation = %.6f", standardDeviation);
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles:
- [Difference Between URI.create() and new URI()](https://www.baeldung.com/java-uri-create-and-new-uri)

View File

@ -174,7 +174,7 @@
<gson.version>2.8.2</gson.version>
<cache.version>1.1.1</cache.version>
<flink.version>1.5.0</flink.version>
<hazelcast.version>3.8.4</hazelcast.version>
<hazelcast.version>5.2.0</hazelcast.version>
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
<jmapper.version>1.6.0.1</jmapper.version>

View File

@ -16,21 +16,22 @@ import org.junit.Test;
public class CacheLoaderIntegrationTest {
private static final String CACHE_NAME = "SimpleCache";
private static final String HAZELCAST_MEMBER_CACHING_PROVIDER = "com.hazelcast.cache.HazelcastMemberCachingProvider";
private Cache<Integer, String> cache;
@Before
public void setup() {
// Adding fully qualified class name because of multiple Cache Provider (Ignite and Hazelcast)
CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider");
CachingProvider cachingProvider = Caching.getCachingProvider(HAZELCAST_MEMBER_CACHING_PROVIDER);
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<Integer, String> config = new MutableConfiguration<Integer, String>().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader()));
this.cache = cacheManager.createCache("SimpleCache", config);
this.cache = cacheManager.createCache( CACHE_NAME, config );
}
@After
public void tearDown() {
Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider").getCacheManager().destroyCache(CACHE_NAME);
Caching.getCachingProvider(HAZELCAST_MEMBER_CACHING_PROVIDER).getCacheManager().destroyCache(CACHE_NAME);
}
@Test

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
import java.util.Date;

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
import java.util.Date;

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
public interface Notifier<T> {

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
import java.util.Date;

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
import java.util.Date;

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
public class StringNotifier implements Notifier<String> {

View File

@ -1,4 +1,4 @@
package com.baeldung.factoryGeneric;
package com.baeldung.factorygeneric;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

View File

@ -0,0 +1,62 @@
package com.baeldung.rxjava;
import io.reactivex.Observable;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
public class RxJavaRetryWithDelayUnitTest {
@Test
public void givenObservable_whenSuccess_thenOnNext(){
Observable.just(remoteCallSuccess())
.subscribe(success -> {
System.out.println("Success");
System.out.println(success);
}, err -> {
System.out.println("Error");
System.out.println(err);
});
}
@Test
public void givenObservable_whenError_thenOnError(){
Observable.just(remoteCallError())
.subscribe(success -> {
System.out.println("Success");
System.out.println(success);
}, err -> {
System.out.println("Error");
System.out.println(err);
});
}
@Test
public void givenError_whenRetry_thenCanDelay(){
Observable.just(remoteCallError())
.retryWhen(attempts -> {
return attempts.flatMap(err -> {
if (customChecker(err)) {
return Observable.timer(5000, TimeUnit.MILLISECONDS);
} else {
return Observable.error(err);
}
});
});
}
private String remoteCallSuccess(){
return "Success";
}
private String remoteCallError(){
// consider a network call that failed over here.
return "Error";
}
private boolean customChecker(Throwable t){
// this will include custom logic that decides whether resubscription should occur or not
return true;
}
}

View File

@ -5,3 +5,4 @@ This module contains articles about Spring 5 WebFlux
## Relevant articles:
- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable)
- [Comparison Between Monos doOnNext() and doOnSuccess()](https://www.baeldung.com/mono-doonnext-doonsuccess)
- [How to Access the First Element of a Flux](https://www.baeldung.com/java-flux-first-element)

View File

@ -0,0 +1,13 @@
package com.baeldung.camel.exception;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExceptionHandlingSpringApplication {
public static void main(String[] args) {
SpringApplication.run(ExceptionHandlingSpringApplication.class, args);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.camel.exception;
import java.io.IOException;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class ExceptionHandlingWithDoTryRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:start-handling-exception")
.routeId("exception-handling-route")
.doTry()
.process(new IllegalArgumentExceptionThrowingProcessor())
.to("mock:received")
.doCatch(IOException.class, IllegalArgumentException.class)
.to("mock:caught")
.doFinally()
.to("mock:finally")
.end();
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.camel.exception;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ExceptionHandlingWithExceptionClauseRoute extends RouteBuilder {
@Autowired
private ExceptionLoggingProcessor exceptionLogger;
@Override
public void configure() throws Exception {
onException(IllegalArgumentException.class).process(exceptionLogger)
.handled(true)
.to("mock:handled");
from("direct:start-exception-clause")
.routeId("exception-clause-route")
.process(new IllegalArgumentExceptionThrowingProcessor())
.to("mock:received");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.camel.exception;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class ExceptionLoggingProcessor implements Processor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionLoggingProcessor.class);
@Override
public void process(Exchange exchange) throws Exception {
Map<String, Object> headersMap = exchange.getIn().getHeaders();
if (!headersMap.isEmpty()) {
headersMap.entrySet()
.stream()
.forEach(e -> LOGGER.info("Header key [{}] -||- Header value [{}]", e.getKey(), e.getValue()));
} else {
LOGGER.info("Empty header");
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.camel.exception;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class ExceptionThrowingRoute extends RouteBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionThrowingRoute.class);
@Override
public void configure() throws Exception {
from("direct:start-exception")
.routeId("exception-throwing-route")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
LOGGER.error("Exception Thrown");
throw new IllegalArgumentException("An exception happened on purpose");
}
}).to("mock:received");
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.camel.exception;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class IllegalArgumentExceptionThrowingProcessor implements Processor {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionLoggingProcessor.class);
@Override
public void process(Exchange exchange) throws Exception {
LOGGER.error("Exception Thrown");
throw new IllegalArgumentException("An exception happened on purpose");
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.camel.exception;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@CamelSpringBootTest
class ExceptionHandlingWithDoTryRouteUnitTest {
@Autowired
private ProducerTemplate template;
@EndpointInject("mock:caught")
private MockEndpoint mock;
@Test
void whenSendHeaders_thenExceptionRaisedAndHandledSuccessfully() throws Exception {
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start-handling-exception", null, "fruit", "Banana");
mock.assertIsSatisfied();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.camel.exception;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@CamelSpringBootTest
class ExceptionHandlingWithExceptionClauseRouteUnitTest {
@Autowired
private ProducerTemplate template;
@EndpointInject("mock:handled")
private MockEndpoint mock;
@Test
void whenSendHeaders_thenExceptionRaisedAndHandledSuccessfully() throws Exception {
mock.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start-exception-clause", null, "fruit", "Banana");
mock.assertIsSatisfied();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.camel.exception;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@CamelSpringBootTest
class ExceptionThrowingRouteUnitTest {
@Autowired
private ProducerTemplate template;
@Test
void whenSendBody_thenExceptionRaisedSuccessfully() {
CamelContext context = template.getCamelContext();
Exchange exchange = context.getEndpoint("direct:start-exception")
.createExchange(ExchangePattern.InOut);
exchange.getIn().setBody("Hello Baeldung");
Exchange out = template.send("direct:start-exception", exchange);
assertTrue(out.isFailed(), "Should be failed");
assertTrue(out.getException() instanceof IllegalArgumentException, "Should be IllegalArgumentException");
assertEquals("An exception happened on purpose", out.getException().getMessage());
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.camel.exception;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class IllegalArgumentExceptionThrowingProcessorUnitTest {
@Test
void whenProcessed_thenIllegalArgumentExceptionRaisedSuccessfully() {
assertThrows(IllegalArgumentException.class, () -> {
new IllegalArgumentExceptionThrowingProcessor().process(null);
});
}
}

View File

@ -6,4 +6,5 @@ This module contains articles about Spring with Groovy
### Relevant Articles:
- [Building a Simple Web Application with Spring Boot and Groovy](https://www.baeldung.com/spring-boot-groovy-web-app)
- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans)
- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans)
- [Using Groovy in Spring](https://www.baeldung.com/groovy/spring-using-groovy)

View File

@ -8,4 +8,5 @@
- [How to Define a Map in YAML for a POJO?](https://www.baeldung.com/yaml-map-pojo)
- [Using application.yml vs application.properties in Spring Boot](https://www.baeldung.com/spring-boot-yaml-vs-properties)
- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties)
- [IntelliJ Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties)
- [IntelliJ Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties)
- [Log Properties in a Spring Boot Application](https://www.baeldung.com/spring-boot-log-properties)

View File

@ -6,4 +6,5 @@ This module contains articles about reactive Spring 5 WebClient
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles
- [Limiting the Requests per Second With WebClient](https://www.baeldung.com/spring-webclient-limit-requests-per-second)
- More articles: [[<-- prev]](../spring-5-reactive-client)

View File

@ -8,3 +8,4 @@
- [Determine the Execution Time of JUnit Tests](https://www.baeldung.com/junit-test-execution-time)
- [@BeforeAll and @AfterAll in Non-Static Methods](https://www.baeldung.com/java-beforeall-afterall-non-static)
- [The java.lang.NoClassDefFoundError in JUnit](https://www.baeldung.com/junit-noclassdeffounderror)
- [assertAll() vs Multiple Assertions in JUnit5](https://github.com/eugenp/tutorials/tree/master/testing-modules/junit-5)