Maven Interview Questions and Answers – Part 2

0
289
Maven Interview Questions and Answers

One of the perfect dependency management  and build tools, we are using on lot of projects, we would like to share some interesting Mavan Interview Questions, which may help others to get more knowledge about. here you go..

Already we have derived some of the Questions already in Part1, here we continues the next setup of questions.

1) Why do we say “Maven uses convention over configuration” ?

Convention over configuration is a Software Design Paradigm that decreases the number of decisions made by a software developer, without losing flexibility.

In Maven, there are many conventions for setting up the project, building the artifacts, running unit tests and releasing the code. These conventions lead to common process for Software development.

In case of other tools, there are a lot of configuration options are present. But most of the time, a developer uses same set of configuration options. So it is better to make these as default options. Maven uses default options from best practices and provides right conventions for Software development.

2) What is the difference between a Release version and SNAPSHOT version in Maven?

A SNAPSHOT version in Maven is the one that has not been released.

Before every release version there is a SNAPSHOT version. Before 1.0 release there will be 1.0-SNAPSHOT.

If we download 1.0-SNAPSHOT today, then we may get different set of files than the one we get on downloading it yesterday. SNAPSHOT version can keep getting changes in it since it is under development.

But release version always gives exactly same set files with each download.

3) What is a cyclic dependency?

A has a dependency of B, B has a dependency of C and C has a dependency of A.

With Maven 2, came transitive dependency wherein in above scenario, C will act as a dependency of A as if this dependency has been defined directly in A but the negative side is that if it leads to cyclic dependency, it creates problems

4) Difference between Maven Project and Module?

Maven Module has a Parent whereas Project doesn’t. when we add the parent section to the pom file, it adds the module section to the parent project pom file. When we execute mvn compile / install, it basically checks that module section of the parent to identify all the modules that needs to be compiled first.

5) Have you heard of Ban Duplicate Classes Maven enforcer plugin? What is its use?

Yes, we have been using this plugin with our projects and its purpose is to warn and stop the Build if there are duplicates of the same package and class are being carried either directly or through transitive dependencies. the duplicate could be coming through different types of dependencies or through different versions of the same dependency. Its purpose is to make sure that there is only one copy that’s being used at compile time and runtime and hence shouldn’t later result in runtime problems.

6) What are the different ways to convert an InputStream to a Sting?

Ways to convert an InputStream to a String:

1) Using IOUtils.toString (Apache Utils)

String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

2) Using CharStreams (guava)

String result = CharStreams.toString(new InputStreamReader(
inputStream, Charsets.UTF_8));

3) Using Scanner (JDK)

Scanner s = new Scanner(inputStream).useDelimiter(“\\A”);
String result = s.hasNext() ? s.next() : “”;

4) Using Stream Api (Java 8). Warning: This solution convert different line breaks (like \r\n) to \n.

String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining(“\n”));

5) Using parallel Stream Api (Java 8). Warning: This solution convert different line breaks (like \r\n) to \n.

String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
.parallel().collect(Collectors.joining(“\n”));

6) Using InputStreamReader and StringBuilder (JDK)

final int bufferSize = 1024;
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(inputStream, “UTF-8”);
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
return out.toString();

7) Using StringWriter and IOUtils.copy (Apache Commons)

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, “UTF-8”);
return writer.toString();

8) Using ByteArrayOutputStream and inputStream.read (JDK)

ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString(“UTF-8”);

9) Using BufferedReader (JDK). Warning: This solution convert different line breaks (like \n\r) to line.separator system property (for example, in Windows to “\r\n”).

String newLine = System.getProperty(“line.separator”);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line; boolean flag = false;
while ((line = reader.readLine()) != null) {
result.append(flag? newLine: “”).append(line);
flag = true;
}
return result.toString();

10) Using BufferedInputStream and ByteArrayOutputStream (JDK)

BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
// StandardCharsets.UTF_8.name() > JDK 7
return buf.toString(“UTF-8”);

11) Using inputStream.read() and StringBuilder (JDK). Warning: This solution has problem with Unicode, for example with Russian text (work correctly only with non-Unicode text)

int ch;
StringBuilder sb = new StringBuilder();
while((ch = inputStream.read()) != -1)
sb.append((char)ch);
reset();
return sb.toString();

7) What is force maven update?

mvn clean install -U

-U means force update of snapshot dependencies. Release dependencies can’t not 
be updated this way.

8) How to add local jar files to a Maven project?

How do I add local jar files (not yet part of the Maven repository) directly in my project’s library sources?

You can add local dependencies directly (as mentioned in build maven project with propriatery libraries included) like this:

<dependency>
<groupId>com.sample</groupId>
<artifactId>sample</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>

9) How do you build fat jar using maven?

I have a code base which I want to distribute as jar. It also has dependency on external jars, which I want to bundle in the final jar.

I heard that this can be done using maven-assembly-plug-in, but I don’t understand how. Could someone point me to some examples.

Right now, I’m using fat jar to bundle the final jar. I want to achieve the same thing using maven.

>> Add following plugin to your pom.xml The latest version can be found at https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-assembly-plugin

…
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>CHOOSE LATEST VERSION HERE</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>

</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

After configuring this plug-in, running mvn package will produce two jars: one containing just the project classes, and a second fat jar with all dependencies with the suffix “-jar-with-dependencies”.

if you want correct classpath setup at runtime then also add following plugin

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
</configuration>
</plugin>

10) How do you run JUnit tests in parallel in a Maven build?

