Friday, 15 June 2018

Sort using lambda exp.


 By using lambda expression we can sort object list using single line of code.

package lambda;

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

public class CompareByName {
    public static void main(String args[]) {
        List<Employee> list = new ArrayList<>();
        list.add(new Employee("sushil",15));
        list.add(new Employee("mittal",25));
        list.add(new Employee("kumar",20));
       
        System.out.println("***********original list*****");
        list.forEach(e-> System.out.println(e));
        System.out.println("***********sort by name******");
        list.sort((e1,e2)-> e1.getName().compareTo(e2.getName()));
        list.forEach(e-> System.out.println(e));
        System.out.println("***********sort by age******");
        list.sort((e1,e2)-> e1.getAge()- e2.getAge());
        list.forEach(e-> System.out.println(e));
    }
   
     static class Employee{
        String name;
        Integer age;
       
        public Employee(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

       
        public String getName() {
            return name;
        }

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

       
        public Integer getAge() {
            return age;
        }

       
        public void setAge(Integer age) {
            this.age = age;
        }


        @Override
        public String toString() {
            return "Employee [name=" + name + ", age=" + age + "]";
        }
       
    }
   
}


output:
 ***********original list*****
Employee [name=sushil, age=15]
Employee [name=mittal, age=25]
Employee [name=kumar, age=20]
***********sort by name******
Employee [name=kumar, age=20]
Employee [name=mittal, age=25]
Employee [name=sushil, age=15]
***********sort by age******
Employee [name=sushil, age=15]
Employee [name=kumar, age=20]
Employee [name=mittal, age=25]



Friday, 8 June 2018

Find Minimum Length Sub Array With Sum K

public class FindMinimumLengthSubArrayWithSumK {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arr = {2,3,1,1,-1,6,4,2,1,8};
        int val = 7;
        findLength(arr, val);
    }
   
   
    public static void findLength(int[] arr, int val) {
        int start=0;
        int end=0;
        int finalCount = arr.length;
        for(int i=0;i<arr.length;i++) {
            int sum = 0;
            int count = 0;
            for(int j=i;j<arr.length;j++) {
                sum+= arr[j];
                count++;
                if(sum==val && count<finalCount) {
                    start = i;
                    end = j;
                    finalCount = count;
                    break;
                }
            }
        }
       
        System.out.println("start::"+start);
        System.out.println("end::"+end);
        System.out.println("final count::"+finalCount);
    }

}

output::
start::6
end::8
final count::3

How to deploy a war file to remote server on tomcat using shell script


Step1: reach to project directory where pom.xml file exist from terminal
Step2: clean mavan using below
mvn clean
Step3: create a war file
mvn package
Step4: remove existing war from webapps tomcat
ssh user@address 'rm /data/apache-tomcat-8.0.29/webapps/warFile'
Step5: remove module exist in webapps tomcat
ssh user@address 'rm -rf moduleName'
Step6: copy war file to wenapps tomcat to remote server
scp /pathOf local dirctory/project.war user@address:/data/apache-tomcat-8.0.29/webapps
echo "deployment done"!

we need to provide some write permission to remote server webapps folder using below:
step1: need to login remote server in teminal
step2: move to directory where you want to provide write access
step3:   chmod -R 777 .

we also need to add our system public key to remote because it will not ask password during deployment:
cat ~/.ssh/id_rsa.pub | ssh user@address 'cat >> .ssh/authorized_keys'


complete script save into a file(deploywar.sh):
mvn clean
mvn package
ssh user@address 'rm /data/apache-tomcat-8.0.29/webapps/warFile' 
ssh user@address 'rm -rf moduleName' 
scp /pathOf local dirctory/project.war user@address:/data/apache-tomcat-8.0.29/webapps 
echo "deployment done"! 

 execute below command from terminal from project location where pom.xml file exist:
/path where script file /deploywar.sh
 

Thursday, 7 June 2018

Find an element in a sorted rotated array


public class FindElementInSortedRotatedArray {

    public static void main(String[] args) {
        int findValue = 98;
        int[] arr = {25,35,45,65,67,78,97,98,2,3,4,7,11,22,23,24};
            boolean bool = checkArrIsRotated(arr);
             if(bool) {
                 int index = findPivot(arr);
                 if(findValue>=arr[0] && findValue<=arr[index]) {
                     //first half
                System.out.println(binarySearch(arr, 0, index, findValue));
                 }else {
                     //second half
                System.out.println(binarySearch(arr, index+1, arr.length-1, findValue));
                 }
             }else {
                 //no rotated arr
                 System.out.println(binarySearch(arr, 0, arr.length-1, findValue));
             }
    }
   
