Wednesday, 9 October 2019

[Jenkins] Automatically retry a failed build

[Jenkins] Automatically retry a failed build

Are your Jenkins builds failing due to unavoidable reasons like unavailability of external databases, file systems etc? The only solution you might be having right now is to reschedule the build after fixing that external issue. In this post, I will be discussing on how you can automatically rerun a failed build.

Setup

For this, we are going to use a plugin named Naginator, version 1.8 is available here for download. As the first step, please install this plugin into your Jenkins.

When it is installed, there will be a new action named "Retry build after failure" added to the post-build action list in job configuration page (as shown).

Configuration

First create a new job. If you need to retry an existing job, please open the job configuration page. Then click on the "Add post-build action" button and select "Retry build after failure". This will add a new configuration section as shown in the below image.


There are 3 configuration settings (as numbered in above image). Let's discuss each in details below.

Setting 1 || Rerun build for unstable builds as well as failures

This option is there to indicate whether you should be retrying the UNSTABLE state builds as well in addition to FAILURE state builds. Let's set it to true.

Setting 2 || Delay before schedule

This allows you to define how long to delay a retrying build start-time from the time it was failed. There are two options to choose from; one is to provide a "fixed period" and the other is to provide an "increasing period". Let's use fixed period; and set 300 there (meaning 5 mins).

Setting 3 || Max number of successive failed build

This is used to control the number of continuous failure builds. Jenkins will not automatically retry more than this maximum number of consecutive failures. So let's set 2 there so that it is retried only two times.

Conclusion

As expected, this is working without any issues and stops retrying as soon as the build is successful. Hope this will help you in avoiding manual retries.

Tuesday, 1 October 2019

Maven interview questions

Q: What is Maven?
Maven is a build automation tool or a project management tool. With Maven we can import all libraries and can also create project structures. In Maven we have many inbuilt templates. These templates are called archetypes. A Maven is basically a tool used to compile our applications. It helps to develop and managing project structure or applications like deployment, clean, packaging, jar and many more features for the Java-based project.
In another word, it is a Java tool. If you want to create a sample project or skeleton project you can use Maven. It is an automated build tool. The Maven focused on simplicity that it generates intelligent starters and assumes intelligence defaults. It also covers build-oriented phases in Application Lifecycle Management i.e. testing, deployment, builds management, and release versioning.
Q: How many project types available in Maven to choose from?
There is more than thousand Java project as there are templates, skeleton provided to you by Maven so that you do not have to remember a basic configuration detail or a basic setup of that particular type of project which Maven is going to give it to you. It includes examples like basic Java project, Spring Project, Spring MVC, Spring Web Flow, and Spring Boot.
Q: Why should one use Maven?
>> It helps to setup project very quickly and it avoids complicated build files like build.xml. Maven required files like POM.xml; it serves the purpose for Maven only. POM.xml is a collection of dependencies of your Java Project which one can specify to Maven and then Maven will download all of them from the internet and then store it to some repository i.e. local repository, central repository, and remote repository.