we are using JUnit 4.4 and Maven and we have a large number of long-running integration tests.

When it comes to parallelizing test suites there are a few solutions that allow me to run each test method in a single test-class in parallel. But all of these require that I change the tests in one way or another.

I really think it would be a much cleaner solution to run X different test classes in X threads in parallel. I have hundreds of tests so I don’t really care about threading individual test-classes.

Is there any way to do this?

>> From junit 4.7 it’s now possible to run tests in parallel without using TestNG. Actually it has been possible since 4.6, but there are a number of fixes being made in 4.7 that will make it a viable option. You may also run parallel tests with spring.

or

Use maven plugin:

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.7.1</version>
<configuration>
<parallel>classes</parallel>
<threadCount>5</threadCount>
</configuration>
</plugin>
</plugins>
</build>

11) How do you host a Maven repository on github?

I have a fork of a small open sourced library that I’m working on on github. I’d like to make it available to other developers via maven, but I don’t want to run my own Nexus server, and because it’s a fork I can’t easily deploy it to oss.sonatype.org.

What I’d like to do is to deploy it to github so that others can access it using maven. What’s the best way to do this?

>> The best solution I’ve been able to find consists of these steps:

Create a branch called mvn-repo to host your maven artifacts.
Use the github site-maven-plugin to push your artifacts to github.
Configure maven to use your remote mvn-repo as a maven repository.
There are several benefits to using this approach:

Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
Unlike some other proposed solutions, it doesn’t conflict with your gh-pages if you’re using them.
Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would
The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let’s patch into that mechanism for this solution.

12) What is an uber jar? What does an uber-jar mean and what are its features/advantages?

>> An uber-jar is an “over-jar”, one level up from a simple “jar”, defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of “beyond the normal”.

The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.

All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies.

13) What are the methods for constructing an uber jar?

>> ubar jar is also known as fat jar i.e. jar with dependencies.

There are three common methods for constructing an uber jar:

Unshaded: Unpack all JAR files, then repack them into a single JAR. Works with Java’s default class loader. Tools maven-assembly-plugin

Shaded: Same as unshaded, but rename (i.e., “shade”) all packages of all dependencies. Works with Java’s default class loader. Avoids some (not all) dependency version clashes. Tools maven-shade-plugin

JAR of JARs: The final JAR file contains the other JAR files embedded within. Avoids dependency version clashes. All resource files are preserved.

14) How do you get source JARs from Maven repository?

>> Get sources and Javadocs – When you’re using Maven in an IDE you often find the need for your IDE to resolve source code and Javadocs for your library dependencies. There’s an easy way to accomplish that goal.

mvn dependency:sources
mvn dependency:resolve -Dclassifier=javadoc

The first command will attempt to download source code for each of the dependencies in your pom file.

The second command will attempt to download the Javadocs.

Maven is at the mercy of the library packagers here. So some of them won’t have source code packaged and many of them won’t have Javadocs.

In case you have a lot of dependencies it might also be a good idea to use inclusions/exclusions to get specific artifacts, the following command will for example only download the sources for the dependency with a specific artifactId:

mvn dependency:sources -DincludeArtifactIds=guava

15) What is Maven error “Failure to transfer…”?

I am trying to set up a project using Maven (m2eclipse), but I get this error in Eclipse:

Description Resource Path Location Type Could not calculate build plan: Failure to transfer org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced.

Original error: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from/to central (http://repo1.maven.org/maven2): No response received after 60000 ExampleProject Unknown Maven Problem

Any ideas? It would be helpful if you could show me how to check if everything is configured fine…

>> Remove all your failed downloads:

find ~/.m2 -name “*.lastUpdated” -exec grep -q “Could not transfer” {} \; -print -exec rm {} \;

For windows:

cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i

Then rightclick on your project in eclipse and choose Maven->”Update Project …”, make sure “Update Dependencies” is checked in the resulting dialog and click OK.

16) How do you force Maven to copy dependencies into target/lib?

How do I get my project’s runtime dependencies copied into the target/lib folder?

As it is right now, after mvn clean install the target folder contains only my project’s jar, but none of the runtime dependencies.

>> The best approach depends on what you want to do:

If you want to bundle your dependencies into a WAR or EAR file, then simply set the packaging type of your project to EAR or WAR. Maven will bundle the dependencies into the right location.

If you want to create a JAR file that includes your code along with all your dependencies, then use the assembly plugin with the jar-with-dependencies descriptor. Maven will generate a complete JAR file with all your classes plus the classes from any dependencies.

If you want to simply pull your dependencies into the target directory interactively, then use the dependency plugin to copy your files in.

If you want to pull in the dependencies for some other type of processing, then you will probably need to generate your own plugin. There are APIs to get the list of dependencies, and their location on disk. You will have to take it from there.

or use this:

<project>
…
<profiles>
<profile>
<id>qa</id>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

17) Is there a way I can configure maven to always download sources and javadocs?

Specifying -DdownloadSources=true -DdownloadJavadocs=true everytime (which usually goes along with running mvn compile twice because I forgot the first time) becomes rather tedious.

>> Open your settings.xml file ~/.m2/settings.xml (create it if it doesn’t exist). Add a section with the properties added. Then make sure the activeProfiles includes the new profile.

<settings>
<!– … other settings here … –>
<profiles>
<profile>
<id>downloadSources</id>
<properties>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</properties>
</profile>
</profiles>

<activeProfiles>
<activeProfile>downloadSources</activeProfile>
</activeProfiles>
</settings>

NO COMMENTS