    public static int binarySearch(int[] arr,int start,int end,int findValue) {
       
        int mid = 0;
        while(start<=end) {
            mid = (start+end)/2;
            if(arr[mid]==findValue) {
                return mid;
            }else if(findValue<arr[mid]) {
                end = mid-1;
            }else {
                start = mid+1;
            }
        }
        return -1;
    }
   
    public static int findPivot(int[] arr) {
        int start = 0;
        int end = arr.length-1;
        int mid = 0;
        while(start<=end) {
            mid = (start+end)/2;
            if(arr[mid]>arr[mid+1]) {
                return mid;
            }else if(arr[start]<arr[mid]) {
                start = mid+1;
            }else if(arr[start]>arr[mid]) {
                end = mid-1;
            }
        }
        return -1;
    }
   
    public static boolean checkArrIsRotated(int[] arr){
        if(arr[0]>arr[arr.length-1]) {
            return true;
        }
        return false;
       
    }
}

Sunday, 20 May 2018

How Web.xml work

Question 1: Where does the web.xml fit into things (when is it used/called, and where is it called from)?
Code sample 1:
    <servlet>
    <servlet-name>qrst</servlet-name>
        <display-name>qrst Servlet</display-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
What does the above snippet do (or, what does it cause to happen)? At some point in my web app qrst.jsp gets used; is it the DispatcherServlet that calls qrst.jsp using the servlet name? Else what is the significance of the servlet name? What is load on startup?
Code sample 2:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /someLocation/some-servlet.xml
    </param-value>
</context-param>
Links or explanation of what the above does? I can see from looking at the XML file that it contains bean definitions and I do understand what beans are and how they are used, but I don't know any other details about this and would like to.
Code sample 3:
<servlet>
  <servlet-name>dwr-invoker</servlet-name>
  <display-name>DWR</display-name>
  <servlet-class>
        org.directwebremoting.servlet.DwrServlet
</servlet-class>
    <init-param>
        <param-name>classes</param-name>
        <param-value>
            somepackage.someclass
        </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>
 
 
 
 
Sol:
 
Servlets are JavaEE's idiom for answering HTTP requests. You program the behavior of your application in a Servlet which will respond to a request.
Tomcat is a Servlet container, which means you deploy your application in Tomcat and it will manage all the communication infrastructure for you: it accepts connections, manages database connections(*) and will call upon your servlets to handle incoming requests.
web.xml is part of any JavaEE application, not Spring. Your code sample 1 declares that your app will use an instance of class org.springframework.web.servlet.DispatcherServlet to handle incoming requests.
Although servlets are the basic foundations for JavaEE development, it is not advised to create your own; instead, with Spring, you create MVC controllers. Then the DispatcherServlet will call upon these controllers to handle the requests. It's just another indirection (but a very powerful one!)
is it the DispatcherServlet that calls qrst.jsp using the servlet name?
Not directly. It's just a coincidence that your servlet and the JSP file have the same name.
What is loaded on startup?
Your code sample 2 instructs the DispatcherServlet to load the beans from file /someLocation/some-servlet.xml. If there are controller beans in this file and according to how you configured the url mapping, beans from this file will answer the incoming requests. See the reference.
I believe those init-param elements are just parameters that get set in the servlet's java class
The init-param elements in web.xml are for the servlet class.
The web app somehow "knows" when an AJAX (dwr) call is happening versus when the web app is being loaded for the first time (when its loading for the first time it should use qrst.jsp). How does it know this?
Missing from the question are either the <servlet-mapping> element (found in web.xml), or the url mappings (found in the spring files). These are responsible for deciding whether an URL should be handled by the dispatcher servlet or the dwr servlet.
For instance, with an servlet mapping like below:
<servlet-mapping>
    <servlet-name>qsrt</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>dwr</servlet-name>
    <url-pattern>*.dwr</url-pattern>
