I have two CompletableFutures and one combining them as below and they are getting executed on server start up and not when I call them. How do I make them execute when I call them?
#Service
public class testFutures {
public String runFutures(){
return combinedFuture;
}
CompletableFuture<String> future1(){
return CompletableFuture.supplyAsync(() -> {
System.out.println("Future 1");
return "Future 1"
});
}
CompletableFuture<String> future2(){
return CompletableFuture.supplyAsync(() -> {
System.out.println("Future 2");
return "Future 2";
});
}
CompletableFuture<String> combinedFuture = future1().thenCombine(future2(),
(future1, future2) -> {
System.out.println("Combined Future);
return "Combined Future";
});
}
Related
I am new to spring webclient and i'm trying to write test case for failure case for onstatus method.
Logic here
private Function<ClientResponse, Mono<? extends Throwable>> errorStrategy() {
return response -> {
return response.bodyToMono(Errors.class).flatMap(errorResponse -> {
log.info("Track Error ----> {}", errorResponse.getErrorCode());
Errors errors = new Errors(errorResponse.getErrorMsg());
return Mono.error(errors);
});
};
}
public Mono<EnterpriseSearchResponse> getCustomerID(EnterpriseSearchRequest searchRequest) {
Mono<EnterpriseSearchResponse> response = this.client.method(HttpMethod.GET)
.uri(enterpriseSearchURI + enterpriseSearchContext)
.header("Authorization", "Bearer " + enterpriseSearchAuthToken)
.accept(new MediaType[] { MediaType.APPLICATION_JSON }).bodyValue(searchRequest).retrieve()
.onStatus(HttpStatus::is5xxServerError, errorStrategy())
.onStatus(HttpStatus::is4xxClientError, errorStrategy()).bodyToMono(EnterpriseSearchResponse.class);
return response;
}
I want to write test case for errorStategy method.
can someone suggest how to achieve that?
In my android project, I use objectbox as database, if I insert with lock and query without lock, is there any side effect ? such as crash and so on.
fun query(uniqueId: String = ""): MutableList<T> {
if (box.store.isClosed) return mutableListOf()
val query = box.query()
withQueryBuilder(query, uniqueId)
//开始
return query.build().find()
}
private fun putInner(entity: T): Long {
synchronized(box.store) {
if (box.store.isClosed) return -1
if (entity.unique.isBlank()) {
entity.unique = entity.providerUnique()
}
entity.timestamp = System.currentTimeMillis()
return try {
box.put(entity).let { id -> entity.id = id }
entity.id
} catch (ex: Exception) {
-1
}
}
}
Hello i have this method
private ActionResult CheckResult(ReactivationResponse result, GlobalObject globalInfo)
{
if (result == null)
{
return RedirectToAction("Failed", "Redirect", new { errorCode = 1014 });
}
else if (!result.IsReactivationSuccess && !result.IsOrderImported && !globalInfo.MemberInfo.IsWinbackAplicable)
{
return RedirectToAction("Failed", "Redirect", new { errorCode = 201 });
}
else if (!result.IsReactivationSuccess && result.Errors.Any())
{
if (result.Errors.Any(e => e.Message == "ApprovalPending"))
{
return View("Pending");
}
return RedirectToAction("Failed", "Redirect", new { errorCode = result.Errors.FirstOrDefault().StackTrace });
}
return null;
}
inside another Action Result
public ActionResult OtherMethod()
{
CheckResult(result, globalInfo);
//More code
return View()
}
I'm trying to redirect the code according to the result, and in case it doesn't apply, that the app continue and return the normal view.
But it doesn't work, if any of the if statements applies it doesn't redirect to anywhere, it continues with the normal viw.
I also tried to put a return before the method
return CheckResult(result, globalInfo);
and it works except if my method returns null, then it doesn't continue with the app.
I want to evaluate if it needs to redirect or if it should continue
I'm trying to write a unit test for getUser() function:
fun getUser(userId:Int) {
// some code...
launchDataOperation { api.getUser(userId) }
}
The issue I can see (but don't know how to resolve in a clean way) is launchDataOperation(...) creates a coroutine to call suspend function api.getUser:
fun launchDataOperation(block: suspend () -> Unit): Job {
return coroutineScope.launch {
try {
setLoading(true)
block()
} catch (error: NetworkConnectionException) {
setError(Errors.NETWORK_CONNECTION_ERROR)
} catch (error: DataOperationException) {
setMessage(error.getErrors())
} finally {
setLoading(false)
}
}
}
This is my failing test:
#Test
fun `error message is displayed if api error occurred`() {
val exception = DataOperationException(listOf("FATAL ERROR"))
runBlocking {
`when`(api.getUser(anyInt())).thenAnswer { throw exception }
subject.getUser(userId)
// execution fails if the below line is commented
// this is not the correct way to wait for other coroutines
delay(500) // wait for 500ms till the other coroutines finish
assertThat(subject.messages.value).isEqualTo(exception.getErrors())
}
}
I have 2 methods:
private static async Task<T> GetInfoAsync<T>(MyClient service, Func<Task<T>> funcAsync, string resultText)
{
var result = default(T);
if (service != null) {
try {
service.Open();
result = await funcAsync();
service.Close();
Console.WriteLine(resultText);
} catch (Exception ex) {
service.Abort();
}
}
return result;
}
private static async Task<T> GetInfoAsync<T>(MyClient service, Func<string,Task<T>> funcAsync, string resultText, string param)
{
var result=default(T);
if (service != null) {
try {
service.Open();
result = await funcAsync(param);
service.Close();
Console.WriteLine(resultText);
} catch (Exception ex) {
service.Abort();
}
}
return result;
}
Is is possible to create 1 method for 2 functions?
Something like
"private static async Task GetInfoAsync(MyClient service, Something??, string resultText, string param)"
No, but in general you can do a partial function (see for example http://blogs.msdn.com/b/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx) that, given a function with a parameter, calls it with a fixed value for that parameter.
// The original function
Func<string, Task<T>> fullFunction = x => ...;
// The partial function
string param = "...";
Func<Task<T>> partialFunction = () => fullFunction(param);
So it would be the caller of GetInfoAsync that would need to create this partialFunction and pass it to GetInfoAsync.