lambda expression not working with cucumber - java

Scenario is an interface of Cucumeber.api package.
I want to use this interface to get scenario name.
I am trying:
String string = () - > {
public String getName(Scenario scenario) {
return scenario.getName().toString();
}
});
but it is giving error, what am I missing here?
I am already following several posts (like below), but didn't what wrong I am doing:
Lambda Expression is not working, getting terminated

Related

How to prevent NoSuchElementException using Optional class in Java [duplicate]

This question already has answers here:
java.util.NoSuchElementException: No value present even though we use stream
(2 answers)
Closed 9 months ago.
While filtering through a list of user defined class type using Stream API has been encountered some cases where no element has been found in the list for given condition.
How to prevent exception in such case and handle according to business logic using optional class?
Stream API method looks like :
public static Optional<Policy> getPolicy(ReturnTermPolicy policyType,
String policyKey) {
Optional<Policy> policy = Optional.of(policyType.getPolicies().stream()
.filter(temp -> temp.getPolicyKey().equals(policyKey))
.findFirst().get());
return policy;
}
The calling code looks like that:
Optional<Policy> updatedPolicyOptional = getPolicy(updatedPolies,policykey); // <- exception is being generated here
if (updatedPolicyOptional.isPresent()) {
// business logic
}
else {
// business logic
}
Output :
Verify audit report for update made in TC_08
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
There's no need to extract the result from the optional object just in order to wrap it with an optional again.
It's pointless and will trigger NoSuchElementException if result is not present. To solve the problem, remove the call of get() which both unsafe and redundant in this case:
public static Optional<Policy> getPolicy(ReturnTermPolicy policyType,
String policyKey) {
return policyType.getPolicies().stream()
.filter(temp -> temp.getPolicyKey().equals(policyKey))
.findFirst();
}
In order implement your conditional logic fluently you can make use of Optional.ifPresentOrElse() which expects a Consumer that would be executed if result is present and a Runnable that will be fired in case if optional is empty. Note, this method is accessible with Java 9.
getPolicy(updatedPolies,policykey).ifPresentOrElse(policy -> doSomething(policy),
() -> doSomethingElse());
With Java 8 you can use Optional.ifPresentOrElse() that expects consumer and can cave the if part of conditional logic. And for the case of empty optional, you will need a condition.
Optional<Policy> policy = getPolicy(updatedPolies,policykey);
policy.ifPresentOrElse(policy -> doSomething(policy));
if (!policy.isPresent()) doSomethingElse();
findFirst() already returns an Optional, trying to get() it leads to an error when it is empty. So your function should be:
public static Optional<Policy> getPolicy(ReturnTermPolicy policyType,
String policyKey) {
return = policyType.getPolicies().stream()
.filter(temp -> temp.getPolicyKey().equals(policyKey))
.findFirst();
}
And depending on your Java version (and your business logic) you can use things like:
Java 8.
if (updatedPolicyOptional.isPresent()) {
// business logic
}
else {
// business logic
}
or
T value = updatedPolicyOptional(mapToTFunctor).orElse(someTValue);
Java 9.
updatedPolicyOptional.ifPresentOrElse(someConsumer,someNoParamFunctor);

scala compiling error: Cannot resolve overloaded method 'withTransaction'

I'm new to Scala, and I can't figure out how to solve a compiling error for method withTransaction :
Cannot resolve overloaded method 'withTransaction'
object Global {
def goBootstrap(app: Application) {
Logger.info(" **** start *****")
onGet();
}
def onGet() {
import play.db.jpa.JPA
Logger.info("Cnnection start");
JPA.withTransaction(JPA.em =>
{
val resultsList = JPA.em.createNamedQuery("findCity").setParameter("name", "Boston").getResultList
}
);
}
}
This code snippet is located in a Global.scala file in Play project (version 2.3.X). JPA came from import play.db.jpa.JPA
How can I solve this compiling error?
The error is telling you that there is no method on JPA whose signature matches the parameters you're passing. You are calling JPA.withTransaction( () => Unit).
Looking at the source there are three methods withTransaction with Unit return types:
void withTransaction(Consumer<EntityManager> block);
void withTransaction(String name, Consumer<EntityManager> block);
void withTransaction(String name, boolean readOnly, Consumer<EntityManager> block);
I'm going to assume that you're trying to use the first of those methods. Looking at the docs for Consumer it requires a single argument.
In short, you need to provide an input to your block, something like:
JPA.withTransaction(JPA.em => {
val resultsList = JPA.em.createNamedQuery("findCity").setParameter("name", name).getResultList
});
The problem is that you can't directly instantiate a JPA connection through scala. Also because the play 2.3 framework does not support this feature: https://www.playframework.com/documentation/2.3.x/ScalaHome

Need to extract data from Mono<string> [duplicate]

