Showing posts with label MicroServices. Show all posts
Showing posts with label MicroServices. Show all posts

October 01, 2018

Solution for upload Large File in a Spring Boot


Default browser/postman allows 1MB files for uploading, if want to upload more then 1MB, we need to do below configurations based spring-boot versions

Exception while uploading file/image:
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (1025607423) exceeds the configured maximum (104857600)

Solution for spring-boot 1.5.12:
For org.springframework.boot spring-boot-starter-parent 1.5.12.RELEASE;
application.yml
===
spring:
  http:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

===   
Reference:
https://javadeveloperzone.com/common-error/org-apache-tomcat-util-http-fileupload-fileuploadbasefilesizelimitexceededexception-field-file-exceeds-maximum-permitted-size-n-bytes/
https://dzone.com/articles/upload-large-file-in-spring-boot-2-application-usi
https://stackoverflow.com/questions/34177873/max-limit-of-multipartfile-in-spring-boot
https://grokonez.com/java-integration/upload-multipartfile-spring-boot
Read more ...

December 28, 2017

How to handle "java net unknownhostexception" exception

While creating restTemplate, we have to configure proxy settings like:

@Bean
RestTemplate restTemplate() {
final String username = "xxxxx";
final String password = "XXXXXX";
final String proxyUrl = "XXXX.com";
final int port = 8080;

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxyUrl, port),
new UsernamePasswordCredentials(username, password));
HttpHost myProxy = new HttpHost(proxyUrl, port);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.setProxy(myProxy).setDefaultCredentialsProvider(credsProvider).disableCookieManagement();
HttpClient httpClient = clientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);      
return new RestTemplate(factory);
}
Driver program:
String getUrl = "https://XXXX/XXXX";//ex: "http://localhost:8080/get?id=1&name='Dasu'&age=30";
ResponseEntity getResponse = restTemplate().getForEntity(getUrl, Object.class);
if (getResponse.getBody() != null) {
System.out.println("Response for Get Request: " + getResponse.getBody().toString());
} else {
System.out.println("Response for Get Request: NULL");
}
Read more ...

December 08, 2017

Spring Boot Interview Questions


In this post, we will look at Spring Boot Interview questions. Examples are provided with an explanation. 

Q: What is Spring Boot?
A: Over the years spring has become more and more complex as new functionalities have been added. Just visit the page-https://spring.io/projects and we will see all the spring projects we can use in our application for different functionalities. If one has to start a new spring project we have to add build path or add maven dependencies, configure application server, add spring configuration. So a lot of effort is required to start a new spring project as we have to currently do everything from scratch. Spring Boot is the solution to this problem. Spring boot has been built on top of existing spring framework. Using spring boot we avoid all the boilerplate code and configurations that we had to do previously. Spring boot thus helps us use the existing Spring functionalities more robustly and with minimum efforts.
More details and miscellaneous examples 

Q: What are advantages of Spring Boot?
A:
 The advantages of Spring Boot are
  • Reduce Development, Testing time and efforts.
  • Use of JavaConfig helps avoid usage of XML.
  • Avoid lots of maven imports and the various version conflicts.
  • Provide Opinionated Development approach.
  • Quick start to development by providing defaults.
  • No Separate Web Server Needed.Which means that you no longer have to boot up Tomcat, Glassfish, or anything else.
  • Requires less configuration-Since there is no web.xml file. Simply add classes annotated with@Configuration and then you can add methods annotated with@Bean, and Spring will automatically load up the object and manage it like it always has. You can even add @Autowired to the bean method to have Spring autowire in dependencies needed for the bean.
  • Environment Based Configuration-Using these properties, you can pass into the application which environment you are using with:-Dspring.profiles.active={enviornment}. Spring will then load up the subsequent application properties file at (application-{environment}.properties) after loading up the main application properties file.


Q: Which build tool have you used to develop Spring Boot Application?
A: 
Spring Boot application can be developed using Maven as well as Gradle. 
Spring Boot application using Maven 
Spring Boot application using Gradle 

