<repo_name>kumararvind269/practice<file_sep>/java8/lambdaExpression/LambdaDemo1.java
package java8.lambdaExpression;

import java.util.Arrays;
import java.util.Collection;

public class LambdaDemo1 {

	public static void main(String[] args) {
		
		String[] strArr = {"qaz","edced","ujnd","mnbqsc","as","uefvxcvdf"};
		
		System.out.println("Original Array:" + Arrays.asList(strArr));
		
		Arrays.sort(strArr,(x,y)->x.compareTo(y));   //Arrays.sort(strArr,String::compareTo);
		
		System.out.println("Sorted Array:" + Arrays.asList(strArr));
		
		Arrays.sort(strArr,(x,y)->y.length()-x.length());
		
		System.out.println("Array sorted via length:" + Arrays.asList(strArr));

	}

}
<file_sep>/java8/lambdaExpression/ErrorHandingLambda.java
package java8.lambdaExpression;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class ErrorHandingLambda {

	public static void main(String[] args) {

		int[] arr = {1,3,6,3,2,0,3,4};
		List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

		// list.forEach(x-> System.out.println(50/x));

		   list.forEach(ConsumerWrapper(x-> System.out.println(50/x)));


	}

	public static Consumer<Integer> ConsumerWrapper(Consumer<Integer> con){
		return i -> {
			try {
				con.accept(i);
			}catch(Exception ex){
				System.out.println(ex);
			}	
		};
	}
}
<file_sep>/stock-manager-app/user-stock-service/src/main/java/com/stockmanager/userstockservice/service/StockDetailService.java
package com.stockmanager.userstockservice.service;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.stockmanager.userstockservice.model.Stock;
import com.stockmanager.userstockservice.model.UserStock;
import com.stockmanager.userstockservice.model.UserStockDetail;
import com.stockmanager.userstockservice.repo.StockDetailRepository;

import rx.Observable;
import rx.schedulers.Schedulers;

@Service
@SuppressWarnings("deprecation")
public class StockDetailService {

	@Autowired
	StockDetailRepository stockRepo;

	@Autowired
	StockPriceService stockPriceService;

	public Observable<Stock> getStockPrice(String stock) {
		return stockPriceService.getStockPrice(stock);
	}

	public UserStock save(UserStock sd) {
		return stockRepo.save(sd);
	}

	public UserStock findByUserNameAndStockName(String user, String stock) {
		return stockRepo.findByUserNameAndStockName(user,stock);
	}

	public Observable<UserStockDetail> getUserStockDetail(String userName) {
		return Observable.<UserStockDetail>create(s->{
			UserStockDetail usd = new UserStockDetail();
			usd.setUser(userName);
			List<UserStock> list = stockRepo.findByUserName(userName);
			list.stream().map(stock ->{ 

				Stock temp = stockPriceService.getStockPrice(stock.getStockName()).toBlocking().first();
				if(temp!=null)
					usd.getStock().add(new UserStockDetail.StockDetail(stock.getStockName(),stock.getStockPrice(),
							temp.getPrice()));

				return usd;
			}).collect(Collectors.toList());
			s.onNext(usd);
			s.onCompleted();
		}).subscribeOn(Schedulers.newThread());
	}

}

<file_sep>/rxjavaDemo/RxJavaDemo2.java
package rxjavaDemo;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Single;

public class RxJavaDemo2 {