>> It helps to not bundle all the jars in your package i.e. in your War file or Ear file because all of them are going store in the repository and wherever you install this application that repository will be used for any dependencies look up. So, your Jar file, War file or Ear file or your bundle deployment will be very light.
Q: Maven advantages over Ant?
** Maven uses Convention whereas ant uses Configuration. In Maven, convention means a standard layout suggested by Maven. If you want a skeleton project of sample Java application, so Maven is going to give you one set of folders and configurations for that Java applications whereas in the case of Ant you need to have lots of configurations.
** Maven supports project modularization.
** Maven also supports dependency management and migration.
Q: What Maven creates for you?
1. Directory Name
2. Purpose
3. Project home
4. Contains the POM.xml and all subdirectories.
5. Src/main/Java
6. Contains the deliverable Java source code for the project.
7. Src/main/resources
8. Contain the deliverable resources for the project.
9. Src/test/Java
10. Contains the testing Java source code.
11. Src/test/resources
12. Contains resources necessary for testing.
Q: For whom this Maven course is for?
>> Maven can use for the Intermediate Java developers.
>> It works for a large project or portfolio managers.
>> It helps to work for heavy users of libraries.
Q: What are the Maven Phases?
1. The first phase is the Validate Phases. It checks whether everything is in order i.e. the configuration is running properly, the code is placed in a proper way. This kind of validation check is done in the validate phase.
2. The next comes the compiler phases. It compiles everything together and stores it.
3. The third comes to the test phases. Here we run the test cases which are specified for the code.
4. The fourth phase is the package phases. Package file ends up in Jar file or War file or Ear file depending on what we have specified on the POM.xml.
5. The fifth phase is the install phase. It installs to your local Maven repository.
6. The sixth phase is called the deploy phase. 
Q: What are the tenets of Maven?
1. Project oriented.
2. Dependency Management.
3. Reuse through centralized repositories.
4. Convention over Configuration.
5. Extensible through plugins.
Q: What is the Projected Oriented Build in Maven?
Maven tools are build on the model as POM i.e. Project Object Model.
Supports single-inheritance tree like Java.
Defined as XML in pom.xml
Every pom extends the super POM
Q: What are POM Files in Maven?
All your code and resources are placed in the src directory.
>> The main/Java directory holds your project code.
>> Compiled code is placed in the largest directory.
>> The test/Java directory holds your JUnit test code.


Maven Interview Questions And Answers For Experienced

Q: What is Maven Archetypes? And what are the Project Types?
Archetypes are templates to create a variety of Java project structures, including web applications specific to a container such as Wildfly. In other words, it is a tool that creates the stuff you build the project on top of.
Project Types:
1. War
2. Jar
3. Ear
4. Wildfly
5. JMS
6. Android

Q: What are Maven’s main objectives?
** It helps to make project build easy to work for the users.
** It easily helps in to migrate from one feature to another or one folder to another.
** It helps in the new development with proper series of guidelines.
** It creates a flexible working system for the users. So that you can work uniformly and orderly.
Q: What is Maven Repository?
In Maven a repository is used as a storage folder or a directory to store your projects, your files such as Jar, War or Ear files that can be later used by the Maven application or tool. It works as a whole library of the files that is easily accessible and can be easily located in your system without any trouble and then can be used by Maven.
Q: How many repositories are there in Maven?
There are three types of repository present in Maven. This includes Local Repository, Central Repository, and Remote Repository.
Local Repository- This local repository is located on your local system and it works when you run a maven command. Maven local repository command is %USER_HOME%/.m2 directory.
Central Repository- Installation from the repository is performed on creating a project from archetype or resolving the dependency.
Remote Repository- This repository is located on the web. It is just a network accessible location that Maven downloads dependencies from. All the artifacts that remote repository contains are open source.
Q: How to install Maven?
Make sure JDK is installed, and ‘JAVA_HOME’ variable is added as Windows environment variable.
Add both M2_HOME and MAVEN_HOME variable in the Windows environment, and point it to your Maven folder.
Q: What is the Maven Lifecycle?
Lifestyle executed in term of phases:
1. Maven Steps through phases.
2. Execution defined in terms of plugin goals.
3. Execution associated with phases.
4. Lifecycle completes when all phase executes successfully.
Q: What is the system requirement for Maven?
Maven does not require any high configuration to use. It requires only very minimal and simple system requirements for the users:
1. Java Deployment Kit
2. Installed
3. Configured (JAVA_HOME)
4. Internet Connection
5. For interacting with the repository.
6. Downloading dependencies.


Advanced Interview Questions on Maven

 

Q: What is the method and installing process of Maven?
Download Maven from:

