Limit function in Kotlin - java-8

There is a stream method limit in Java 8:
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class LimitDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("AA","BB","CC","DD","EE");
list.stream().limit(3).forEach(s->System.out.println(s));
}
}
output:
AA
BB
CC
What is the name of analog in Kotlin, or how to do it better by another way?

Based on the documentation:
list.take(3).forEach(::System.out.println)

Related

how to connect to the spring-boot API from my web browser?

I am trying to connect to the code I have wrote through my browser, but unfortunately can not figure out how to do so. I have tried 127.0.0.1/hash but it did not work even though I have build the project using maven build compile. was wondering if someone could tell me what am I doing wrong here.
here is the code :
package com.snhu.sslserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
#SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
#RestController
class ServerController{
public static String calculateHash(String name) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(name.getBytes(StandardCharsets.UTF_8));
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
#RequestMapping("/hash")
public String myHash() throws NoSuchAlgorithmException{
String data = "Hello Kamran Khosravi!";
String hash = calculateHash(data);
return "<p>data:"+data+" : SHA-256 "+" : "+hash;
}
}
you can just replace the port 8080 with respective to your port number which you have in application.properties
Command : spring-boot:run
http://localhost:8080/hash

Mockito when().thenReturn doesn't give expected result

I am new to Junit and Mockito.
Trying to mock one of the object of the class, but it is not working.
The mock method is returning an empty list, due to which test case is getting failed.
This is the code which I have written.
Junit Test Class : Here I have mocked the object and method to return an Arraylist, but when the code is executed this mock method is returning an empty list due to which test case is getting failed.
package com.business;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.data.api.ToDoService;
public class TodoBusinessImplMockTest {
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void testRetrieveTodosRelatedToSpringUsingMock()
{
ToDoService todoServiceMock = mock(ToDoService.class);
List<String> todoList=Arrays.asList("Learn Spring MVC", "Learn Spring","Learn to Dance");
Mockito.when(todoServiceMock.retrieveTodos("Dummy")).thenReturn(todoList);
TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoServiceMock);
List<String> todos = todoBusinessImpl.retrieveTodosRelatedToSpring("Ranga");
assertEquals(2, todos.size());
}
}
Interface : ToDoService.java
package com.data.api;
import java.util.List;
public interface ToDoService {
public List<String> retrieveTodos(String s);
}
TodoBusinessImpl.java
package com.business;
import java.util.ArrayList;
import java.util.List;
import com.data.api.ToDoService;
public class TodoBusinessImpl {
private ToDoService todoService;
TodoBusinessImpl(ToDoService todoService) {
this.todoService = todoService;
}
public List<String> retrieveTodosRelatedToSpring(String s) {
List<String> filteredTodos = new ArrayList<String>();
List<String> allTodos = todoService.retrieveTodos(s);
for (String todo : allTodos) {
if (todo.contains("Spring")) {
filteredTodos.add(todo);
}
}
return filteredTodos;
}
}
Your spec says:
Mockito.when(todoServiceMock.retrieveTodos("Dummy")).thenReturn(todoList);
but your call uses:
todoBusinessImpl.retrieveTodosRelatedToSpring("Ranga");
"Ranga" isn't "Dummy", therefore your spec isn't matched; therefore mockito returns the default result (which would be an empty list).
Try replacing the "Dummy" in Mockito.when(todoServiceMock.retrieveTodos("Dummy")).thenReturn(todoList); with anyString() (import static org.mockito.ArgumentMatchers.anyString;). This did the trick for me.

The type EnableBinding is deprecated, The type StreamListener is deprecated - Spring Cloud Stream

I am using Spring Boot version 2.4.2 and doing Spring Cloud Stream and Spring Integration using #InboundChannelAdapter .
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.integration.annotation.InboundChannelAdapter;
#EnableBinding(value = Source.class)
public class TransactionPublisher {
#InboundChannelAdapter(channel = Source.OUTPUT)
public String sendTransactionDetails() {
return "{name:\"T1\", amount: \"1000\", transactionFor : \"Purchase\"}";
}
}
RabbitmqReceiverApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
#EnableBinding(value = Sink.class)
#SpringBootApplication
public class RabbitmqReceiverApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitmqReceiverApplication.class, args);
}
#StreamListener(Sink.INPUT)
public void log(String message) {
System.out.println(message);
}
}
What could be the alternative ? how to refactor the above code then? A lot of things are happening with the pace getting difficult to understand whats coming and whats going off ?
See the documentation.
e.g. On the consumer side...
#Bean
Consumer<String> log() {
return str -> {
System.out.println(str);
};
}
The binding name is log-in-0.
On the producer side, it's a Supplier<String> bean with binding name sendTransactionDetails-out-0.

Type mismatch: cannot convert from SpringBootApplication to Annotation

I have have recently started to learn SpringBoot. But I am facing with this problem.
Can someone help me regarding this.
Thanks in advance.
My Code Snippet:
package com.example.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootApplication{
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
This is the fixed code: Here I Changes the public class name :
package com.example.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootAppl {
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(SpringBootAppl.class, args);
}
}

how to overload Spring PropertyPlaceholderConfigurer's processProperties() method

My requirement is as given below :
"we have a load a big properties file using Spring and then loop through it .
While looping we have to check the very first column of properties file for some particular values.
As soon as we find those values we have to print that value and continue this printing process till the very end."
For this i finally able to build a code like below :
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {
private static Map<String, String> propertiesMap;
private static String keyToFind = "myProperty";
// Default as in PropertyPlaceholderConfigurer
private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;
#Override
public void setSystemPropertiesMode(int systemPropertiesMode) {
super.setSystemPropertiesMode(systemPropertiesMode);
springSystemPropertiesMode = systemPropertiesMode;
}
#Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
super.processProperties(beanFactory, props);
for (Object key : props.keySet()) {
String keyStr = key.toString();
if(keyStr.equals(keyToFind)) {
String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
System.out.println(valueStr);
}
}
}
public String getProperty(String name) {
return propertiesMap.get(name).toString();
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
((ConfigurableApplicationContext)context).close();
}
}
It is working fine but i am finding a nicer way of doing this if i can overload processProperties() and can pass String keyTofind to this method rather than defining it globally.
Any suggestion is welcome.
Thanks.
Alternatively to your solution, you could implement a custom property source. I believe this is the mechanism Spring has intended for proprietary "source parsing logic".
The subject is not terribly well documented on the web, but this article gives some insight: http://scottfrederick.cfapps.io/blog/2012/05/22/Custom-PropertySource-in-Spring-3.1---Part-1/

Resources