Prof. Rodrigo Noll @ IFRS Canoas
“Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information.”https://maven.apache.org/
Considera a Convenção sobre Configuração:
Não é necessário instalação manual usando IDEs
POM significa Project Object Model. Este modelo tem um conjunto de padrões, um ciclo de vida de projeto, um sistema de gerenciamento de dependência e a lógica para executar os objetivos do plugin em fases específicas do ciclo de vida.
Convenção sobre Configuração: usando sempre uma estrutura padrão de pastas, faz com que desenvolvedores se concentrem em codificar, deixando o maven fazer o resto
pom.xml inclui:
pom.xml responsável por:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.edu.ifrs.canoas.lpoo2</groupId>
<artifactId>maven</artifactId>
<version>0.1</version>
<description>Este programa mostra o funcionamento básico do maven.
</description>
<packaging>jar</packaging>
<name>maven</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<project>
<groupId>br.edu.ifrs.canoas.lpoo2</groupId>
<artifactId>maven</artifactId>
<version>0.1</version>
<packaging>jar</packaging>
</project>
Os itens acima representam as coordenadas necessárias ao maven para todos os projetos.
Onde groupId:artifactId:packaging:version: definem o local e o nome do projeto
no repositório do maven.
Coordenadas necessárias para todos projetos:
Plugin é como tudo funciona no Maven, cada plugin é um framework de execução
composto por uma coleção de goals.
ex.: archetype:generate, install:install
Goal pode ser uma tarefa específica ou parte de um build maior.
Podem receber parâmetros e ter valores padrões para estes parâmetros.
ex.: compile, test, package
Alguns core plugins do Maven são:
Maven permite que outros plugins possam ser criados (java, ant, grovie, etc.)
mvn compiler:compile
Exemplo:mvn install
Execução das fases do ciclo de vida
plugin:goal
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building maven 0.1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ maven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ maven ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ maven ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ maven ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ maven ---
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-booter/2.12.4/surefire-booter-2.12.4.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-booter/2.12.4/surefire-booter-2.12.4.pom (3 KB at 1.2 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-api/2.12.4/surefire-api-2.12.4.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-api/2.12.4/surefire-api-2.12.4.pom (3 KB at 7.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/maven-surefire-common/2.12.4/maven-surefire-common-2.12.4.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/maven-surefire-common/2.12.4/maven-surefire-common-2.12.4.pom (6 KB at 14.7 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugin-tools/maven-plugin-annotations/3.1/maven-plugin-annotations-3.1.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugin-tools/maven-plugin-annotations/3.1/maven-plugin-annotations-3.1.pom (2 KB at 4.8 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugin-tools/maven-plugin-tools/3.1/maven-plugin-tools-3.1.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugin-tools/maven-plugin-tools/3.1/maven-plugin-tools-3.1.pom (16 KB at 32.2 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/reporting/maven-reporting-api/2.0.9/maven-reporting-api-2.0.9.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/reporting/maven-reporting-api/2.0.9/maven-reporting-api-2.0.9.pom (2 KB at 5.2 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/reporting/maven-reporting/2.0.9/maven-reporting-2.0.9.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/reporting/maven-reporting/2.0.9/maven-reporting-2.0.9.pom (2 KB at 4.2 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-toolchain/2.0.9/maven-toolchain-2.0.9.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-toolchain/2.0.9/maven-toolchain-2.0.9.pom (4 KB at 10.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-common-artifact-filters/1.3/maven-common-artifact-filters-1.3.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-common-artifact-filters/1.3/maven-common-artifact-filters-1.3.pom (4 KB at 10.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-components/12/maven-shared-components-12.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-components/12/maven-shared-components-12.pom (10 KB at 25.8 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-parent/13/maven-parent-13.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-parent/13/maven-parent-13.pom (23 KB at 56.2 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-booter/2.12.4/surefire-booter-2.12.4.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-booter/2.12.4/surefire-booter-2.12.4.jar (34 KB at 81.0 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-api/2.12.4/surefire-api-2.12.4.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-api/2.12.4/surefire-api-2.12.4.jar (115 KB at 161.3 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/maven-surefire-common/2.12.4/maven-surefire-common-2.12.4.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/maven-surefire-common/2.12.4/maven-surefire-common-2.12.4.jar (257 KB at 260.4 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-common-artifact-filters/1.3/maven-common-artifact-filters-1.3.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-common-artifact-filters/1.3/maven-common-artifact-filters-1.3.jar (31 KB at 75.5 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.8/plexus-utils-3.0.8.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.8/plexus-utils-3.0.8.jar (227 KB at 275.7 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/reporting/maven-reporting-api/2.0.9/maven-reporting-api-2.0.9.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/reporting/maven-reporting-api/2.0.9/maven-reporting-api-2.0.9.jar (10 KB at 28.9 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/maven-toolchain/2.0.9/maven-toolchain-2.0.9.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/maven-toolchain/2.0.9/maven-toolchain-2.0.9.jar (38 KB at 96.1 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/plugin-tools/maven-plugin-annotations/3.1/maven-plugin-annotations-3.1.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/plugin-tools/maven-plugin-annotations/3.1/maven-plugin-annotations-3.1.jar (14 KB at 38.5 KB/sec)
[INFO] Surefire report directory: /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/target/surefire-reports
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit3/2.12.4/surefire-junit3-2.12.4.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit3/2.12.4/surefire-junit3-2.12.4.pom (2 KB at 5.1 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-providers/2.12.4/surefire-providers-2.12.4.pom
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-providers/2.12.4/surefire-providers-2.12.4.pom (3 KB at 6.6 KB/sec)
[INFO] Downloading: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit3/2.12.4/surefire-junit3-2.12.4.jar
[INFO] Downloaded: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-junit3/2.12.4/surefire-junit3-2.12.4.jar (26 KB at 68.4 KB/sec)
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running br.edu.ifrs.canoas.lpoo2.maven.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ maven ---
[INFO] Building jar: /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/target/maven-0.1.jar
[INFO] META-INF/maven/br.edu.ifrs.canoas.lpoo2/maven/pom.xml already added, skipping
[INFO] META-INF/maven/br.edu.ifrs.canoas.lpoo2/maven/pom.properties already added, skipping
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ maven ---
[INFO] Installing /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/target/maven-0.1.jar to /Users/rodrigo/.m2/repository/br/edu/ifrs/canoas/lpoo2/maven/0.1/maven-0.1.jar
[INFO] Installing /Users/rodrigo/Development/eclipseProjects/ws-2017/maven/pom.xml to /Users/rodrigo/.m2/repository/br/edu/ifrs/canoas/lpoo2/maven/0.1/maven-0.1.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 15.941 s
[INFO] Finished at: 2017-06-30T14:48:47-03:00
[INFO] Final Memory: 18M/164M
[INFO] ------------------------------------------------------------------------
Onde os arquivos estão
Como recuperar a referência
http://search.maven.org/Como recuperar a referência
Copiando a dependência no POM do projeto
[...]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
[...]
Arquivos copiados do repositório central para o local (máquina do desenvolvedor)
Pasta ~/.m2 do computador.Os projetos Maven desenvolvidos também são incluídos no repositório local
Pasta ~/.m2 do computador.Se algum produto não estiver disponível no repositório central, pode-se criar um coorporativo que espelha o central e adiciona os produtos faltantes
<project>
[...]
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
[...]
</project>
Notem que a tag de escopo não está definida para estas duas. Se não está definido, o padrão é a fase compile
<scope>test</scope>
Iremos discutir:
Aplicação Web para gerenciar produtos:
Copie o código abaixo após a declaração de dependências:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Como podem ver, tudo no Maven é configurado via plugins
Para recompilar o projeto em Java 8, conforme redefinição do JDK
package br.edu.ifrs.canoas.jee.maven.dto;
public class Product {
private int id;
private String name;
private String description;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
a) Adicione os métodos CRUD na interface: br.edu.ifrs.canoas.jee.maven.dao.ProductDAO
package br.edu.ifrs.canoas.jee.maven.dao;
import br.edu.ifrs.canoas.jee.maven.dto.Product;
public interface ProductDAO {
void create(Product product);
Product retrieve (int id);
void update(Product product);
void delete (int id);
}
package br.edu.ifrs.canoas.jee.maven.dao;
import java.util.HashMap;
import java.util.Map;
import br.edu.ifrs.canoas.jee.maven.dto.Product;
public class ProductDAOImpl implements ProductDAO{
private Map <Integer, Product> products = new HashMap<>();
@Override
public void create(Product product) {
products.put(product.getId(), product);
}
@Override
public Product retrieve(int id) {
return products.get(id);
}
@Override
public void update(Product product) {
products.replace(product.getId(), product);
}
@Override
public void delete(int id) {
products.remove(id);
}
}
Visite MVN Repository e procure a última versão do JUnit
Atualize o pom.xml com esta dependência e depois Update ProjectAdicione agora a dependência da biblioteca assertj-core e hamcrest-all. Atualize novamente o projeto.
package br.edu.ifrs.canoas.jee.maven.dao;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
import br.edu.ifrs.canoas.jee.maven.dto.Product;
public class ProductDAOImplTest {
private ProductDAO dao;
@Before
public void setup(){
dao = new ProductDAOImpl();
}
@Test
public void testCreateShouldCreateAProduct() {
Product product = this.getProduct();
//Busca o produto pelo Id
Product retrievedProduct = dao.retrieve(product.getId());
//Verifica que não existe o produto na camada de persistência
assertThat(retrievedProduct).isNull();
//Cria um novo produto
dao.create(product);
//Busca o produto pelo Id novamente
retrievedProduct = dao.retrieve(product.getId());
//Verifica que o produto de nome Phone agora existe.
assertThat(retrievedProduct.getName()).isEqualTo("Phone");
}
private Product getProduct(){
Product product = new Product();
product.setId(1);
product.setName("Phone");
product.setDescription("Awesome product!");
product.setPrice(100.2f);
return product;
}
}
a) Verifique o que acontece se uma asserção falhar. Para pular o teste no Eclipse:
b) Para pular o teste no Eclipse:
Defina: Name (qualquer), Base Directory (selecione do workspace), Goal (install) e marque o checkbox 'Skip Tests'Implemente a estrutura abaixo e realize os testes dos demais métodos das classes.