	public static void main(String[] args) {

		System.out.println("scan");
		String[] letters = {"a", "b", "c"};
		Observable.from(letters)
		.scan(new StringBuilder(), StringBuilder::append)
		.subscribe(total -> System.out.println(total.toString()));

		System.out.println("groupBy");
		Observable.just(1,2,3,4,5,6,7,8,9,10)
		.groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
		.subscribe(group ->
		group.subscribe((number) -> {
			if (group.getKey().equals("EVEN")) {
				System.out.println("Even: "+ number);
			} else {
				System.out.println("odd: "+ number);
			}
		})
				);

		System.out.println("fiter");
		Observable.just(1,2,3,4,5,6,7,8,9,10)
		.filter(i -> (i % 2 == 1))
		.subscribe(i -> System.out.println(i));

		System.out.println("takeWhile");
		Observable.just(1,2,3,4,5,6,7,8,9,10)
		.takeWhile(i -> i < 5)
		.subscribe(i -> System.out.println(i));


		String[] result = {"X"};
	    Observable<Long> obser
		= Observable.interval(200, TimeUnit.MILLISECONDS).limit(10);
	    obser.subscribe(i -> result[0] += i+" ");
		try {
			Thread.sleep(1500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(result[0]);
		
		String[] result1 = {""};
		Single<String> single = Observable.just("Hello")
		  .toSingle()
		  .doOnSuccess(i -> result1[0] += i)
		  .doOnError(error -> {
		      throw new RuntimeException(error.getMessage());
		  });
		single.subscribe(i->System.out.println(i));
		
		
	}
}
<file_sep>/stock-manager-app/user-stock-service/src/main/java/com/stockmanager/userstockservice/service/StockPriceService.java
package com.stockmanager.userstockservice.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.stockmanager.userstockservice.model.Stock;
import com.stockmanager.userstockservice.repo.StockDetailRepository;

import rx.Observable;
import rx.schedulers.Schedulers;

@Service
@SuppressWarnings("deprecation")
public class StockPriceService {

	@Autowired
	StockDetailRepository stockRepo;

	@Autowired
	RestTemplate rest;

	public static final String STOCK_URI = "http://localhost:8000/stock/";

	public static final String STOCK_BCKUP_URI = "http://localhost:8001/stock/";

	public static final Stock[] stArray= {new Stock(10001,"A1",111), new Stock(10002,"A2",222)
			,new Stock(10003,"A3",333) ,new Stock(10004,"A4",444)};

	@HystrixCommand(fallbackMethod="getStockPriceAlt", groupKey="StockDetailService" 
			, commandKey="getStockPrice",threadPoolKey="helloThread",
			commandProperties = {
					@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"),
					@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "4"),
					@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "60000"),
					@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")
	}, threadPoolProperties = {
			@HystrixProperty(name = "coreSize", value = "30")})
	public Observable<Stock> getStockPrice(String stock) {
		return Observable.<Stock>create(s->{
			ResponseEntity<Stock> entity = null;
			try {
				entity = rest.exchange(STOCK_URI+stock,HttpMethod.GET,null,Stock.class);
			}catch(Exception e) {
				s.onError(e);
			}
			if(entity.getBody()!=null)
				s.onNext(entity.getBody());
			else
				s.onNext(null);
			s.onCompleted();
		}).subscribeOn(Schedulers.newThread());
	}

	public Observable<Stock> getStockPriceAlt(String stock) {
		/*return Observable.<Stock>create(s->{
			ResponseEntity<Stock> entity = null;
			try {
				entity = rest.exchange(STOCK_BCKUP_URI+stock,HttpMethod.GET,null,Stock.class);
			}catch(Exception e) {
				s.onError(e);
			}
			if(entity.getBody()!=null)
				s.onNext(entity.getBody());
			else
				s.onNext(null);
			s.onCompleted();
		}).subscribeOn(Schedulers.newThread());*/
		return Observable.from(stArray).filter(x-> x.getName().equals(stock));
	}

}
<file_sep>/java8/functionalInterface/Condition.java
package java8.functionalInterface;

@FunctionalInterface
public interface Condition<T> {
	
	public boolean check(T t);

}
<file_sep>/java8/stream/ParallelStreamDemo.java
package java8.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ParallelStreamDemo {

	public static void main(String...strings) {

		long startTime = System.currentTimeMillis();
		long StreamSum = StreamSum(1000L);
		long endTime = System.currentTimeMillis();
		System.out.println("Stream sum:"+StreamSum+" total time: "+(endTime-startTime));

		startTime = System.currentTimeMillis();
		long ParaStreamSum = ParaStreamSum(1000L);
		endTime = System.currentTimeMillis();
		System.out.println("Parallel Stream sum:"+ParaStreamSum+" total time: "+(endTime-startTime));
		
		List<Long> list = Stream.iterate(1L,i->i+1).limit(10).collect(Collectors.toList());
		Spliterator<Long> s = list.spliterator();
	    System.out.println("Total Size: "+s.estimateSize());
	    
	   // while(s.tryAdvance(x->System.out.print(x+" ") ));
	    s.tryAdvance(x->System.out.print(x+" ") );
	    s.tryAdvance(x->System.out.print(x+" ") );
	    System.out.println("\nSize after two iteration "+s.estimateSize());
	    
	    Spliterator<Long> s1 = s.trySplit();
	    System.out.println("Size after split 1st: "+ s.estimateSize());
	    System.out.println("Size after split 2nd: "+s1.estimateSize());
	    
	    while(s.tryAdvance(x->System.out.print(x+" ") ));
	    System.out.println();
	    while(s1.tryAdvance(x->System.out.print(x+" ") ));
		
	}

	private static long StreamSum(Long num) {
		Long temp= Stream.iterate(1L,i->i+1).limit(num).reduce(0L,(i,j)->i+j);
		return temp;
	}

	private static long ParaStreamSum(Long num) {
		Long temp= Stream.iterate(1L,i->i+1).limit(num).parallel().reduce(0L,(i,j)->i+j);
		return temp;
	}


}
<file_sep>/stock-manager-app/user-stock-service/src/main/resources/data.sql
insert into USER_TBL (id,name)
values(20001,'USER1');