Q: What is JavaConfig?
A: 
Spring JavaConfig is a product of the Spring community that provides a pure-Java approach to configuring the Spring IoC Container. It thus helps avoid using XML configurations. The advantages of using JavaConfig are
The advantages of JavaConfig are
  • Object-oriented configuration. Because configurations are defined as classes in JavaConfig, users can take full advantage of object-oriented features in Java. One configuration class may subclass another, overriding it's @Bean methods, etc.
  • Reduced or eliminated XML configuration. The benefits of externalized configuration based on the principles of dependency injection have been proven. However, many developers would prefer not to switch back and forth between XML and Java. JavaConfig provides developers with a pure-Java approach to configuring the Spring container that is conceptually similar to XML configuration. It is technically possible to configure the container using only JavaConfig configuration classes, however in practice, many have found it ideal to mix-and-match JavaConfig with XML.
  • Type-safe and refactoring-friendly. JavaConfig provides a type-safe approach to configuring the Spring container. Thanks to Java 5.0's support for generics, it is now possible to retrieve beans by type rather than by name, free of any casting or string-based lookups.
Added security configuration without XML using java config.
Q: How to reload my changes on Spring Boot without having to restart the server?
A: 
This can be achieved using DEV Tools. With this dependency any changes you save, the embedded tomcat will restart. Spring Boot has a Developer tool (DevTools) module which helps to improve the productivity of developers. One of the key challenges for the Java developers is to auto-deploy the file changes to server and auto restart the server. Developers can reload changes on Spring Boot without having to restart my server. This will eliminate the need for manually deploying the changes every time. Spring Boot doesn’t have this feature when it has released it’s first version. This was a most requested feature for the developers. The module DevTools does exactly what is needed for the developers. This module will be disabled in the production environment. It also provides an H2-database console for better testing the application. The following dependency is used
   
   org.springframework.boot
   spring-boot-devtools
   true
    
   
DevTool dependency usage for autostart and H2 DB console is illustrated in this example

QWhat is Actuator in Spring Boot?
A: 
Spring boot actuator is one of the important features in spring boot framework. Spring boot actuator helps you to access the current state of the running application in production environment. There are several metrics that have to be checked and monitored in the production environment. Even some external applications may be using those services to trigger the alert message to the concerned person. Actuator module exposes set of REST endpoints that can be directly accessed as an HTTP URL to check the status.

Q: How to run Spring boot application to custom port?
A: 
In order to run a spring boot application on a custom port you can specify the port in application.properties.
server.port=8090 

Q: Have you written Test cases using Spring Boot?
A: 
Spring Boot provides the @SpringBootTest for writing Unit Test Cases
Spring Boot Unit Test Simple Example

Q: What is YAML?
A: 
YAML is a human-readable data serialization language. It is commonly used for configuration files.
Compared to the properties file, YAML file is much more structured and less confusing in case we want to add complex properties in the configuration file. As can be seen, YAML has hierarchical configuration data. 
Use YAML properties in Spring Boot
Q: How to implement security for Spring boot application?
A: 
For Implementing security for Spring Boot we use the spring-boot-starter-security dependency and have to add the Security config. It requires very little code. Config class will have to extend WebSecurityConfigurerAdapter and override its methods.
Spring Boot Security example and explanation 

Q: Have you integrated Spring Boot and ActiveMQ?
A: 
For integrating Spring Boot and ActiveMQ we use the spring-boot-starter-activemq dependency
It requires very little configuration and no boilerplate code.
Spring Boot ActiveMQ explanation 

Q: Have you integrated Spring Boot and Apache Kafka?
A: 
For integrating Spring Boot and Apache Kafka we use the spring-kafka dependency.
Spring Boot + Apache Kafka Example 

Q: How to implement Pagination and Sorting with Spring Boot?
A: 
Using Spring Boot achieving pagination is very simple. Using the Spring Data-JPA this is achieved passing pageable org.springframework.data.domain.Pageable to the repository methods.
Spring Boot pagination explanation

Q: What is Swagger? Have you implemented it using Spring Boot?
A: 
Swagger is widely used for visualizing APIs, and with Swagger UI it provides online sandbox for frontend developers. For the tutorial, we will use the Springfox implementation of the Swagger 2 specification. A swagger is a tool, a specification and a complete framework implementation for producing the visual representation of RESTful Web Services. It enables documentation to be updated at the same pace as the server. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Thus Swagger removes the guesswork in calling the service.
Spring Boot + Swagger2 