</servlet-mapping>
Then all URLs ending in .do will be answered by the dispatcher servlet, and those ending with .dwr will be handled by the dwr servlet. Here's where the names of the servlets are important.
JSP files are a different story. The container will simply use them to handle a URL ending in *.jsp. Do not create your onw servlet mapping for URLs ending in *.jsp. This will only cause headaches. This is probably unspecified behavior.
Edit:
However, the URL in the browser's address bar always looks the same: it would always invoke the qrst servlet
Then it is possible that your servlet-mapping is so broad (something like: <url-pattern>/*</url-pattern>) that it will handle anything you throw at the server and never give a chance for the other servlets to handle it.
Last but not least, when working with DWR or any Ajax technology, install the HttpFox extension for Firefox so you can monitor the Ajax calls of your application.
 
 Ref: https://stackoverflow.com/questions/5837122/can-someone-explain-the-spring-web-xml-file
 
 
http://shengwangi.blogspot.in/2015/08/understand-webxml-in-spring-mvc-project.html 

How does the DispatcherServlet, Resolver and Controllers interact?


When sending a request to your application the following happens:
  • The request arrives at your server (e.g. Tomcat). Depending on the context path in the url the server decides to which application the request belongs.
  • Depending on the url and the servlet mapping in the web.xml file of your application the server knows which servlet should handle the request.
  • The request is passed to the servlet filter chain which can modify or reject requests
  • The servlet takes control over the request. In case of your Spring application the spring Dispatcherservlet receives the request. Now Spring kicks in
  • The request is processed by mvc intercepters preHandle methods
  • The request is mapped to a controller based on the url. The corresponding controller method will be called.
  • Your controller is processing the request. Many different responses can be returned in controllers (jsp, pdf, json, redirects, etc.). For now i assume you want to render a simple jsp view. Result of the controller are two things: a model and a view. The model is a map that contains the data you want to access later in your view. The view at this stage is most of the time a simple string containing a view name.
  • Registered springs mvc interceptors can kick in again using the postHandle method (e.g. for modifying the model)
  • The 'view' result of your controller is resolved to a real View using a ViewResolver. Depending on the ViewResolver the result can be jsp page, a tiles view, a thymeleaf template or many other 'Views'. In your case the ViewResolver resolves a view name (e.g. 'myPage') to a jsp file (e.g. /WEB-INF/jsp/myPage.jsp)
  • The view is rendered using the model data returned by your controller
  • The response with the rendered view will be passed to mvc interceptors again (afterCompletion method)
  • The response leaves the dispatcher servlet. Here ends spring land.
  • The response passes servlet filters again
  • The response is send back to client
 ref: https://stackoverflow.com/questions/14015642/how-does-the-dispatcherservlet-resolver-and-controllers-interact



Sunday, 10 December 2017

Implement Spring Retry in Spring Boot

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.8</version>

</dependency>


<dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
  <version>1.1.5.RELEASE</version>
</dependency>



@EnableRetry
@SpringBootApplication
@ComponentScan(basePackages="com.example")
@EnableAutoConfiguration
public class SampleApplication extends SpringBootServletInitializer{

///.....
}


@Service
public class MyService {

@Retryable(value = {
IndexOutOfBoundsException.class, Exception.class}, maxAttempts = 10, backoff = @Backoff(delay = 5000))
  public void retryWithException() {
System.out.println("running......");
    List<Integer> list  = new ArrayList<>();
    list.get(3);
   

  }


@RequestMapping(value="/testRetry",method=RequestMethod.GET)
public @ResponseBody String retry(){
System.out.println("requestReceived::"+"/retry");
myservice.retryWithException();
return "done";
}



output:

requestReceived::/retry
running......
running......
running......
running......
running......
running......
running......
running......
running......
running......
2017-12-10 19:24:26.924 ERROR 30540 --- [io-8080-exec-17] o.s.boot.web.support.ErrorPageFilter     : Forwarding to error page from request [/testRetry] due to exception [Index: 3, Size: 0]

java.lang.IndexOutOfBoundsException: Index: 3, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653) ~[na:1.8.0_144]
at java.util.ArrayList.get(ArrayList.java:429) ~[na:1.8.0_144]





//recover after retry

//add below in MyService class

 @Recover
  public void recover(IndexOutOfBoundsException exception) {
          System.out.println("ah... catch");

  }



output:


requestReceived::/retry
running......
running......
running......
running......
running......
running......
running......
running......
running......
running......
ah... catch


links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...