insert into USER_TBL (id,name)
values(20002,'USER2');

insert into USER_TBL (id,name)
values(20003,'USER3');
<file_sep>/java8/stream/StreamDemo2.java
package java8.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import org.omg.Messaging.SyncScopeHelper;

public class StreamDemo2 {

	public static void main(String[] args) {

		List<Integer> numbers = Arrays.asList(1, 2, 8, 4, 5,6);
		List<Integer> squares = numbers.stream().map(n -> n * n).collect(Collectors.toList());
		System.out.println(squares);

		//Integer max1 = numbers.stream().reduce(0,(x,y)->x>y?x:y);
		Integer max = numbers.stream().reduce(0,Integer::max);

		System.out.println(max);

		int sum = numbers.parallelStream().reduce(0, Integer::sum);
		System.out.println(sum);

		List<Integer> numbers1 = Arrays.asList(1, 2, 3);
		List<Integer> numbers2 = Arrays.asList(3, 4);

		List<int[]> x = numbers1.stream().flatMap(i -> numbers2.stream()
				.map(j -> new int[] {i,j})).collect(Collectors.toList());
		x.forEach(x1->System.out.println(Arrays.toString(x1)));

		IntStream intStrm = Arrays.stream(new int[] {1,2,3});

		IntStream.range(0,100).filter(i -> i%7==0).forEach((i)->System.out.print(i+" "));


		String[][] twoArr = {{"sdfsd","sdfsd"}};
		Stream<String[]> StrmTwoArr = Stream.of(twoArr);
		Stream<String> vv = StrmTwoArr.flatMap(qq->Stream.of(qq));
		vv.forEach(System.out::print);
		System.out.println();

		Stream.iterate(new int[] {0,1},t -> new int[] {t[1],t[1]+t[0]}).
										limit(10).forEach(t->System.out.print(t[0]+" "));;

	}

}
<file_sep>/stock-manager-app/user-stock-service/src/main/java/com/stockmanager/userstockservice/repo/StockDetailRepository.java
package com.stockmanager.userstockservice.repo;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.stockmanager.userstockservice.model.UserStock;

public interface StockDetailRepository extends JpaRepository<UserStock, Integer> {

	UserStock findByUserNameAndStockName(String user, String stock);

	List<UserStock> findByUserName(String userName);

}
<file_sep>/java8/lambdaExpression/LambdaDemo2.java
package java8.lambdaExpression;

public class LambdaDemo2 {
	
	public static void main(String[] arg) {
	
	 MathOperation addition = (int a, int b) -> a + b;
		
     MathOperation subtraction = (a, b) -> a - b;
		
     MathOperation multiplication = (int a, int b) -> { return a * b; };
		
     MathOperation division = (int a, int b) -> a / b ;
		
     System.out.println("15 + 5 = " + operate(15, 5, addition));
     System.out.println("15 - 5 = " + operate(15, 5, subtraction));
     System.out.println("15 x 5 = " + operate(15, 5, multiplication));
     System.out.println("15 / 5 = " + operate(15, 5, division));
  }
	
  private static int operate(int a, int b, MathOperation mathOperation) {
     return mathOperation.operation(a, b);
  }

}
<file_sep>/stock-manager-app/user-stock-service/src/test/java/com/stockmanager/userstockservice/UserStockServiceApplicationTests.java
package com.stockmanager.userstockservice;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.stockmanager.userstockservice.controller.StockDetailController;
import com.stockmanager.userstockservice.model.Stock;
import com.stockmanager.userstockservice.service.StockDetailService;