https://maven.apache.org./download.html
Choose the .zip format.
Extract Maven to:
/usr/local/maven – Unix / Linux
C:Program Filesmaven – Windows
Q: What is Key Maven Command?
Maven as an application has a limited number of commands
“Command” is a way of invoking the maven lifecycle.
Other “Commands” are defined through plugins.
Q: What is Maven Plugin?
Core Maven functionality is simplistic:

Really just a plugin execution framework.
Knows predefined lifecycle and how to execute plugins.
Plugins are dynamically downloaded and installed.
Plugins encapsulate build related functionality:
Define by name.
Contain a set of goals.
Plugins are invoked using the syntax:
%>mvn plugin_name:goal
Q: What are the archetype goals?
Four goals associated with archetype plugin:
Create - creates using a quick-start template.
Generate – provide a menu of templates.
Create-from-project – creates an archetype from an existing project.
Crawl – searches the repository for archetype and updates catalog.
Q: What are Maven build plugins?
Antlr Plugin –
 Generates parsers that you can use in your code from a very concise domain-specific language.
QueryDSL Plugin – Interrogates your database and creates data access objects that you can use to write SQL- like queries in your Java code.
Test Report Plugins – Make cool report websites that show you how well your unit tests are covering your code.
Shade Plugin – Allow you to bundle all of your classes into an uber-Jar that is runnable. This way you can deploy just one artifact. Also, can change packages of your dependencies to work around conflicts.
Q: What is the dependency scope in Maven?
Compile
– The library is available while compiling and running, main code and test code.
Provided – The library is available at compile time but will not be packaged with your code at run-time. Typically this is used when running on an app-server that will provide its chosen version of the library to all running applications.
Runtime – The library is not around for compilation but is around at run-time. 
Test – Only include the library when compiling/running unit tests.
System – Refer to a library on this computer by filename; useful for libraries built into system. 
Q: What is parent POMs?
1. Basically, these are parent projects without code.
2. Used by companies to define the set of libraries/versions, plugins they want their teams using.
3. Can have dependencies, build plugins, variables definitions, and even their own parent POM, forming a chain.
4. A great example is Spring Boot. You can extract it to create production-grade web services crazily fast. 
Q: What is Maven Artifact?
Maven Artifact consists of files like Jar file or War file that result in the expansion of the specific file in the Maven repository. The Jar file can use as an artifact in Maven. The Maven Artifact determined by a group ID name to run the Maven Artifact in the Maven. They can contain files like Ear, Jar, and War or Zip file as well. Maven Artifact is used for specifying applications to locate a name or package. It is usually stored in your system repository. 
Q: What is the sequence in which Maven searches for dependency libraries?
You can locate dependency in the local repository system of your software. Sometimes, it is difficult to locate or identify in the local repository. So, I can find or look in the central repository system and if it shows the dependency missing then one can look in remote repository to find the dependency. If it still shows the same thing repeatedly then the system will show error in finding the dependencies. And if the dependencies are found in the local repository then it will be automatically downloaded in the central repository for future use.
Q: What are the things you need to define for each external dependency?
External Dependency plays an important part in the Maven software. It is an internal part of the system without which dependency cannot be located in a system. To specify the external dependency we need:
1. It requires a group ID duplicate to the library name.
2. It requires an artifact ID duplicate to the library name.
3. Mentioning of dependency scope in the system
4. Have to mention the system route corresponding to the project position.


Maven Interview Questions and Answers

 

Q: What are the steps involved in project deployment?
There are several steps to follow while implying project deployment in Maven. These steps include:
1. Go through all the projects and analyze the code that is working in the background in progress in the source code repository and identifies it.
2. In order to get the project development, one need to download the whole source code from the Social Venture Network.
3. Construct or develop the application in the system
4. It needs to be saving as a War or Jar file system.
5. Get the specified file from the location path and move that specific file to create a site.
6. The application that is created in the system needs to be updated with the latest version with date and version number.
Q: What are the aspects Maven manages?
1. Documentation
2. SCMs
3. Distribution
4. Builds
5. Reporting
6. Releases
7. Mailing list
8. Dependencies
Q: What is a goal in Maven terminology?
The goals mentioned here in the Maven suggests the managing and building process requires creating a project. There is no limitation to follow the goals in Maven; it can build as many phases as it wants with zero boundations. You directly achieve your goal without any kind of outside intervention.