Q: What is Spring Profiles? How do you implement it using Spring Boot?
A: 
Spring Profiles allows users to register beans depending on the profile(dev, test, prod etc). So when the application is running in DEVELOPMENT only certain beans can be loaded and when in PRODUCTION certain other beans can be loaded. Suppose our requirement is that the Swagger documentation be enabled only for the QA environment and disabled for all others. This can be done using Profiles. Spring Boot makes using Profiles very easy. 
Spring Boot + profiles 

Q: What is Spring Batch? How do you implement it using Spring Boot?
A: 
Spring Boot Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high-performance batch jobs through optimization and partitioning techniques.Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information. 
Spring Boot + Batch 

Q: What is FreeMarker Template? How do you implement it using Spring Boot?
A: 
FreeMarker is a Java-based Template Engine, originally focusing on dynamic web page generation with MVC software architecture. The major advantage of using Freemarker is the complete separation of the Presentation layer and the Business Layer. The Programmers can work on the application code while the designers can work on the HTML page design. Finally using freemarker these can then be combined to give the final output page. 
Spring Boot + FreeMarker Example 

Q: How did you perform database operations using Spring Boot?
A: 
Spring Boot Tutorial-Spring Data JPA
Spring Boot JDBC Example 

Q: How to upload a file using Spring?
A: 
Spring Boot + File Upload Example
Q: How to implement interceptors with Spring Boot?
A: 
Using Spring MVC HandlerInterceptor with Spring Boot 

Q: How to use schedulers with Spring Boot?
A: 
Spring Boot Task Scheduler Example 

Q: Which all starter maven dependencies have you used?
A: 
Have used different starter dependencies like spring-boot-starter-ActiveMQ dependencyspring-boot-starter-security dependencyspring-boot-starter-web dependency 
. This helps in adding less number of dependencies and also in reducing version conflicts. 
Spring Boot Security example and explanation 

Q: Have you used any integration framework with Spring Boot?
A:
 Have integrated Apache Camel with Spring Boot. Made use of Apache Camel Spring Boot starter dependency. Spring Boot +Apache Camel 

Q: What is Apache Freemarker? When to use it instead of JSP? How to integrate it with Spring Boot?
A:
JSP is tailor-made for Web pages, Freemarker template is a more generic templating language - it can be used to generate HTML, plain text, emails, etc.
Spring Boot + FreeMarker Example

Q: What is AOP? How to use it with Spring Boot?
A: 
During software development, functions that span multiple points of an application are called cross-cutting concerns. These cross-cutting concerns differ from the application’s main business logic. Hence, separating these cross-cutting concerns from the business logic is where aspect-oriented programming (AOP) comes into the picture.
Spring Boot + AOP Example 
Q: What is Apache Kafka? How to integrate it with Spring Boot?
A:
Apache Kafka is a distributed publish-subscribe messaging system. It is a scalable, fault-tolerant, publish-subscribe messaging system which enables us to build distributed applications. It is an Apache Top-Level project. Kafka is suitable for both offline and online message consumption.
Spring Boot + Apache Kafka Example 

Q: Have you used any Spring Cloud Components with Spring Boot?
A:
 Have used Spring Cloud components like Netflix Eureka for Service Registration, Ribbon for Load Balancing.
Spring Boot + Cloud Components


Reference: http://www.javainuse.com/spring/SpringBootInterviewQuestions

Read more ...

Difference between Object Oriented Programming(OOP) vs. Functional Programming(FP)

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods -- Wikipedia https://en.wikipedia.org/wiki/Object-oriented_programming
Functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data -- Wikipedia https://en.wikipedia.org/wiki/Functional_programming