import rx.Observable;
import rx.observers.TestSubscriber;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserStockServiceApplicationTests {

	@MockBean
	StockDetailService sds;
	
	@Autowired
	StockDetailController sdc;
	
	
	@Test
	public void contextLoads() {
		Mockito.when(sds.getStockPrice("AAA")).thenReturn(Observable.just(new Stock(111,"AAA",222)));
		
		TestSubscriber<Stock> testSubscriber = new TestSubscriber<>();
		   sds.getStockPrice("AAA").subscribe(testSubscriber);
		   testSubscriber.assertNoErrors();
		   testSubscriber.assertValue(new Stock(111,"AAA",222));
	}

}
<file_sep>/stock-manager-app/user-stock-service/src/main/java/com/stockmanager/userstockservice/service/UserService.java
package com.stockmanager.userstockservice.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.stockmanager.userstockservice.exception.CustomException;
import com.stockmanager.userstockservice.model.User;
import com.stockmanager.userstockservice.repo.UserRepository;
import rx.Observable;
import rx.schedulers.Schedulers;

@Service
@SuppressWarnings("deprecation")
public class UserService {

	@Autowired
	UserRepository UserRepo;

	public Observable<List<User>> getAll(){
		return Observable.<List<User>>create(s->{
			List<User> list = UserRepo.findAll();
			if(!list.isEmpty())
				s.onNext(list);
			else
				s.onError(new CustomException("No user Found",HttpStatus.NOT_FOUND));
			s.onCompleted();
		}).subscribeOn(Schedulers.newThread());
	}

	public Observable<User> getByName(String name) {
		return Observable.<User>create(s->{
			User user = UserRepo.findByName(name);
			if(user!=null)
				s.onNext(user);
			else
				s.onError(new CustomException("User doesn't exist",HttpStatus.NOT_FOUND));
			s.onCompleted();
		}).subscribeOn(Schedulers.newThread());
	}

	public User save(User user) {
		return UserRepo.save(user);		
	}


	public void delete(User user) {
		UserRepo.delete(user);
	}
	
}
<file_sep>/java8/defaultAndStatic/FourWheeler.java
package java8.defaultAndStatic;

public interface FourWheeler {


	default void print() {
		System.out.println("Inside FourWheeler print");
	}

	static void blowHorn() {
		System.out.println("inside FourWheeler blowHorn");
	}

	public void type();

}
<file_sep>/stock-manager-app/user-stock-service/src/main/java/com/stockmanager/userstockservice/controller/StockDetailController.java
package com.stockmanager.userstockservice.controller;

import java.util.List;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.util.UriComponentsBuilder;

import com.stockmanager.userstockservice.exception.CustomException;
import com.stockmanager.userstockservice.model.Stock;
import com.stockmanager.userstockservice.model.UserStock;
import com.stockmanager.userstockservice.model.UserStockDetail;
import com.stockmanager.userstockservice.model.User;
import com.stockmanager.userstockservice.service.StockDetailService;
import com.stockmanager.userstockservice.service.UserService;

@RestController
@RequestMapping(value="/stockservice/")
public class StockDetailController {

	@Autowired
	StockDetailService stockService;

	@Autowired
	UserService userService;

	@RequestMapping(value = "/stockprice/{name}" , method=RequestMethod.GET)
	public DeferredResult<ResponseEntity<Stock>> getStockPrice(@PathVariable("name") String name) {

		DeferredResult<ResponseEntity<Stock>> result = new DeferredResult<>();
		stockService.getStockPrice(name).
		subscribe(stock -> {
			result.setResult(new ResponseEntity<Stock>(stock,HttpStatus.OK));
		}, e-> result.setErrorResult(e)	
				);
		return result;
	}

