You are on page 1of 37
Course Material By Mr. Nataraj Naresh i Technologies, Opp. Saty: an Th tre, ae Hyd. Office: 040- 23746666 Mobi HighLights Introduction to Apache Maven Apache Ant Veisus Apache Maven Key Features of Maven Downloading and instaling Maven ‘Maven Repository Maven Archetype Standalone Maven Projects Web Apps through Maven Maven through Eclipse ‘Maven Inheritance ‘Moven Multi Module Project Life Cycle of Maven ‘Maven Interview Questions and Answers Work hard for what you want because it won't come to you without a fight. You have to be strong and | courageous and know that you can do anything you put your mind to, If somebody -| puts you down or criticizes you, just keep on believing in yourself and turn it into By tr Mataral & Team a MAVEN Overview multiple complicated, eepetitiv ment, execution and deployment there will operations are called build operations. for execution /release is called building project. Doing, + In project develo operations, These ‘Keeping ou" project read ious activities anally is complex and error prone process. ine support of batch file and automate the proce: conditional statements to perform build activities id activities in ‘of build process ma + To overcome this proble 1 The linvtations with bat file is we cannot wnt '¢ this problem we can go for Ant build too! ere we cari automate bul conditional environment by using build.xml file declarative >> Ant is just build Too! bet ¢ cannot be used for project manat fies, maintaining repositories, providing standard directory sttuctutes and ete | To solve those problems of ANT we can use Maven tool which not only Project management tool. #lntroduction to Apache Maven poche Maven is an advanced build tool to support the developer at the whole process of a software | project. Maven acts as both a dependency management tool - it can be used to retrieve jars from a central} fepository ar from a repository you set up - and as a declarative build tool. Maven allows the developer to automate the process of the creation of the initial folder structure for the Java application, performing the } 2, packaging and deployment of the final product. It is implemented in Java which rakes it platform-independent, | compilation, testi, Maven relies on conventions about how project directories are laid out in order to achieve its ‘declarativeness.” for example, it has @ convention for where to put your main code, where to put your | \veb.xml, your unit tests, and so on, but also gives the ablty to change themif you need to, | The real out-of-box strength of Maven is its dependency management, You only have to declare the | dependencies and Maven will download them, setup the classpath for you,and even deploy the dependencies with your application, if required. vs aven Apache Ant versus Apache Maven > Ant doesn't have formal conventions. You have to tell Ant exactly where to find the source, where to put the outputs, etc > Ant is procedural. You have to tell Ant exactly what to do; tell it to compile, copy, then compress, etc. > Ant doesn't have a lifecycle. > Maven uses conventions. It knows where your source code is automatically, as long as you follow these convertions. You don't need to tell Maven where is. | Maven is declarative; all you have to do is create a pom.xml file and put your source in the defsult directory. Maven vil take care of the rest Maven has a lifecycle, You simply call mun install and a series of sequence steps areexecuted. ince about common project tasks. To run tests, simple execute mun test, as, the files are in the default location, In Ant, you would first have to JUnit JAR file is, then ‘classpath that ineludes the JUnit JAR, then tell Ant where it should look for test source ‘a goal that compiles the test source and then finaly execute the unit tests with JUnit. | code, wi % pooguanmt Luby ox bis pin’ piece of code oy called tail Felling, Hi cane ee ukng Juntl, steal tots, sesfy the Cod a ale dere wonually on tp 6 olad. Canqeiny engl tule it acteal new - | rrr a | fy Mir, Nataraj &T MAVEN Naresh i Fevhnobogies [ key features of Maven nave ties to avoid as much configuration a6 posible, by choos’ grea word defaut values and supplsing project templates (archetypes) sndoxeniood jar tiles dynamically -fyem internet ing jar files, plugins and et. > Can mavntain multiple repositories provides standard project directory structures and lupin among the mult 7 Gives Maven inheritance to share jar fil projects + Allows to develop multiple medule projects + Cangenerate jr, war, ear and etc. packeging based components er Application > Can tun unit tests and con generate unit test reports Can generate project documentation Can elean and install the projects in the local servers or remote servers #Downloading and Installing Maven sted by the Apache Link ere it was formerly The Maven project Software Foundation, | part ofthe SokartaProjecu incase youwans xo San Tar geet ae dseeaen from thecommorelin, You nued'® Now suppose you mp tie the D:\mave > Add maven bin folder to PATH vaniabh Variable: ATH ValuescMaven_Home>\pin;; | my caseD:Amaven\apache-maven-3.3.8-bin\apache-maven-3.3.9\bin; > To verify if maven has been configured successfully, invoke mun ~version|or myn -v or mun = version) in the command prompt aes = Fapache Haven 3.3.9 (obdzZz TSZeCOasa3F4c09453c074783I23de5; 2015-21-10T22:11:4 H ; saven apache 2°3.0075, ven wven-3.3,9-bin\apache-maven-3.3.9 i Oracle Carporation gran Fives sava\jauaes.0.73\jre é jes" ebcit,, plasters cheading: cods3 ' ae Bh" orion nels apche eaG6", Family: “dost i i you get the message as shown above, it means you have successfully Installed and configured Apache ‘Maven in your windows machine. 1aven, all configu bet! ans will be done in pom.xml file 7A Practical Approach To Learn th Naresh /Tectmoloves taavens 6 introduction to Maven Repository — 1. Hataraj& Tear > According 10 haven Ollie ! ito Documentation, “A repository in Mover is used to hold build artifac arid ae of varying types."A maven repository isa place Le. directory where all the f jars, librery ja, plugins er any other project epecilic artifacts ane stored and can be used hy Maven ca.ily-Thete are three types of repository in maven. They are XH boca : 7 tore fon be ruudbyle oenbrr of ron élp 2/eontral Nepeadteniey Conpig. iy pom. rum remote A wen reepohihnies » conlecin ~wevee 1. Local Repository: ~ jong (4% blew seg ) > Its user specific repository, generally it will be collected from TL/PL who creates Maven project directory struc > Contains jars, plug re. jee Meng [P05 oy = 7] Jroup Coespany ep ins, curtent prjectrelatee packings and ete > Default location: elusersteuseramae>\.m2\ typo diy > willbe created automatically for ary maven command apart from (myn version) . _— fr sox Gitesped rat hee Mea versed Jesse a es SD Yeasogy dod [vorsiog 7 2 | rae | > Location can be changed through \conf\settings.xml file using Poosebb 4 d:\ \mavenc/locolRepository> 2. Central Repository: > Avaialble in internet, managed by Apache Maven Community. When Maven does not find any dependency in local repository, it starts searching in central repository. > URL for central repository: http://repo.maven.apache.org/maven2 > Generally maintains free jars and plugins of open source technologies Remote Repository: Either company specific or Vendar specific repositories | Example UNG repository, Jboss repository \Willbe used only when tag cfg. in pom.xml vyyy 7 Practical Approach To Learn Maven oy Mr. Nat Mavend atest Technoloties de all centigurati the heart for maven tool. This pom.xml contains in maven through porn.aml sieet details, packing details (jar/war/ear and etc.) plugin details, remote repository details and dependency(jan} details andl etc. = > idepindon ai ereprestorieny he (wetson) With reference to the above diagram 17-3 taaven frst searches in Local repository 1.5-d1f available >pives jar file to app 22 if not available in Local repository, it vill search in central repository 2.5-9if avalable in central repository, it will downlaad in lal repository and gives to maven app. —E _ ‘Practical Agproath To Learn Maven 2S es & 3:4 not available in central repository, it pom.xml ill search in remote repository by checking tag In AIF not available error will be raised 4.51f available the jar will be downloaded to local repository and will be given to maven app. dor's hat is downloaded to local repository from pecific remote cific remote tory, It is recommended to push 10 company specific cloud repository or company spe repository #HMaven Archetype iced Stodoss peod. did. prowabese- + It ise maven project templating toolkit that helps users to create different types of maven project having maven Supplied fa ities and user supplied inputs 00+ archetypes are supplied by Maven to create different types of project. The popular > Nearly 1 archetypes are | | i Archetype Artifactids Description | maven-archetype-quickstant ‘An archetype ro generate sample Baven poke. | Aan | maven-archetype-webapp #n archetype to generate @ sample Maven Webapp project. ———— | maven-archetype-j2ee-simple An archetype to generate @ simplifed sample J2EE application. To know more about the different archetypes and its functionalities visit maven.apache.org/guides/introduction/introduction-to-archetypes.html > Every project directory structure gives pon:.xml with minimum details. We can add more tags in that as needed } Every Maven Project, dependency jar, olugin and etc are identified with 3 minimum details. groupld-> Generally company name artifactid Project name/jar name/plugin name version syn:-SNAPSHOT/RELEASE/FINAL/BETA #Generating project through Maven We can create maven projects in any folder of your choice in any drive, Here | am creating it in d:\maven folder. To create a new project based on an Archetype, we need to call myn archetype:generate goal, like the following: #Example1 (Generating project in Interactive mode) to create your project 4nd Call myn 7} ~ Open the. Command Prompt and cha archetype:generategoa! to beain the pro nge direc ess 8 > some time, This is because Maven first | this 1s the first time you execute his moy toke some time member If this is the first time you execute this gool, t i may te a ifen rom the. Moen tenth Ret Joads all required plug-ins and artifacts for the project gen repository, D:\maven>mvn archetype:generate As soon as you hit enter button, it will start loading all the available artifacts and begins interaction with you like: Choose a number or appiy filter (format: [groupld:Jartifactld, case sensitive contains): 902: Here you nave to cither enter the archetype number for which you are going to create your project or apply the filter (nothing but filtering archetypes from the list loaded). First of all, we are going to see how to create the standalone project. So, type maven-archetype-quickstartand hit enter. Now, simply choose the archetype (hit enter key] and supply the propert configuration and confirm it as shown below. choose a number er appl ntains): 9¢ choose’ arch remot Filter (format: (groupid:Jartifacttd, ‘case sensitive co maven-archetype-quickstart apache .maven archetypes :maven-archetype-quickstart (An archetyp c which contains a sampie Maven project.) . neaiagy? Tumer oF apply filter (Format:” [grouprd:Jartifacttd, case sensitive co ntaias ache. maven archetype: laven-archetype-quickstart version: choose’ org : Lo a qumber: 6: value for property ‘grouptd': : naresh value for property ‘artifactid’: : MathProjt value for property ‘version’: 1.0-SNAPSHOT: Define value for property ‘package’: naresh: : com.nt Confirm peopersies configuration: : naresh \jsetifactid: MathProj1 i Wersion: 1.0-SNAFSHOT (package: com.nt Pe ee ecmneror Io mown btenelalont pet the bon ple Of rato few Lonel Ane mratn ] Jawa. bamilirdy Ube bow pew fr unit teling Boverees “Aref Wt / Jove ctory structure looks like the follo 3.5.4 Meyen — arch) onchit Lay - qudchatant ye Mumbo |-sAppava test le The Kenclarsl oc. ipeit peter in Maven [->pomam! Aven. ¢ op java write the following piece of code} AMowdalau pret & is) 5 . wicn lab’ * Breqsaone peries x O-Bem ited! akuniype- 2 \ erwin Sana —y oe eo Sowgee ne Ate ! Saclenpiel eH 10 place capt rePNpy save public static vous main{ Steingl] args H Sytem out prntinl “Hello World!” yw HAs int result app.add(10,20); e1n.out pein Mesult™+ result); 11 out peintin( “End of the App"); Now start runnin, the following, maven goals. By Nt. hei ee \ Naresh (Technologies \.....\MathProj mun compile > Compiles the Appjava (all source file D4.....\MathProjl>mvn package | meosver jar file | ~ Generates jar files in target folder having mvn clean ~ Cleans che project .. deletes targe der | \sou\MathProji>mun clean package | ~ Cleans the project and also creates jar file with latest code | | Torun jo file App manually MathProjl>java -cp target/mathProjl-1.0-SWAPSHOT.jar com.nt-APP #Maven Unit Testing and Unit Test Report With the help of u we cen run the test cases can generate unit test reports in HTML. Maven does so by runnin Unit tests and recording the results of the unit tests. Maven then generates en HTML report from the unit results, We can then read the report to see if any of the unit test have failed during the build. Open the AppTestyava | java file(D: ‘\maven\MathProj1\sre\test\java\com\nt) of MathProjl projec: and do the foll ng changes testAdd() method AppTest.java er! By default Maven’s pom.xmigives tag to download junit jar. So, we can w test cases in Proj\src\test\java\....... AppTest.java) bute void testAdd() { int x=10; int y=20; int expected=30; int actual=new App().add(10,20); Assert.assertEquals("Result1" expected,actual); Now let us run the above test cases and generate the test report. The Maven unit test reports are generated by the Maven Surefire plugin. Therefore such unit test report is also sometimes referred to as surefire report. DA... > Torun these test cases \MathProj1>mvn test \MathProjl>mvn surefire-report:report DA. > Torun test cases and to get test report aa CEE ae eee tae CEE See Dd. \MathProjl>mvn surefire-report:report-only * To get test report directly | (ote: We can get test report in target/site/surefire-report.html form) D:.......\MathProjl>myn install > To keep generated jar file (Application jar in Local Repository The above jar file can be placed in local repository in other maven projects by specifying , , tags in tag Di\v...0\MathProj1>myn site + To get documentation about total project. (generates project document in target/site folder as index.htm! file) While writing iag to download the jar file, we can specify the scope by using tag. The possible scopes are compile, runtime, provided, system, test, import etc In. pom.xml iuniteeroupls> artifactid>junit 4version>3.8.1 focopertestfscope> Maven is having three life cycle and each life cycle is having certain phases. By specifying these lifecycle phases, we can configure plugins in pom.xml so that plugin will perform the activity at the specified phase. | The Maven Life cycles are a. clean(3 phases) b. default(23 phases) c. site (4 phases) et! If you ask maven to perform 17" phase (package) of default life cycle, it also performs the pemette’™” —semaining 16 phases in a sequence like compile, test-compile, test and etc... Vi€reatn standalone maven project in non-interactive mode Syntax: mvn archetype:generate 10 -Dgroupld=groupid Dortifuctidzartifactid DarchetyneArtifactid=maven-orchetype-quickstart DinteractiveMode=booleanValue ample: GenerateSqrRoot given number. am cr ct to find the square root of Here we will create a simple standalone pr my maven projects in D:\maven folder Rrovage, Coot test | myn archetype:generate oS “Dgroupld=com.nt s\ox081 -Dartifactid=GenerateSqrRuat ack PSS -DarchetypeArtifactld=maven-archetype-quickstart | -DinteractiveMode=false Here, we are instructing the maven to create the project directly without interactive mode. Run the above command in command prompt specifying the path where you want to generate the project directory structure. (Caution:while executing the above command make sure it is in the single line as shown in the picture below.) cows Sistema cd exe O:\maven>mvn archetype:generate -DgroupId=con.nt -DartifactId=GenerateSqrRoot -D orchetypeartifactId=maven-archetype-quickstart -DinteractiveMode=false Computer» Entersinnent (02) maven» oy : o As we can see in the above picture, after the successful execution of the maven command, the ‘App.java” java file. Now let's customize and write our own logic va” and write our own logic. directory structure is created with to generate square root. Rename that file with “SqrRootj maven » GenerateSqrRoct + src + main + java >» com > at Date modified "| In SqrRoot.java -qpackage com.nt; [ne * Generate SquareRvot of a given number | itnport java.util Scanner import javalang. Math; jullie lass Sqrtoony H i ‘| public static void main(String arysl})} Scanner = new Seaninest System Jn) Systemcut printny*Enter number to tind its square root") oxtint moult pvintin| Math,sqrin) Now, we will compile and execute our standalone project with the help of maven. For this we need a plugin “exec-maven-plugin”. What actually is this plugin and what it does??? Official documentation says (http://www.mojohaus.org/exec-maven-plugin/} Exec Maven Plugin provides 2 goals to help execute system and Java programs. + execiexec execute programs and Java programs in a separate process. + exec:java execute Java programs in the same VM So, we need to provide this information in pom.xml of the our GenerateSqrRoot project. |, Add the following cfgs in the pom.xml of our project after or before tag, Jn pom.xml org.codehaus.mojos/groupld> exec-maven-plugin 1.4.0¢/version> -com.nt.SqrRoot Execute the project with following command Invoking “myn exec:java” on the command line will invoke the plugin which is configured to execute the class “com.nt.SqrRoot’. So, to trigger the plugin from the command line, just run: D:\maven\GenerateSqrRoot»myn compile Once code is compiled, the following command runs your class } :\maven\GencratesqrRoot>mvn package D:\maven\GenerateSqrRoot>myn execsjava (Note: while may arts execution, supply your desired integer value to get the square root) Tor prajeets ee grec-maven-plugin: 1.4.0: 3av3 (detautt-e14) & Generatesarn rnunber'te Pind v2 Square reek #7) FSmaghed at Final womens a Now let’s run the same project with little bit of twist. W Nw Specifying the class name in the command related tag in the pom.xmi insid ur pom.xml now looks like this € can run the same project by itself. For this we have to remove the je tag that we just placed. So that : org.codchaus.mojo exec-maven-plugins/artifactie> 1.4,0¢/version> Syntax for execution mvn exec:java -Dexec.mainClas: ‘com.nt.module.MoinClassName" Execution: D:\maven\GenerateSqrRoot>mvn exec;java -Dexec.mainClass="com.nt.SqrRoot" fi: \maven\GeneratesqrRoot>mvn exec: java -Dexec.mainClass="com.nt .SqrRoot" (INFO| Scanning for projects... INFO: | CINFO: : | Euro --= axec-maven-plugin:1.4.0:java (default-cli) @ Generatesqr JEnter number to find its square root: en ‘9.0 ance} Building Generatesqrroot 1.0-SNAPSKOT Let’s explore more ways to run the same project. Now, if you want to execute the exec:java goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase to which you want to bind the goal in the execution element: For this ¥ (phase of your choice ike package, test etc pom.xml. So, the changed pom.am! looks like the follows POM nainClass>corn.nt SqrRoots/mainClass erateSqrRoot>myn package ‘Mote: This exveutes com nt.SqrRoot class during the package phase) me mi mane cue dor cra att Wet He x1 rid Example: SvapLemolmd This is just a proof of concept example, Hei to see how to specify command line arguments | He are goin through command line along with maven commands and how to specify arguments in the pom mt through org.codehaus.mojo exec-maven-plugin 1.4.0 org. apache. maven. plugins maven-orchetype-plugin 2.4 « | Execution. | 's command line #8 enecute 's see the syntax to do so. 2. sject, let's see the sy Hee eevee basco line arguments to execute this proje Syntax i Yome" ="arg0 argl arg2" mvn execijava -Dexec.mainClass="com.nt.module. MainClassName" -Dexec.args* gt Here, | will pass 8 and as arguments. So the command looks like this D:\maven\SwapDeri0Cmd>mvn compile D:\maven\SwapDemoCmd>mvn package D:{maven\ SwapDemocmd>mvn execsjava -Dexee.mainClass="com.nt.SwapDemo" -Dexec.args='8 4" om.nt .SwapDeno” -Cexec.org 9: \maven\swapDemecmdrmvn exec: java ~Dexec.mainclass Hee Enrol oo jilinre) | [ESO] 20% Vang’ Snapbenacad i.0-Suarsior fi vec-raven-plugin:1.4.0:java (default-cli) @ swapdemocmd ~~~ 2018~11-30737:45 6/165 Wouldn't it be great if we can specity arguments in the pom.xml itself and run the project in a maven phase? For example, we can run the SwapDemo.main() method as part of the package phase. To specify the arguments in pom.xml, we write under tag. So, mention the following configurations in pom.xml of SwapDemoCmd project. In pom.xml org.codehaus.mojo ] Bull by plagin fr yp” om ution, exec-meven-plugin 1.4.0 9 ny Unud b defeult Ue cayche package J — MAVEN. By Me, Natars] & team “Tom Ge Of plgin Al epable of necwhity jam Yedl, — Me ua to be oneeuiled by plug in. Conamarelling orgamert a Dr tuoltime nocae cell tat yp? hy erceaby Opp rranuedly bcoz no recorded info voll be Tore. bo develeper we jrbnite fplugin> fete] of cawironmaed © t tut the code prparatd i ‘ ing, this by min Z , Fr nan EDL a EG TS plugin eSith lain plese we Cen rrakt mawen to] erecule- be apr a pert of bell) pro D:lmaven\SwapDemoCmd>mvn package Converting Maven standalone project into eclipse project D:lmaven\SwapDemoCmdemvn celipsereelipye Open SwapDemoCmd from Fel ing File menu-Pimport-SGeneral-SFsisting Project into Workspace->Browse the Root Directory seupDemoCnd) of the projec. ftGenerating Maven web project by using maven-archetype-webopp | mn archetype:generate -Dgroupld=com.nt.serviet -Dartifoctid=WishApp -Darchetypeartifactid-maven-archetype-webapp -Dpackage=com.nt.servlet -DinteractiveModesfalse [azmbacgoanre,asetsseessennar she. perowbkssropanecsgiedes, Porsicact™spyien Hit enter key and you will get the following director structure ‘APractical Approach To Learn Maven (Incase if com.nt.serviet package is not created, create it manually) | 9 com/nt/serviet folder > WishServiet.jave, copy the following code In WishServlet.java Package com.nt servlet -servlet; ‘WishServletjava import java io.t | import java titer; import Java.util.celendar; import java.util pau ception; ©.Prin: import javax.servlet import javax. servlet -http.Httpservle import Javax. servlet. htcp.HttpServietRequest; import Javax. servlet. http.HttpServietResponse; Servletexception; | PublicclasswishServietextends Ht Publicvoid doGet (Httpserv. Servletexception { tpServiet { letRequest req, HttpServietResponse res) throws IOException // General setcing res.setContentiype("text/htm"); Printiriter pw = res.geturiter(); Calendar calendar = Calerdar.getInstance(); int hr = calendar.get (Calendar. HOUR_OF DAY); Date d = new Date); Pa-printIn("
Date and Time is “+d +" GOOD MORNING") elseif (hr'<= 16) Pw.print1n("

GO0D AFTERNOON

") ; elseif (hr <= 20) : Pu.print1n("

GOOD EVENING

") 5 else { : Pu.print1n("

G00D NIGHT

") ; //close the stream pw.close(); }// doGet(rea,res) @Override fees Reese Rss geese eea sees See | An Publicvoid GoPost (Atepservie tException, exception { ‘ToDo Auto-generated method stub wager (req, res); oo) quest wa java servlet -apic /ertifactla> L.@e/version> laven Marelre} cliruclordte fo wd Sorat i Are] omin) jaa to heey Lose vay ik fo hep Joma tases ay [mein ) resenneed 19 preperbig Eee I Ao ota hap bo hetp hn ep eee) Tet "17 watt Fea, Execution D:\maven\WishApp>myn package > When you get BUILD SUCCESS while executing the above goal, one war file will be created in targe folder of WishApp application. (D:\maven\WishApp\target\WishApp-1.0-SNAPSHCT.war) Now, start the tomcat server and deploy the generated war file (copy and paste WishApp-1.0- SAPSHOT.warin /webapps folder) > http://locathost:4040/WishApp-1.0-SWAPSHOT/ #Working with Tomcat? Maven Plugin app” Like Looulet fil fits code. > We can even work with embedded tomcat server and deploy the generatedwar file. For this we have to use Tomeat7 Maven Pluginand provide its configuration In pom.xml, Place the following piece of code in WishApp/pom.xmi after or before tag, App/pom.xril ill alName>Wichpporg pache.tomcat.m groupld mifactld>tome /en-plugine/artifactld: Config: contextPath and Port (Default - /WishApp : 8080) configuration: http://locathost:2020/manager/W shAppe/path: ‘/configuration> /plugin: plugins» ui: During deployment, this cfg tells Maven to deploy the WAR file to embedded touncat server via “http://localhost:2020/manager/", on path “/WishApp” Execution D:\maven|WishApp>mvn tomcat7:run -Omaven.tumcat.port=9090 Note: While executing, we have to mention the port number on which it will un, Aiter executing this command, if we get the following message in the command prompt INFO: Starting ProtocolHandler ["http-bio-9090"] then open any browser of your choice and run the web-application (http://localhost:9090/WishApp) Rather than specifying the port number in command prompt, we can do it through pom.xml also with the | following cfgs. Jn pom.xml ee http://localhost:2020/manager /WishApp 080 Execution: D:\maven\Wishapp>mvn tomcat?:run Test the App with this url: http://localhost:9090/WishApp Commands to manipulate WAR file on Tomcat. > mvyntomcat?:deploy — //deployment * myn tomeat?:undeploy //undeployment 7 mvn tomeat7:redeploy j/redeployment #Maven Eclipse In order to work with maven inside eclipse, © have to install M2E Settings 2.0.4 plugin from eclipse | marketplace in > M2E Settings 2.0.4>install Help menu + Eclipse Marketplace > search maven pl Eclipse Marketplace Select solutions to install Press Finish to proceed with installation, * ‘ormetion button to seea detailed overview en a linkto more infointion. Search Recent : Popular {Favorites | Installed! November Newsletter Science) Find SLL All Markets ¥_ -AllCategories seartn Termaven plugin M2E Settings 2.0.4 _. Specify eclipse formatting "ules and plugin settings only ence in your Maven = project definition snd have evensbody on yourteam ute the same settings. No = more. more info magen me maven-eclipsa-pluoin Sext Set fas ate lal eae | #Creating standalone maven project in Eclipse CCIE cenrssroneucumaes resmiracamenbareinste rt Haresh : Technologies MAVEN File>NewS Maven uickstartand enter Groupld and ject > Next > choose maven-archetype- Artifactid as shown in the: crested, as shown in the diag diagram, The default project directory structure “ly created project directory structure, the default JRE System Library [J2SE-1.5] 15) fs token even though you might have installed some other versions of jdk (may be | i 1.8). According to maven documentation: “at present the default source setting is 1.5 and i target setting is 1.5, independently of the JOK you run Maven with. If you went to chonge these defoul ould s o it air You should set source and target as described in Setting the -source and -target of the Java Compiler the gefa: You 3A solve this issue (applicable both in n case of standalone-quickstart and webapp kind of application) by doing certain configuration in pom.xml | and updating the maven project. Let's see how to do it. | Step: | Add folto #8 configuration aftertag in IdbcSelectapp/pom.xml. In idbeSelectApp/vom.xml SelectApp:/finalName> and to 1.8. You do the changes as per your Jdk installation, Step2: Update the Maven project Right click on the JdbcSelectapp->Maven~>Update Project..>Update Maven Project dialog box will appear. Make sure JdbcSelectapp Is checked-> Hit OK button. You are done... Once you are done with all these modifications now let's focus on project development. Add packajye com.ntjdbc to src/maln/java folder, > Create on java class SelectTest. java under com.nt,jdbc package of JdbeSelectApp. Now, we are going to work with oracle database whose jar file is commercial. Commercial jar files are not available in central repository. At the same time we cannot collect then from remote repository because they are commercial. In this situation, we can directly add them to local repository by using mun install:install gc -Iin command prompt. mn install:install-file [ c | file | Theequivalent tag is ~Dfile=spath of ojdbc jor from your local | | | system> | th oracle -Dgroupld=oracle || sartifactid> ojdbe6 -Dartifactld=ojdbc6 || sversion>11.2 | | Duersion=11.2 rk But there is a Good News for lazy programmers like us is, if you don’t want to install this 28 ojdbc jar manually, there is one third-party supplied simulator jer file for ojdic6.jar in \ maven centralrepository. Just add its dependency and enjoy all database related application development through maven. So, you can add the follow you don’t want to go with the above step. | com.hynnet a comuntjalbe | Dy SelectTestjava 12.1.0.1 tem y Bs, Maven Dependencies ee ea In SelectTest.java pom.xml package com.nt.jdbC; nection; armanagers import java.sq) import jave import java.sql-Resultset; jmport java-sq1.SQLexception; import java.sqi-Statement; publicclass SelectTest { ceivetestaticfinal String SELECT_MAX_SAL="SELECT ENPNO,ENAVE,20B, SAL FROM EMP WHERE SAL=(SELECT max(SAL) FROM EMP) "5 publicstaticvoid main(String(] ares) { ‘Connection con = null; statement st ResultSet rs = null; try ( //Register the typed oracle driver Cless..fortlame( "oracle. jdbc. driver OracleDriver” : //Get the Connection object conzbriversianager. getConnection("jdbe:oracle:thin:@localhost:1521:orc]", "scott", "tiger”); // Create the Statement Object if (con != null) st = con.createStatement(); JT Send and execute the SQ query if (st 1= null) rs = st.execut Query(SELECT_MAX_SAL); ing if {7 Process and execute the ResultSet object aif (rs t= null) { System. out. prin | ws-getrnecay); Tin(rs.getInt(2) +" "4 rs.getString(2) +" " 4 rs.getString(3) + | } 4 while | ) | ) 20 ay ‘ception se) { ception cfe) { intstackTrace(); } Finally try { if (rst , rs.close(); } catch (SQLException se) ( Sel.printStackTrace(); try { (st t= nulay st.close(); } catch (sQlexception se2) { ; S@2.printStackTrace(); try ( af (con t= nulay con.close(); } catch (SQLException se) { se.printStackTrace(); } } // finaly W/ main J//class > Finaliy add the following under tag inpom.xmlspecifying thecmainClass> eee eset org. codehaus .mojo exec-paven-plugin 1.4.0 com.nt.“dbc.SelectTest Execution Right click on JdbeSelectapp>Run As Maven Build..> Specify the Goals: (exec;java) >Run COEUR EO EEE EOE OIC DOU DEC EDO IE LEE HEHE EEO EOE CLO OL ene eE steer Another useful feature of maven is that if we add tag for main jar file in pom.xml file, it downloads mian and dependents jar files. Yaresh i Technologies MAVEN Example: If ee By hr, Nataraj & Team add tag for tag, it nat only downloads thi jar | ae -core>tag, it not only down main jar Tile, also downloads lot of dependent jar files : ae Tepositories>/ ta, we can make maven even d ositeries to local repositories if they are not : unloading jar files from remote | vailable in central repositories Example: Resttasy jar files are available in repository maintained by JBOSS, 0590055 kepesitorye/id> curl ohttps://repository. jboss .org/nexus/content/group/pudlic-jboss : ore eee FR OS | tag having other project info like , and = $$ cersins to get other project dependencies | | and plugins. | nareshc/ groupra> Example: In pom.xml of HBProj2, add this code | cartifectId>Miproj | to get plugins and dependencies of HBProjl. Create any Sample Project (say HBProjl with | e/parent certain dependencies) and add having et dependency info oF HBProj1 in pom.xml of |) B ererteava » Bh Librarer JavaScript Resources > C5 Deployed Resources > Create package comunt.serviet under sre/main/java and oS ne add WishServietjava class. Copy and paste the same logic, 3 mein project properties. in WishServiet java as we did previously, configure the ° servlet in web.xml and if you want you can even work with E resource: Tomcat? Maven Plugin by adding its configuration in 4G webapp pan > EBNF i ik) webamt B insarep We can run the above application in the following ways. Goteoe } Run the applicatior .s normal Run on Server application by ‘(A Femsnt configuring tomcat with eclipse | esate B excupie: [Soma 2 22 Wishépe er ¢ ne ted |) Aric ia a Run As maven build.. goals=clean package as discussed earlier and use Run as maven bug in xml as discus: a i Configure maven tomeat plugin in pom. ’ goals=tomcat7:run #Maven Multi-Module Project | Whatever project we created se far are single module projects. The concept of Multi-Module Project is very simple. When various modules are part of @ project and closely related to each other, then the project should be structured as a muhi module project. Ina multi module project, Maven ensures that alt sub | modules are built in proper order before the main module build. According to agile methodology, we take multiple layer: as multiple modules in a project i.e. all DAO | classes together in one module, all service classes together in one module and all web components | together in one module. To develop such projects in maven, we can take maven multi-module project. | Example: StudentMgmt (Proof-Of-Concept example) * We will split StudentMigmtApp in two modules, StudentServiceMod and StudentWebMod. 1. Creating Maven Project by taking packing as pom at Click on File > New —>Maven Project > check Create simple project > Next Enter Groupld:NVaresh, Artifactid: StudentMgmt and Packaging: pom > Finish AServiceMod &@ porn 2. Add maven module to Studentigmt project having name StudentServiceMod (use quickstart archetype) Right click on Studentigmt app> New > Others Expand 4 {2 StudentServiceMtod Maven dir. > Select Maven Module > Next->Module Name: + © s#*main/jave StudentServiceMod-> Next select quickstart archetype >Next — : iy stue 23 > Finish & B srettestjave 3. Add one service class in StudentMgmt project in —” 5 Maver Dependencies iP BB JRE System Library (+. «52+ src/main/java package Lo » & tanger 4 pomam! In StudentService Bi pom: package com.nt.service; publicclass StudentService { publicint getRank(int no) { return 100; }//getRank(-) Wiclass 4. Add maven module to StudentMgmt App having name StudentWebMod (use webapp archetype) Right click on StudentMgmt app > New ~ Others > Expand Maven dir. > Select Maven Module > Next->Module Name: StudentWebMod~ Next > select webapp archetype >Next > Finish Pease eee eee eee eee cece eres eeee ee ee eee -eeeeH sree eee eH seca see eee ‘Add ta, jar tag for StudentServiceNtod in pom snl of web module * and also studentse:viceMod 6. Add fotlowir code in in gouls: clean package eral FAQs on Maven to exclude the conflicting jars while we are working with multiple technologies d jar in pom.xml in a simple way? © have already added jars in pom.xml) 1. One way is to manually write the tag. Following is the example carp factid>spring-contexts/artifactio» | cversions§.2.3 | ci Eaiude Commons Logging in favor of SUF4) ~ | censuvon> | | | | 2. Se-ond way is 10 exclude it with the help of Dependency Hierarchy nans making en | The advantage of ‘automating the build process is that you minimize the risk of hur neal at ‘while building the software manually. Additionally, an automated build tool is typically fa a human, Performing the same steps manually How to configure remote repository in maven pom.xml? | > By using tag in pom.xml before or after tag. For example: inject jor | {ebsted dependency in not avaitable in central repostory but its avaiable in repository maintained | by Redhat. | (eae eS | | sid>redhateyids. javax.inject 1.0.0.redhat-6 | j Maven Project-> Next> Configure Add Remote Catalog-> In Catalog File hitos://repoi.maven orz/maven2/archetype-catalop.xml, In Description: RemoteCatalog> Verify(wait till allarchetypes are downloaded)-> OK-> OK-> (make sure in Catalog, RemoteCatalog.is choosen) Now filter || for webapp-jees archetype and choose it>Next>Enter groupid,artifactid end create your project. #Maven Interview Questions and Answers 1. Explain what is Maven? How does it work? a S52 project management tool. it provides the developer a complete build lifecycle framework. On executing Maven commands, it will lock for POM file in Maven; it will run the command on the resources described in the POM. 2 List out what are the aspects does Maven Manages? Maven handles following activities of a developer * Build + Documentation + Reporting * Dependencies i + SCMs | © Releases © Distribution 2 Mailing list 3. Mention the three build lifecycle of Maven? + Clean: Cleans up artifacts that are created by prior builds * Default (build): Used to create the application * Site: For the project generates site documentation 4. Explain what is PON? } In Maven, POM (Project Object Modell is the fundamental unit of work. It is an XML file which holds the information about the project and configuration details used to build a project by Maven. 5. Explain what is Maven artifact? > Usually an artifact is a JAR file which gets arrayed to a Maven repository. One or more artifacts a maven build produces such as compiled JAR and a sources JAR. Each artifact includes a group %, an artifact 1D and a version string. 22 | Explain what is Maven Repository? What are their types? > A Maven repository is a location where all the project jars, library j particular project related artifacts are stored and can be ea: fl us t local, central and remote. “oo 7. Why Maven Plugins are used? Maven plugins are used to 7 + Create a jar file + Create war file + Compile code files «Unit testing of code + Documenting projects + Reporting 8. List out the dependency scope in Maven? > The various dependency scope used in Maven are + Compile: It is the default scope, and it indicates what dependency the project + Provided: It indicates that the dependency is provided by JDK o runtime «Runtime: This tells that the dependency is not needed for compilation but | execution = Test: It says dependency is available 0} + System: It indicates you have to provide the system path + Import: This indicates that the identified or dependencies in that POM section nly for the test compilation and execution phases din Maven? set of the elements existing in the POM itself. 9, Mention how profiles are speci >. Profiles are specified in Maven by using a sul 10. Explain how you can exclude dependency? > By using the exclusion element, dependency can be excluded 14, Mention the difference between Apache Ant and Maven? > Apache Ant Maven «Ant isa toolbox — Maven is a framework «Ant does not have formal conventions like project directory structur information on what to make & how to build) «Ant does not have lifecycle; you have toadd sequence of tasks manually ~ Maven has a lifecycle + Ant scripts are not reusable ~ Maven plugins are reusable 12, In Maven what are the two setting files called and what are their location? > In Maven, the setting files are called settings.xml, and the two setting files are located at «Maven installation directory: $M2_Home/conf/settings.xml «User's home directory: ${ user.home }/ .m2 / settings.xml 13. List out what are the build phases in Maven? s, plugins or any oth Maven. Their types are is available in the classpath of r web server or container at is required during pecified POM should be replaced with the re - Maven has conventions 2 ant is procedural; you have to tell to compile, copy and compress ~ Maven is declarative ( . phases in Maven are + Validate + Compile \ a + Package + Install + Deploy 14. List out the build, source and test source directory for POM in Maven? + Build = Target + Source = src/main/java + Test = sre/main/test 15. Where do you find the class files when you compile a Maven project? * Youwill find the cla lass files $(basedir)/target/classes/. 16. Explain what would the “jar: jar” goal do? © Jr Jar will not recompile sources; it will imply just create a JAR from the target/classes directory considering that everything else has been done 17. List out what are the Maven’s order of inheritance? * The maven’s order of inheritance is + Parent Pom + Project Pom + Settings + CL parameters 18. For POM what are the minimum required elements? 7 ‘The minimum required elements for POM are project root, modelVersion, grouplD, artifactiD and version. 19. Explain how you can produce execution debu; ig output or error messages? > To produce execution debug outp: tut you could call Maven with X parameter or e parameter, 20. Explain how to run test classes in Maven? * To run test classes in Maven, you need surefire plugin, check and config setting.xml and porn.xml for a property named “test.” ure your settings in > By default, the location of the generated jar is in ${project.build.directory} or in your target directory. We can change this by configuring the outputDirectory of maven-jar-plugin 21. How can I change the default location of the generated jar when | command "mvn package"? 22. What is a Mojo? ' & Amojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos. 23, How does Maven looks for a dependency or resource? > It refers to the settings.xml to look for the repositories to look for the reource. First It looks into the configured local repository, then it looks into the configured Remote repositories. if the resource is still not found, it looks it within maven repository centrali.e repo maven.org, its still not found, it throws the exception saying "Unable to find resource in repository central” 24, What would you do if you have to add a jar to the project using Maven ? If its already there in Maven local repository, We can add that as a dependency in the project pom file with its Group Id, Artifact Id and version. We can provide additional attribute Syst empath if its unable to locate the jar in the local repository. If its not there in the local repository, we can install it first in the Jocal repository and then can add it as dependency | 25. Have you ever had problem getting your projects in eclipse refreshed after you made changes in | the Pom files ? | > Yes, It happens many times but | would usually perform mun eclipse:eclipse and this would resolve | the project refresh problems. | 26. What is the difference between compile and install ? | > Compile compiles the source code of the project whereas Install installs the package into the local | repository, for use as a dependency in cther projects locally. | 27. How can we see Dependencies for the project and where exactly they are defined ? | Using myn dependency:tree 28, What is a transitive dependency? Can we override Transitive Dependency version and If Yes, | how? + Transitive dependency is the dependencies not defined directly in the current POM but the POM of the dependent projects. Transitive dependencies allows to avoid specifying the libraries that are required by the project which are specified in other dependent projects - Remote or Local. Yes we can override transitive dependency version by specifying the dependency in the current POM. 29, Whats a cyclic dependency ? > Ahas dependency of B, B has dependency of C and C has dependency of A. > With Maven 2, came transitive dependency wherein in above scenario, C will acts as a dependency of Aas if this dependency has been defined directly in A but the negative side is that if it leads to cyclic dependency , it creates problems. 30. What is a project's fully qualified artifact name? a. :: b. : ¢. :: d. : Ans. :: MAVEN a same (or missing) elements’ Naresh i Technologies nor have two plugin executions with the 31M message mean? rat does the "You cann . Provide each > Itmeans that you have executed a plugin multiple times with the same with a unique then it would be ok 32. What means SNAPSHOT in Maven? deployment copy. Maven checks during ech 7 SNAPSHOT is a type of version that indicates a current build for 2 new SNAPSHOT version in the remote repository 33, i 3. What is the difference between version and SNAPSHOT ? * Maven will downlo: e 5 eee wnload always latest SNAPSHOT. always the specified version. In case of SNAPSHOT Maven wil download the

You might also like