Tuesday, 24 September 2019

10 Steps to Become an Outstanding Java Developer

If you are a Java developer and passionate about technology, you can follow these ten steps which could make you an outstanding Java developer.


1. Have a strong foundation and understanding of OO principles

For a Java developer, having a strong understanding of object-oriented programming is a must. Without having a strong foundation on OOPS, one can't realize the beauty of an object-oriented programming language like Java. If you don't have a good idea of what OOPS is, even though you are using the OOP language, you may be still coding in a procedural way. Just studying OO principle definitions won't help much. We should know how to apply those principles in designing a solution in an OO way. So, one should have a strong knowledge of object modeling, inheritance, polymorphism, design patterns, etc.

2. Master the core APIs

 It doesn't matter how strong you are in terms of theoretical knowledge if you don't know the language constructs and core APIs. In the case of Java, one should have very strong hands-on experience with core APIs like java.lang.*, I/O, exceptions, collections, generics, threads, JDBC, etc. When it comes to building web applications, no matter which framework you are using, it's also crucial that you understand concepts around servlets and JSPs — this is a must.

3. Keep coding

Things look simpler when talking about them theoretically. We can give a solution to a problem very easily in theory. But we can realize the depth of the problem when we start implementing our approach. You will come to know the language limitations, or design best practices while coding. So keep coding.

4. Subscribe to forums

We are not alone. There are lots of people working on the same technologies that we are working on. While doing a simple proof of concept on a framework may not give you real challenges, when you start using it on real projects, you will face weird issues and won't find any solution in their official documentation. When starting to work on new technology, the best and first thing to do is subscribe to relevant technology forums. Whatever the issue you are facing, someone else in the world might have already faced it and found the solution. And it would be really really great if you could answer the questions asked through other forum users.

5. Follow blogs and respond 

As I already told, you are not alone. There are thousands of enthusiastic technology freaks around the world blogging their insights on technology. You can also gain valuable perspectives on the same technology from other blogs and developers. Some may find specific framework features to be exceptionally useful, while other's might find those features stupid and pointless, giving his own reasons of why he felt like that. So you can see both the good and the bad from other developers using those tools.
Another way to gain value from looking at other blogs is to respond/comment on posts with your opinions and questions. 

6. Read open-source frameworks' source code

A good developer will learn how to use a framework. But if you want to be an outstanding developer, you should study the source code of various successful, popular frameworks where you can see the internal working mechanism of the framework as well as best practices. It will help a lot in using when using frameworks in a more effective way.

7. Know the emerging technology trends

In terms of open-source software development trends, they are growing tremendously. By the time you get a good idea on how to use a specific framework, it risks becoming obsolete as some new framework comes into the picture with super-set of features. Then, the problem you are trying to solve with your current framework may be already solved more easily by the new framework with a single line of configuration. So, keep an eye on what's coming in the picture, and what's going out.

8. Keep commonly used code snippets/utilities handy

Over time, you may need to write/copy-paste the same piece of code/configuration again and again. Keeping those kind of configuration snippets like log4.properties, JDBC configuration, etc. and utilities like StringUtilsReflectionUtilsDBUtils will be more helpful. I know it, itself, won't make you an outstanding developer. But just imagine some co-developer asks you to help in fetching the list of values of a property from a collection of objects, and then you just used your ReflectionUtil and gave the solution in a few minutes: That will make you outstanding.

9. Know different development methodologies