These are acceptable descriptions if you already understand the concepts they’re describing, but not helpful if you don’t. Let’s see if we can do better.
Both OOP and FP have the shared goal of creating understandable, flexible programs that are free of bugs. But they have two different approaches for how to best create those programs.
In all programs, there are two primary components: the data (the stuff a program knows) and the behaviours (the stuff a program can do to/with that data). OOP says that bringing together data and its associated behaviour in a single location (called an “object”) makes it easier to understand how a program works. FP says that data and behaviour are distinctively different things and should be kept separate for clarity.
Let’s look at some examples of the two approaches. I’m using Ruby because it natively supports both styles and is easy to read for non-rubyists, but other languages also support both, such as JavaScript and Scala.
Let’s say you run a company and you’ve just decided to give all your employees a $10,000.00 raise. (If this sort of thing happens often at your company, let me know when you’re hiring) How could we write a command-line script to make this change?
You most likely have all your employee records in a database with two attributes: the employee’s name and a current salary. In our examples, we’ll ignore the part where you transfer the data to and from the database. Let’s just focus on the “giving a raise” feature.
Here’s one approach using OOP:
class Employee
  def initialize(name, salary)
    @name = name
    @salary = salary
  end

  def change_salary(amt)
    @salary = @salary + amt
  end

  def description
    "#{@name} makes #{@salary}"
  end
end
This is our class, which we’ll use to generate new Employee objects. Most OOP languages use classes to generate objects in the same way a cook uses recipes to create meals -- the classes tell us how to construct the object, how it should behave, what it looks like, etc.
The @-sign before a variable makes it an “instance” variable: a variable that lives inside the object (aka instance) and can be used in its methods without having been passed in as an argument, the way change_salary uses @salary. The initialize method takes the name and salary we passed to new and stores them in the @name and @salary instance variables.
All the methods except for initializing are “instance methods” which also live inside the object (aka instance) and can be called on the object itself.
Now we’ll generate some objects to work with.
employees = [
  Employee.new("Bob", 100000.0),
  Employee.new("Jane", 125000.0)
]
Each Employee.new(...) call creates an object with data (@name and @salary) and behavior (change_salary and description). We call new twice, which gives us a pair of objects representing Bob and Jane stored in an array we are calling “employees”. In a normal app, this array of objects will typically be returned from the database directly by a tool such as ActiveRecord.
Now let’s give out those raises.
employees.each do |emp|
  emp.change_salary(10000.0)
end
We call each method on our array of employees, which hands us each employee in turn and stores it in a local variable called emp. We call the “change_salary” method we defined in our class, passing in a value of 10000.0. This adds our $10K to the employee’s salary and stores the sum in @salary, overwriting the existing value.
employees.each do |emp|
  puts emp.description
end
Finally, we can generate some output to make sure the results are what we intended, using the described method to build our output string instead of trying to access the data fields (@salary and @name) directly. This is called “data hiding” and it allows us to change the names of our instance variables without forcing the users of our object to change how they use it.
We use each again to output the results. This time, we use puts (put string) and call the description method for each of our objects to print their description, as we defined in our class.
There are several important things to notice about the OOP implementation. Data is supplied to an object at the time the object is created (when we called the ‘new’ method). Then we use methods on that object (change_salary and description) to interact with data that we’ve already stored. This gives us a good place to put all the behaviours that are associated with that object type, making them easy to find if we’re unfamiliar with the codebase or refreshing our memory after some time away. The names of these methods document object’s behaviours , which also helps us familiarize ourselves with the code. The object is an obvious location to add behaviours as our project becomes more complex.
Let’s implement this task using an FP approach.
employees = [
  [ "Bob",  100000.0 ],
  [ "Jane", 125000.0 ]
]
This time our data structure is an array of arrays instead of an array of objects containing the values. FP prefers to keep data in plain arrays and/or hashes and not “complicate” data by mixing it with behaviour.
Instead of converting the data to an object and then calling methods on it, we write a pair of standalone methods called change_salaries (plural) and change_salary (singular). We pass change_salaries two arguments: the array of arrays representing our data and the change amount. change_salaries uses a map instead of each method we used in the OOP version. We’ll discuss map in a moment.
FP leans very heavily on tiny methods that do one small part of a larger job, delegating the details to other tiny methods. This combining of small methods into a larger task is called “composition”. In our example, change_salaries has a single job: call change_salary for each employee in the employee's array and return those values as a new array. change_salary also has one job: return a copy of a single employee with the salary field updated. change_salaries delegates the calculation of the new salary to change_salary, allowing change_salaries to focus entirely on handling the set of employees and change_salary to focus on updating a single employee. A nice side-effect of this approach is if we had a single employee we wanted to change the salary for, we could call change_salary directly! The composition isn’t unique to FP -- OOP uses it as well -- but it is a cornerstone of the FP mindset.
happier_employees = change_salaries(employees, 10000.0)
Because we don’t have objects, change_salaries requires that we pass in not just the amount, but also the data we want to modify. This method returns the updated dataset, which we store in the happier_employees variable.
happier_employees.each do |emp|
  puts "#{emp[0]} makes #{emp[1]}"