I have a method which accepts Mono as a param.
All I want is to get the actual String from it. Googled but didn't find answer except calling block() over Mono object but it will make a blocking call so want to avoid using block(). Please suggest other way if possible.
The reason why I need this String is because inside this method I need to call another method say print() with the actual String value.
I understand this is easy but I am new to reactive programming.
Code:
public String getValue(Mono<String> monoString) {
// How to get actual String from param monoString
// and call print(String) method
}
public void print(String str) {
System.out.println(str);
}
Getting a String from a Mono<String> without a blocking call isn't easy, it's impossible. By definition. If the String isn't available yet (which Mono<String> allows), you can't get it except by waiting until it comes in and that's exactly what blocking is.
Instead of "getting a String" you subscribe to the Mono and the Subscriber you pass will get the String when it becomes available (maybe immediately). E.g.
myMono.subscribe(
value -> System.out.println(value),
error -> error.printStackTrace(),
() -> System.out.println("completed without a value")
)
will print the value or error produced by myMono (type of value is String, type of error is Throwable). At https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html you can see other variants of subscribe too.
According to the doc you can do:
String getValue(Mono<String> mono) {
return mono.block();
}
be aware of the blocking call
Finally what worked for me is calling flatMap method like below:
public void getValue(Mono<String> monoString)
{
monoString.flatMap(this::print);
}
What worked for me was the following:
monoString.subscribe(this::print);
Simplest answer is:
String returnVal = mono.block();
This should work
String str = monoString.toProcessor().block();
Better
monoUser.map(User::getId)

How to make JUnit take any Lambda expression

I am using SpringAMQP where I am testing producer method (basically AMQP template) which is like this.
public void send(Message message, Throwable error, String queue, String routingKey) {
this.amqpTemplate.convertAndSend(
RabbitConfiguration.ERROR_EXCHANGE,
RabbitConfiguration.ERROR_ROUTING_KEY,
message,
messageMetaData -> {
messageMetaData.getMessageProperties().getHeaders().put("x-death-reason", error.getMessage());
return messageMetaData;
}
);
}
I am testing this code with following
import static org.hamcrest.Matchers.any;
....
#Test
public void will_create_error_message_if_incorrect_payload_is_given() {
AmqpTemplate amqpTemplate = mock(AmqpTemplate.class);
Throwable throwable = mock(Throwable.class);
when(throwable.getMessage()).thenReturn("first");
when(throwable.getStackTrace()).thenReturn(null);
ErrorMessageProducer errorMessageProducer = new ErrorMessageProducer(amqpTemplate);
Message message = MessageBuilder.withBody("test".getBytes()).build();
verify(amqpTemplate).convertAndSend(
eq(RabbitConfiguration.ERROR_EXCHANGE),
eq(RabbitConfiguration.ERROR_ROUTING_KEY),
any(Message.class),
Mockito.any()
);
}
But I am getting Invalid use of argument matchers! 4 matchers expected, 3 recorded. Is there any way I can test with Lambda or ignore Lambda altogether.
The problem is because you are using wrong any().
verify(amqpTemplate).convertAndSend(
eq(RabbitConfiguration.ERROR_EXCHANGE),
eq(RabbitConfiguration.ERROR_ROUTING_KEY),
any(Message.class),
Mockito.any()
);
Here your 3rd argument using any from org.hamcrest.Matchers.any, however 4th argument uses right Mockito.any(). So 3rd argument isn't detected as a matcher, but is threated like a usual argument.
To check your lambda you should probably use ArgumentCaptor.
ArgumentCaptor<Runnable> argument = ArgumentCaptor.forClass(Runnable.class);
verify(mock).doSomething(any(), argument.capture());
argument.getValue().run();
...verify that lambda called your services...
You can change Runnable to any type of function your lambda actually represents: i.e. Function/Callable.

Custom Sonar Rule To Check For Correct Method Call

I have my custom SonarQube plugIn up and running on a local SonarQube server and it works fine. Now I want to add more stuff to it. I'm interested in coding my own Sonar Rule which checks if the non deprecated constructor is used for one class.
Possible constructor calls:
#Deprecated
public ExampleClass(String a)
{
//deprecated/old/wrong stuff happening
}
public ExampleClass(String a, String b)
{
//correct stuff happening
}
I'm already at the state, that only Method notes will be visited.
Now I'm wondering how can I check which new ExampleClass expression is used?
Found a working solution.
Here's what I did:
set nodesToVisit to Tree.Kind.ASSIGNMENT
check if the expression is Tree.Kind.NEW_CLASS
check if identifier is ExampleClass.class.getSimpleName()
do my argument checks
Code:
AssignmentExpressionTree assignment = (AssignmentExpressionTree) tree;
if ( assignment.expression().is(Tree.Kind.NEW_CLASS) )
{
NewClassTreeImpl expression = (NewClassTreeImpl) assignment.expression();
IdentifierTreeImpl identifier = (IdentifierTreeImpl) expression.identifier();
if ( StringUtils.equals(identifier.name(), ExampleClass.class.getSimpleName()) )
{
ArgumentListTreeImpl arguments = (ArgumentListTreeImpl) expression.arguments();
if ( arguments.size() != 2 )
{
reportIssue(expression, "Use the 2 parameter constructor call when creating new ExampleClass objects!");
}
else if ( StringUtils.indexOfAny(arguments.get(1).symbolType().name(), POSSIBLE_PARAMETER_TYPES) == -1 )
{
reportIssue(expression, "The second parameter must be from type String");
}
}
}
If you find any improvement of my rule, please let me know. Thanks!

Categories

Resources