Be familiar with various kinds of methodologies like Agile, SCRUM, XP, Waterfall, etc. Nowadays, choosing the development methodology depends on the client. Some clients prefer Agile and some clients are happy with the Waterfall model. S,o having an idea on various methodologies would be a real plus.

10. Document/blog your thoughts on technology

In a day-to-day job, you may learn new and better ways of doing things, as well as best practices, architectural ideas, etc. Keep documenting those thoughts, blog about them, and/or share them across the community. Imagine you solved a weird problem that occurred while doing a simple POC and you blogged about it. Maybe developers elsewhere in the world are facing the same issue on a production-deployed application. Think of how valuable that solution is to that developer. So, blog your thoughts, they might be helpful for others or to yourself one day!

Monday, 29 April 2019

Difference between throw and throws in java

Throw vs Throws in java

In this guide, we will discuss the difference between throw and throws keywords. 

1. Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic Exception");
and
throws ArithmeticException;
3. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.
For example:
Throw:
...
void myMethod() {
   try {
      //throwing arithmetic exception using throw
      throw new ArithmeticException("Something went wrong!!");
   } 
   catch (Exception exp) {
      System.out.println("Error: "+exp.getMessage());
   }
}
...
Throws:
...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
   //Statements
}
...
4. You can throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword.
For example:
Throw:
void myMethod() {
   //Throwing single exception using throw
   throw new ArithmeticException("An integer should not be divided by zero!!");
}
..
Throws:
//Declaring multiple exceptions using throws
void myMethod() throws ArithmeticException, NullPointerException{
   //Statements where exception might occur
}
These were the main differences between throw and throws in Java. Lets see complete examples of throw and throws keywords.

Throw Example

To understand this example you should know what is throw keyword and how it works
public class Example1{  
   void checkAge(int age){  
 if(age<18)  
    throw new ArithmeticException("Not Eligible for voting");  
 else  
    System.out.println("Eligible for voting");  
   }  
   public static void main(String args[]){  
 Example1 obj = new Example1();
 obj.checkAge(13);  
 System.out.println("End Of Program");  
   }  
}
Output:
Exception in thread "main" java.lang.ArithmeticException: 
Not Eligible for voting
at Example1.checkAge(Example1.java:4)
at Example1.main(Example1.java:10)

Throws Example

To understand this example you should know what is throws clause and how it is used in method declaration for exception handling.
public class Example1{  
   int division(int a, int b) throws ArithmeticException{  
 int t = a/b;
 return t;
   }  
   public static void main(String args[]){  
 Example1 obj = new Example1();
 try{
    System.out.println(obj.division(15,0));  
 }
 catch(ArithmeticException e){
    System.out.println("You shouldn't divide number by zero");
 }
   }  
}
Output:
You shouldn't divide number by zero

Wednesday, 24 April 2019

Nginx Questions & Answers

1) Explain what is Nginx?
Nginx is a web server and a reverse proxy server for HTTP, HTTPS, SMTP, POP3 and IMAP protocols.
2) Mention some special features of Nginx?
Special features of the Nginx server includes
  • Reverse proxy/ L7 Load Balancer
  • Embedded Perl interpreter
  • On the fly binary upgrade
  • Useful for re-writing URLs and awesome PCRE support
3) Mention what is the difference between Nginx and Apache?
                            Nginx                                 Apache
  • Nginx is an event based web server
  • All request are handled by a single thread.
  • Nginx avoids child processes idea.
  • Nginx resembles speed
  • Nginx is better when it comes to memory consumption and connection
  • Nginx is better when you want load-balancing
  • For PHP, Nginx might be preferable as it supports PHP internally
  • Nginx do not support O.S like IBMi and OpenVMS.
  • Nginx comes only with core features
  • Nginx performance and scalability do not depend on hardware
  •  Apache is a process based server
  • Single thread handles a single request.
  • Apache is based on child processes
  • Apache resemble power
  • Apache is not up-to the mark when it comes to memory consumption and connection
  • Apache will refuse new connections when traffic reaches the limit of processes
  • Apache support’s PHP, Python, Perl and other languages using plugins. It is useful when application is based on Python or Ruby
  • Apache support much wider range of O.S
  • Apache provides lot more functionality than Nginx
  • Apache is dependent on hardware components like CPU and memory