	@RequestMapping(value = "/buystock/{user}/{stock}/{quantity}" , method=RequestMethod.GET)
	public ResponseEntity<UserStock> buyStock(@PathVariable("user") String userName
			,@PathVariable("stock") String stockName,@PathVariable("quantity") int quantity) {

		if(quantity<=0)
			throw new CustomException("Quantity Should be greater than 0",HttpStatus.CONFLICT);

		User user = userService.getByName(userName).toBlocking().first();
		Stock stock ;
		try {
			stock = stockService.getStockPrice(stockName).toBlocking().first();
		}catch(NoSuchElementException ex){
			throw new CustomException("No Stock Found with Name: "+stockName,HttpStatus.CONFLICT);
		}

		UserStock sd = stockService.findByUserNameAndStockName(user.getName(),stock.getName());
		if(sd==null)
			sd = new UserStock(-1, user.getName(),stock.getName(), stock.getPrice(), quantity);
		else{
			sd.setStockPrice(stock.getPrice());
			sd.setStockQuantity(quantity);
		}
		sd = stockService.save(sd);		
		return new ResponseEntity<UserStock>(sd,HttpStatus.CREATED);
	}

	@RequestMapping(value = "/viewStock/{user}" , method=RequestMethod.GET)
	public DeferredResult<ResponseEntity<UserStockDetail>> viewStock(@PathVariable("user") String userName) {

		User user = userService.getByName(userName).toBlocking().first();
		DeferredResult<ResponseEntity<UserStockDetail>> result = new DeferredResult<>();
		stockService.getUserStockDetail(userName).
		subscribe(userStockDetail -> {
			result.setResult(new ResponseEntity<UserStockDetail>(userStockDetail,HttpStatus.OK));
		}, e-> result.setErrorResult(e)	
				);
		return result;
	}


}
<file_sep>/stock-manager-app/stock-price-service/src/main/resources/data.sql
insert into STOCK_TBL (id,name,price)
values(10001,'A1', 111);

insert into STOCK_TBL (id,name,price)
values(10002,'A2', 222);

insert into STOCK_TBL (id,name,price)
values(10003,'A3', 333);

insert into STOCK_TBL (id,name,price)
values(10004,'A4', 444);
<file_sep>/java8/optional/Car.java
package java8.optional;

import java.util.Optional;
import java8.optional.Insurance;

public class Car {

	
	private String carName;
	
	private Optional<Insurance> insurance;

	public Car( String carName, Optional<Insurance> insurance) {
		super();
		this.carName = carName;
		this.insurance = insurance;
	}

	public String getCarName() {
		return carName;
	}

	public void setCarName(String carName) {
		this.carName = carName;
	}

	public Optional<Insurance> getInsurance() {
		return insurance;
	}

	public void setInsurance(Optional<Insurance> insurance) {
		this.insurance = insurance;
	}
	
	
		
}
<file_sep>/java8/stream/StreamDemo1.java
package java8.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo1 {

	public static void main(String[] args) {

		List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);

		numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

		List<String> str = Arrays.asList("hello","world","hi");

		//Stream<String> str1 = str.stream().flatMap(x->Arrays.stream(x.split(""))).distinct();
		Stream<String> str1 = str.stream().map(x -> x.split("")).flatMap(x->Arrays.stream(x)).distinct();
		List<String> str2 = str1.collect(Collectors.toList());

		System.out.println(str2);
		
		System.out.println(str.stream().allMatch(x->x.equals("hi")));
		System.out.println(str.stream().anyMatch(x->x.equals("hi")));
		System.out.println(str.stream().noneMatch(x->x.equals("h")));
		System.out.println(str.stream().findAny().get());
		
		System.out.println(str2.stream().sorted(String::compareTo).limit(5).skip(2).collect(Collectors.toList()));
		
		List<Integer> lt1 = Arrays.asList(1,4,44,2,7,0,4,75,3,23);
		
		System.out.println(lt1.stream().filter(x -> x>4).collect(Collectors.toList()));
		
		System.out.println(lt1.stream().reduce(0,(x,y)->x+y));
		

	}

}
<file_sep>/stock-manager-app/stock-price-service/src/main/java/com/stockmanager/stockpriceservice/model/Stock.java
package com.stockmanager.stockpriceservice.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author NKT
 *
 */

@Entity()
@Table(name="STOCK_TBL")
public class Stock {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int id;
	
	@Column(unique=true)
	private String name;
	
	@Column
	private int price;

	
	public Stock() {
		super();
	}


	public Stock(int id, String name, int price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public int getPrice() {
		return price;
	}


	public void setPrice(int price) {
		this.price = price;
	}

	
}