end
Finally, we use ‘each’ to walk through every record in happier_employees and generate the output message ourselves. This fits the FP model because FP likes to view everything as a data transformation: you start with this dataset, apply these transformations to it (in this case, adding $10K) and generate a new dataset.
Something you’ll notice right off is there are fewer lines of code, mainly because we don’t build the class for creating our objects.
Another subtle -- but important -- the difference is that in the OOP version change_salary used each to process each employee, but the FP version uses map. Instead of changing the original value, ’map’ creates a copy of the array containing the return value of each pass. When all elements have been processed, map hands us the copy with all the new values, which we store in happier_employees. The original array is untouched!
This idea of not changing the contents (or “state”) of a variable once it’s been created is called immutability and is another key aspect of FP. In the OOP version, the contents of the employee's array changes over time: before change_salary is applied the salaries are 100K and 125K, but afterwards, they are 110K and 135K! This means we don’t always know which value we’ll have at any given point in the program: we have to walk through the program flow and find out if change_salary has been called or not. This can be difficult as the program increases in complexity. The FP version avoids this because employees represent the “before” state and happier_employees represents the “after” state. Their values are always the same over their entire existence.
So which approach should you choose for your next project?
Michael Fogus, author of “Functional JavaScript”, suggests in his blog post “FP vs OO, from the trenches” (http://blog.fogus.me/2013/07/22/fp-vs-oo-from-the-trenches/) that when he deals with data about people, FP works well, but when he tries to simulate people, OOP works well. Our example is “data about people” -- since we’re changing the salary directly -- so the FP version is shorter and simpler. If we described a feature like “employee requests time off” that requires a more-complicated interaction with the data -- likely creating a “time-off request” object attached to the employee -- then OOP might be a better fit. Hardcore OOP or FP developers could explain why their approach is better in either situation, which makes this debate so interesting. Read the comments on the post for an example of the dialogue that surrounds OOP and FP.
If you’re on a tight schedule and are already familiar with one approach or the other, stick with what you know. If it’s a personal project or you have some flexibility with deadlines, it might be worth trying each approach for a feature and seeing which results in a more pleasing, clear solution. We’ve only scratched the surface, and the problems you’re solving may look nothing like the trivial one I used in my example. Explore both and use your best judgement.
Reference: https://www.codenewbie.org/blogs/object-oriented-programming-vs-functional-programming
Read more ...

July 21, 2017

Evolving a REST API is a difficult problem – one for which many options are available - Solution for API Versioning

 Situation:
    Evolving a REST API is a difficult problem – one for which many options are available - Solution for API Versioning.

Action
 > Specifying the version number in URI  E.g.: /v2/products/
              The URI in REST should represent the resource only
              This is not suggested unless the entire set of APIs migrate to a new platform
> Passing the version number as a URI Parameter: E.g.: /products?version=2
            • This is used by Amazon, Google and Netflix
            • Parameters are used for filtering resources and should not specify the implementation
            • The APIs have to parse the param string before knowing where to route the request.
> Using the well-known HTTP header: The Accept header is used to make up our own resource types. E.g.: Accept: application/vnd.test.v2 + json

This means that I, as a vendor, can define (and can register) a media type. If we do this it's called a 'vendor' media type. It works and well-known.

The disadvantage with this approach is it is not very intuitive.
According to the Rest API specifications, A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience. Failure here implies that out-of-band information is driving interaction instead of hypertext.

So URIs are not part of the contract!
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.

So the Media Type definitions are part of the contract and should be prior knowledge for the client that consumes the API.


Conclusion:
This article tried to provide an overview of the very diverse and difficult problem of evolving a REST Service. We discussed the two common solutions, advantages and disadvantages of each one, and ways to reason about these approaches in the context of REST. The article concludes by making the case for the second solution – versioning the media types, while examining the possible changes to a RESTful API.Finally Considering all the above, using well-known HTTP header, Accept may be a better option.
 
 

@RequestMapping(..., produces = "application/vnd.company.app-[1.0-1.6]+json)
@ResponseBody
public Object method1() {
   // so something
   return object;
}
@RequestMapping(..., produces = "application/vnd.company.app-[1.7-]+json)
@ResponseBody
public Object method2() {
   // so something
   return object;
}
 
Result:
We can get the different version data without any changes in the code level. 

Ref:
http://www.baeldung.com/rest-versioning

Solution implementation at: https://github.com/mspapant/restVersioningExample/


Read more ...

How Internally works Eureka connection pool? How to configure?

We can configure total connections Eureka, updating peerNodeTotalConnections property in the application.yml (default: eurkea peerNodeTotalConnections is 1000) in eureka application:

eureka:
    server:
       waitTimeInMsWhenSyncEmpty: 0
       peerNodeTotalConnections: 1000
       peerNodeTotalConnectionsPerHost: 500

Ref:
https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerConfigBean.java
EurekaServerConfigBean :
private int peerNodeTotalConnections = 1000;
private int peerNodeTotalConnectionsPerHost = 500;

http://blog.abhijitsarkar.org/technical/netflix-eureka/:
For Eureka server config: org.springframework.cloud.netflix.eureka.server.EurekaServerConfigBean that implements com.netflix.eureka.EurekaServerConfig. All properties are prefixed by eureka.server.
Further more info:
We can check eureka health and info, we can configure below configuration in Eureka:

instance:
    hostname: ${vcap.application.uris[0]:localhost}
    statusPageUrl: https://${eureka.hostname}/info
    healthCheckUrl: https://${eureka.hostname}/health
    homePageUrl: https://${eureka.hostname}/

For Eureka instance config: org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean that implements (indirectly) com.netflix.appinfo.EurekaInstanceConfig. All properties are prefixed by eureka.instance.

For Eureka client config: org.springframework.cloud.netflix.eureka.EurekaClientConfigBean that implements com.netflix.discovery.EurekaClientConfig. All properties are prefixed by eureka.client.

We can check eureka apps info:
https://github.com/Netflix/eureka/wiki/Eureka-REST-operations
Using ribbon, zuul configurations, we can manage connection pool also.


For more information about eureka connections:
DefaultEurekaServerConfig side maximum limit of Peer Node Total Connections = 1000 and Peer Node Total Connections Per Host = 500. DefaultEurekaClientConfig side it is 200 and 50.
Given our environment, from the short and medium-terms, the above default limits may be fine and these connections are not expensive as database connections
In the case in the long-term, we need to override the defaults, we have options to do so.
https://github.com/Netflix/eureka/wiki/Overriding-Default-Configurations
The life cycle of Eureka client and server are summarized below.
Registration:
Eureka client registers the information about the running instance to the Eureka server
Renewal:
1. Eureka client needs to renew the lease by sending heartbeats every 30 seconds.
2. The renewal informs the Eureka server that the instance is still alive. If the server doesn’t see a renewal for 90 seconds, it removes the instance out of its registry.
Fetching Registry:
1. Eureka clients fetch the registry information from the server and cache it locally. After that, the clients use that information to find other services.
2. This information is updated periodically (every 30 seconds) by getting the delta updates between the last fetch cycle and the current one.
3. After getting the deltas, Eureka client reconciles the information with the server by comparing the instance counts returned by the server and if the information does not match for some reason, the whole registry information is fetched again.
4. Eureka server caches the payload of the deltas, whole registry and also per application
Cancellation:
1. Eureka client sends a cancel request to Eureka server on shutdown.
2. This removes the instance from the server's instance registry thereby effectively taking the instance out of traffic.
Time lag:
1. All operations from Eureka client may take some time to reflect in the Eureka servers and subsequently in other Eureka clients.
2. This is because of the caching of the payload on the Eureka server which is refreshed periodically to reflect new information.

3. Eureka clients also fetch deltas periodically. Hence, it may take up to 2 minutes for changes to propagate to all Eureka clients.
Other ways:
Ribbon Configuration ref:
https://github.com/Netflix/ribbon/blob/3a707ec518a896053be44266dddc4c4f925f4e60/ribbon-core/src/main/java/com/netflix/client/config/DefaultClientConfigImpl.java#L331


More refference links:
Eureka default configuration:
https://github.com/Netflix/eureka/blob/master/eureka-client/src/main/java/com/netflix/discovery/EurekaClientConfig.java

https://github.com/Netflix/eureka/blob/master/eureka-client/src/main/java/com/netflix/discovery/DefaultEurekaClientConfig.java

https://github.com/Netflix/eureka/blob/master/eureka-client/src/main/java/com/netflix/appinfo/MyDataCenterInstanceConfig.java

https://github.com/Netflix/eureka/blob/master/eureka-core/src/main/java/com/netflix/eureka/DefaultEurekaServerConfig.java

https://www.npmjs.com/package/eureka-js-client

http://programtalk.com/java-api-usage-examples/com.netflix.discovery.DefaultEurekaClientConfig/

https://insight.io/github.com/Netflix/eureka/blob/master/eureka-client/src/main/java/com/netflix/appinfo/DataCenterInfo.java

https://spring.io/blog/2015/01/20/microservice-registration-and-discovery-with-spring-cloud-and-netflix-s-eureka


Read more ...

August 01, 2014

Mockito Junit Code Examples

Mockito is an unwrap source testing framework for Java released under the MIT License. The framework allows the creation of test double objects (mock objects) inautomated unit tests for the purpose of Test-driven Development (TDD) or Behavior Driven Development (BDD).
Unit testing is used to test a single programming unit Ex: a class or a method, in-fact almost every Java developer write unit test on per method basis. The Stub and Mock objects are two concepts, which helps during unit testing, they are not real world objects, but act like real world objects for unit testing purpose. 
The common testing for approach to test a unit, which depends on other unit is by using Stubs and Mock objects. They help to reduce complexity, which may be require to create actual dependent object. In this tutorial, we will learn few basic difference between Stub and Mock object in Java Unit testing. This post is rather small to tackle this whole topic, at best it just provide an introduction.

JUnit is the most popular framework for unit testing Java code. I am assuming you can download Mockito and get it in your classpath.  So I'll start with tests that implement some of the requirements from here (https://code.google.com/p/mockito/downloads/list). However, in a nutshell:Download mockito-all-1.7.jar from here. Create a new Java project in your favorite IDE Add that jar to your project's classpath, Add JUnit 4 to your project's classpath. More Examples( https://code.google.com/p/mockito/ )
Mockito API: http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html )

package com.mockito;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.List;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
/**
 * I am assuming you can download Mockito and get it in your classpath.
 * So I'll start with tests that implement some of the requirements from here
 * (https://code.google.com/p/mockito/downloads/list).
 * However, in a nutshell:Download mockito-all-1.7.jar from here.
 * Create a new Java project in your favorite IDE Add that jar to your project's classpath,
 * Add JUnit 4 to your project's classpath
 * More Examples( https://code.google.com/p/mockito/ )
 * Mockito API ( http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html )
 * @author Myjavacafe
 */
public class MockitoTest {
                public static void main(String[] args) {
                                // TODO Auto-generated method stub
                }
/**
* This example creates a mock iterator and makes it return “Hello” the first time method
* next() is called. Calls after that return “World”. Then we can run normal assertions.
*/
                @Test
                public void iterator_will_return_hello_world() {
                                // arrange
                                Iterator i = Mockito.mock(Iterator.class);
                                Mockito.when(i.next()).thenReturn("Hello").thenReturn("World");
                                // act
                                String result = i.next() + " " + i.next();
                                // assert
                                Assert.assertEquals("Hello World", result);
                }
               
               
                /**
                 * Its creates a stub Comparable object and returns 1 if it is compared to
                 * a particular String value (“Test” in this case).
                 */
                @Test
                public void with_arguments(){
                                //Set the class to mockito
                                Comparable c = Mockito.mock(Comparable.class);
                                //Set the values to mockito object
                                Mockito.when(c.compareTo("Test")).thenReturn(1);
                                //set the
                                Assert.assertEquals(1,c.compareTo("Test"));
                }
               
                /**
                 * The method has arguments but you really don’t care what gets passed or cannot predict it,
                 * use anyInt() (and alternative values for other types.
                 * This stub comparable returns -1 regardless of the actual method argument.
                 */
                @Test
                public void with_unspecified_arguments(){
                                Comparable c = Mockito.mock(Comparable.class);
                                Mockito.when(c.compareTo(Mockito.anyInt())).thenReturn(-1);
                                Assert.assertEquals(-1,c.compareTo(6));
                }
               
                /**
                 * The syntax is doReturn(result).when(mock_object).void_method_call();
                 * Instead of returning, you can also use .thenThrow() or doThrow() for void methods.
                 * This example throws an IOException when the mock OutputStream close method is called.
                 */
                @Test(expected=IOException.class)
                public void OutputStreamWriter_rethrows_an_exception_from_OutputStream()
                                throws IOException{
                                OutputStream mock = Mockito.mock(OutputStream.class);
                                OutputStreamWriter osw=new OutputStreamWriter(mock);
                                Mockito.doThrow(new IOException()).when(mock).close();
                                osw.close();
                }
               
                /**
                 * We verify easily that the OutputStreamWriter rethrows the exception of the wrapped output stream.
                 * To verify actual calls to underlying objects (typical mock object usage),
                 * we can use verify(mock_object).method_call; This example will verify that OutputStreamWriter
                 * propagates the close method call to the wrapped output stream.
                 */
                @Test
                public void OutputStreamWriter_Closes_OutputStream_on_Close()
                                 throws IOException{
                                OutputStream mock = Mockito.mock(OutputStream.class);
                                OutputStreamWriter osw=new OutputStreamWriter(mock);
                                osw.close();
                                Mockito.verify(mock).close();
                }
               
                /**
                 * We can’t mix literals and matchers, so if you have multiple arguments they all have to be either
                 * literals or matchers. Use eq(value) matcher to convert a literal into a matcher that compares on value.
                 * Mockito comes with lots of matchers already built in, but sometimes you need a bit more flexibility.
                 * For example, OutputStreamWriter will buffer output and then send it to the wrapped object when flushed,
                 * but we don’t know how big the buffer is up front. So we can’t use equality matching.
                 * However, we can supply our own matcher.
                 */
                @Test
                public void OutputStreamWriter_Buffers_And_Forwards_To_OutputStream()
                                throws IOException{                     
                                OutputStream mock = Mockito.mock(OutputStream.class);
                                OutputStreamWriter osw=new OutputStreamWriter(mock);
                                osw.write('a');
                                osw.flush();
                                // can't do this as we don't know how long the array is going to be
                                // verify(mock).write(new byte[]{'a'},0,1);

                                BaseMatcher arrayStartingWithA=new BaseMatcher(){
                                                // check that first character is A
                                                @Override
                                                public boolean matches(Object item) {
                                                                byte[] actual=(byte[]) item;
                                                                return actual[0]=='a';
                                                }
                                                @Override
                                                public void describeTo(Description description) {
                                                                // TODO Auto-generated method stub
                                                               
                                                }
                                };
                // check that first character of the array is A, and that the other two arguments are 0 and 1
                                Mockito.verify(mock).write((byte[]) Mockito.argThat(arrayStartingWithA), Mockito.eq(0),Mockito.eq(1));
//                            Mockito.verify(mock).write(Mockito.eq(0));
                }
}
Do you want to download this example, please Click Me
Do you want to know more about Mockito, please Click Me
Do you want  to know more about SprignBoot MicroServices Mockito ClickMe
Read more ...

My Favorite Site's List

#update below script more than 500 posts