4) Explain how Nginx can handle HTTP requests?
Nginx uses the reactor pattern.  The main event loop waits for the OS to signal a readiness event- such that the data is accessible to read from a socket, at which instance it is read into the buffer and processed.  A Single thread can serve tens of thousands of simultaneous connections.
5) In Nginx how you can prevent processing requests with undefined server names?
A server that just drops the requests can be defined as

Server {
listen                80;
server_name  “ “ ;
return              444;
}
Here the server name is kept as an empty string which will match request without the “Host” header field, and a special Nginx’s non-standard code 444 is returned that terminates the connection.
Nginx-logo
6) What is the advantage of using a “reverse proxy server”?
The reverse proxy server can hide the presence and characteristics of the origin server. It acts as an intermediate between internet cloud and web server. It is good for security reason especially when you are using web hosting services.
7) Mention what is the best usage of Nginx server?
The best usage of Nginx server is to deploy dynamic HTTP content on a network with using SCGI, WSGI application servers, FastCGI handlers for scripts.  It can also serve as a load balancer.
8) Mention what is the Master and Worker Processes in Nginx Server?
  • Master processes: It reads as well as evaluates configuration and maintains worker processes.
  • Worker processes: It actually does the processing of the requests.
9) Explain how you can start Nginx through a different port other than 80?
To start Nginx through a different port, you have to go to /etc/Nginx/sites-enabled/ and if this is the default file, then you have to open file called “default.” Edit the file and put the port you want
Like server { listen 81; }
10) Explain is it possible to replace Nginx errors like 502 error with 503?
  • 502= Bad gateway
  • 503= Server overloaded
Yes, it is possible but you to ensure that fastcgi_intercept_errors is set to ON, and use the error page directive.

Location / {
fastcgi_pass 127.0.01:9001;
fastcgi_intercept_errors on;
error_page 502 =503/error_page.html;
#…
}
11) In Nginx, explain how you can keep double slashes in URLs?
To keep double slashes in URLs you have to use merge_slashes_off;
Syntax: merge_slashes [on/off]
Default: merge_slashes on
Context: http, server
12) Explain what is ngx_http_upstream_module is used for?
The ngx_http_upstream_module is used to define groups of servers that can reference by the fastcgi pass, proxy pass, uwsgi pass, memcached pass and scgi pass directives.
13) Explain what is C10K problem?
C10K problem is referred for the network socket unable to handle a large number of client (10,000) at the same time.
14) Mention what is the use of stub_status and sub_filter directives?
  • Stub_status directive: This directive is used to know the current status of Nginx like current active connection, total connection accepted and handled current number of read/write/wait connection
  • Sub_filter directive: It is used to search and replace the content in response, and quick fix for stale data
15) Explain does Nginx support compress the request to the upstream?
You can compress the request to the upstream by using the Nginx module gunzip. The gunzip module is a filter that decompresses responses with “Content Encoding: gzip” for clients or servers that do not support “gzip” encoding method.
16) Explain how you can get the current time in Nginx?
To get the current time in Nginx, you have to use variables from SSI module, $date_gmt and $date_local.
  • Proxy_set_header THE-TIME $date_gmt;
17) Explain what is the purpose of –s with Nginx Server?
To run the executable file of Nginx –s parameter is used.
18) Explain how to add modules in Nginx Server?
During the compilation process, Nginx modules must be selected as such run-time selection of modules is not supported by Nginx.

Getting started with Elasticsearch and Node.js

  In this article we're going to look at using Node to connect to an Elasticsearch deployment, index some documents and perform a simple...