Modern Java Development

35
016 IKERLAN. All rights reserved ©2016 IKERLAN. All rights reserved Ikerlan – Java 8 Ángel Conde– [DevOps & Data Engineer] 2016/4/6

Transcript of Modern Java Development

Page 1: Modern Java Development

©2016 IKERLAN. All rights reserved©2016 IKERLAN. All rights reserved

Ikerlan – Java 8

Ángel Conde– [DevOps & Data Engineer]2016/4/6

Page 2: Modern Java Development

©2016 IKERLAN. All rights reserved 2

Outline

1. Maven – Solving the Dependency Hell

2. Java 8 – What's new

3. Logging – Understanding the JVM logging system

4. Useful libraries – do not reinvent the wheel

5. Testing – Mocks Everywhere

Page 3: Modern Java Development

©2016 IKERLAN. All rights reserved 3

Automatize your builds

Tasks called phases.

Dependency management via repositories.

XML configuration, quite verbose.

Plugin support.

1. validate2. generate-sources3. process-sources4. generate-resources5. process-resources6. compile

mvn compile

Page 4: Modern Java Development

©2016 IKERLAN. All rights reserved 4

<project xmlns=http://maven.apache.org/POM/4.0.0 …. "> <modelVersion>4.0.0</modelVersion> <parent>

<groupId>es.ikerlan.ulma</groupId> <artifactId>ulma-supervisor</artifactId> <version>1.0</version>

</parent> <artifactId>compactor</artifactId> <packaging>jar</packaging> <properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <name>compactor</name><repositories> </repositories><dependencies> </dependencies><build>

<plugins> </plugins></build></project>

– A “pom” to rule them all

Page 5: Modern Java Development

©2016 IKERLAN. All rights reserved 5

– Dependencies

<dependencies> <dependency>

<groupId>group-a</groupId> <artifactId>artifact-a</artifactId> <version>1.0</version> <exclusions>

<exclusion> <groupId>group-c</groupId> <artifactId>excluded-artifact</artifactId>

</exclusion> </exclusions>

</dependency> <dependency>

<groupId>group-a</groupId> <artifactId>artifact-b</artifactId> <version>1.0</version> <type>bar</type> <scope>runtime</scope>

</dependency> </dependencies>

Transitive dependency support & Scope Limit.

Page 6: Modern Java Development

©2016 IKERLAN. All rights reserved 6

– Useful plugins

1. maven-shade-plugin: Uber Jar generation.

2. findbugs-maven-plugin: static code analysis.

3. maven-surefire-plugin: automates JUnit tests.

4. maven-enforcer-plugin: enforces configuration.

5. docker-maven-plugin: generates Docker images.

6. exec-maven-plugin: provides execution capabilities.

Page 7: Modern Java Development

©2016 IKERLAN. All rights reserved 7

– The Future?

Google’s Maven “successor”

Groovy-based DSL instead of XML.

DAG in order to solve tasks ordering.

Dependency solver.

Multi-language support.

Page 8: Modern Java Development

©2016 IKERLAN. All rights reserved 8

Outline

1. Maven – Solving the Dependency Hell

2. Java 8 – What's new

3. Logging – Understanding the JVM logging system

4. Useful libraries – do not reinvent the wheel

5. Testing – Mocks Everywhere

Page 9: Modern Java Development

©2016 IKERLAN. All rights reserved 9

Java 8 – Default Methods

Allows developer to add new methods to old interfaces.

Used to add Lambdas and Streams support to the JDK8.

public interface oldInterface { public void existingMethod();

default public void newDefaultMethod() { System.out.println("New default method" " is added in interface"); } }

Page 10: Modern Java Development

©2016 IKERLAN. All rights reserved 10

Java 8 – Functional Interfaces

Interfaces with only one method.

Used for providing lambda support to the JDK.

@FunctionalInterface public interface Predicate<T>{ boolean test(T t); }

public static <T> List<T> filter(List<T> list, Predicate<T> p) { List<T> results = new ArrayList<>(); for(T s: list){ if(p.test(s)){

results.add(s); }

} return results; }

Page 11: Modern Java Development

©2016 IKERLAN. All rights reserved 11

Java 8 – Method References

Class::Method meaning “use this method as a value”

File[] hiddenFiles = new File(".").listFiles(File::isHidden);

File[] hiddenFiles = new File(".").listFiles(new FileFilter() { public boolean accept(File file) {

return file.isHidden(); }

});

Vanilla Java

Java 8

Page 12: Modern Java Development

©2016 IKERLAN. All rights reserved 12

Java 8 – Anonymous Functions (Lambdas)

public static boolean isGreenApple(Apple apple) { return "green".equals(apple.getColor());}

Java 7

filterApples(inventory, (Apple a) -> a.getWeight() > 150 );

Java 8

1.(int x, int y) -> x + y2.(x, y) -> x - y 3.() -> 42 4.(String s) -> System.out.println(s) 5.x -> 2 * x

Introduce the idea of functions into the language.

Kind of anonymous method with compact syntax.

Page 13: Modern Java Development

©2016 IKERLAN. All rights reserved 13

Java 8 – Streams

Lazy Immutable evaluated collections.

Partially evaluated —elements remain to be generated.

Exhausted — when its elements are used up.

An array, a collection, a generator function, or an IO channel.

Two types of operations: intermediate and terminal.

A partially evaluated stream may have infinitely elements.

IntStream.iterate(0, i -> i + 2) .limit(100) .forEach(System.out::println);

Stream.generate(Math::random) .limit(5) .forEach(System.out::println);

Page 14: Modern Java Development

©2016 IKERLAN. All rights reserved 14

Java 8 – Streams (II)

Page 15: Modern Java Development

©2016 IKERLAN. All rights reserved 15

Java 8 – Streams (III)

List<String> title = Arrays.asList("Java8", “Rules");Stream<String> s = title.stream(); s.forEach(System.out::println); s.forEach(System.out::println);

s.stream() .map(w -> w.split("")) .flatMap(Arrays::stream) .distinct() .collect(Collectors.toList());

s.stream() .map(word -> word.split("")) .map(Arrays::stream) .distinct() .collect(toList());

List<Integer> result = numbers.stream() .peek(x -> System.out.println("from stream: " + x)) .map(x -> x + 17).collect(toList());

ERROR!! Stream already closed

ERROR!! Nested Stream….

Page 16: Modern Java Development

©2016 IKERLAN. All rights reserved 16

Java 8 – Streams (IV)

List<String> names = menu.stream() .filter(d -> d.getCalories() > 300) .map(Dish::getName) .limit(3) .collect(toList());

String traderStr = transactions.stream() .map(transaction -> transaction.getTrader().getName()) .distinct() .sorted() .reduce("", (n1, n2) -> n1 + n2);

String traderStr = transactions.stream() .map(transaction -> transaction.getTrader().getName()) .distinct() .sorted() .collect(joining());

The second is faster because it avoids String duplication with StringBuilder

Page 17: Modern Java Development

©2016 IKERLAN. All rights reserved 17

Java 8 – Streams (V)

String traderStr = transactions.stream() .map(transaction -> transaction.getTrader().getName()) .distinct() .sorted() .collect(joining());

Map<Dish.Type, List<Dish>> dishesByType = menu.stream() collect(groupingBy(Dish::getType));

The Collector Interface

Implement various useful reduction operations.

Page 18: Modern Java Development

©2016 IKERLAN. All rights reserved 18

Java 8 – Streams (VI)

Immutable parallelism: fork / join pools

Page 19: Modern Java Development

©2016 IKERLAN. All rights reserved 19

Java 8 – Streams (VII)

public static long rangedSum(long n) { return LongStream.rangeClosed(1, n) .parallel() .reduce(0L, Long::sum); }

public static long parallelSum(long n) { return Stream.iterate(1L, i -> i + 1).limit(n) .parallel() .reduce(0L, Long::sum); }

Avoid this, very slow!! (iterate is not parallel friendly)

Very fast because LongStream provide longs NOT Longs

Page 20: Modern Java Development

©2016 IKERLAN. All rights reserved 20

Java 8 – Streams (VII)

public static long sideEffectSum(long n) { Accumulator accumulator = new Accumulator(); LongStream.rangeClosed(1,n).forEach(accumulator::add); return accumulator.total; } public class Accumulator {

public long total = 0;public void add(long value) { total += value; }

}

stream.parallel() .filter(...) .sequential() .map(...) .parallel() .reduce();

Fine-Grained control?

AVOID MUTABLE STRUCTURES!!!!

Page 21: Modern Java Development

©2016 IKERLAN. All rights reserved 21

Java 8 – More Features

Data & Time API (based on Joda-Time library).

CompletableFuture, futures the functional way.

Optionals for avoiding null checking.

LocalDate today = LocalDate.now();LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);

public void renderPage(CharSequence source) {List<ImageInfo> info = scanForImageInfo(source); info.forEach(imageInfo -> CompletableFuture .supplyAsync(imageInfo::downloadImage) .thenAccept(this::renderImage)); renderText(source); }

String name = computer.flatMap(Computer::getSoundcard) .flatMap(Soundcard::getUSB) .map(USB::getVersion) .orElse("UNKNOWN");

Page 22: Modern Java Development

©2016 IKERLAN. All rights reserved 22

Outline

1. Maven – Solving the Dependency Hell

2. Java 8 – What's new

3. Logging – Understanding the JVM logging system

4. Useful libraries – do not reinvent the wheel

5. Testing – Mocks Everywhere

Page 23: Modern Java Development

©2016 IKERLAN. All rights reserved 23

Logging Systems

In Java world different implementations.

1. Interface.

2. Underlying implementation.

3. Configuration.

private final Logger log = LoggerFactory.getLogger(LogExample.class);

public static void main(String... args) { log.error("Something's wrong here");}

static

Page 24: Modern Java Development

©2016 IKERLAN. All rights reserved 24

Slf4j

Page 25: Modern Java Development

©2016 IKERLAN. All rights reserved 25

Slf4j

Page 26: Modern Java Development

©2016 IKERLAN. All rights reserved 26

Slf4j with Logback

<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT“ class="c...core.ConsoleAppender"> <encoder class="c...encoder.PatternLayoutEncoder">

<Pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} %msg%n</Pattern> </encoder>

</appender> <logger name="es.ikerlan.ulma" level="warn"/><logger name="org.apache.hadoop" level="error"/> <logger name="parquet.hadoop" level="error"/><root level="debug">

<appender-ref ref="STDOUT" /> </root> </configuration>

Logback.xml

Page 27: Modern Java Development

©2016 IKERLAN. All rights reserved 27

Outline

1. Maven – Solving the Dependency Hell

2. Java 8 – What's new

3. Logging – Understanding the JVM logging system

4. Useful libraries – do not reinvent the wheel

5. Testing – Mocks Everywhere

Page 28: Modern Java Development

©2016 IKERLAN. All rights reserved 28

Useful Libraries – lombok

https://projectlombok.org/ – useful decorators. - @Data: adds setters/getters, constructor.- @Slf4j: adds logging via SLF4J.

@Datapublic class DataExample { private final String name; private double score; }

lombok

@Datapublic class DataExample { private final String name; private double score; public String getName(){return name;}public double getScore(){return score;} ……}

vanilla Java

Page 29: Modern Java Development

©2016 IKERLAN. All rights reserved 29

Useful Libraries

http://www.jcabi.com/ – more decorators and utilities (Amazon, Json, XML….)

https://github.com/google/guava – Google Java core libraries, from caches, parsers, optionals, collections, etc.

https://commons.apache.org/ – apache hosted libraries.

Page 30: Modern Java Development

©2016 IKERLAN. All rights reserved 30

Outline

1. Maven – Solving the Dependency Hell

2. Java 8 – What's new

3. Logging – Understanding the JVM logging system

4. Useful libraries – do not reinvent the wheel

5. Testing – Mocks Everywhere

Page 31: Modern Java Development

©2016 IKERLAN. All rights reserved 31

– Testing

The facto standard unit testing library for Java.

Best tool for Test Driven development.

@Test : methods to be executed on testing

@Before: executed before each test

@After: executed before each test

@BeforeClass: runs once before the test fixture.

@AfterClass: runs once before the entire test fixture.

Page 32: Modern Java Development

©2016 IKERLAN. All rights reserved 32

– Testing

@Test public void multiplicationOfZeroIntegersShouldReturnZero() { // MyClass is tested MyClass tester = new MyClass(); // assert statements assertEquals("10 x 0 must be 0", 0, tester.multiply(10, 0)); assertEquals("0 x 10 must be 0", 0, tester.multiply(0, 10)); assertEquals("0 x 0 must be 0", 0, tester.multiply(0, 0));}

An example:

Page 33: Modern Java Development

©2016 IKERLAN. All rights reserved 33

– Mocks everywhere

mock()/@Mock: create mock from an object.

when()/given() : to specify how a mock should behave

spy()/@Spy: partial mocking, methods are invoked but still can be verified and stubbed

@InjectMocks: automatically inject mocks/spies fields annotated with @Spy or @Mock

verify(): to check methods were called with given arguments

Mock Object library for testing.

Page 34: Modern Java Development

©2016 IKERLAN. All rights reserved 34

– Mocks everywhere (II)

@Spy private LocationService locationService;

@Testpublic final void spyTest() { //mock the objectLocation loc = new Location(); //we mock the locationService.getLocation method from the real object using mockito doReturn(loc).when(locationService).getLocation("test");Location found = locationService.getLocation("test"); assertEquals(loc, found); }

An example with @Spy:

Page 35: Modern Java Development

©2016 IKERLAN. All rights reserved

IKERLAN Polo GaraiaC/ Goiru , 920500 Arrasate-Mondragón

Tel.: 943 71 02 12Fax: 943 79 69 44

IKERLAN Unidad de energíaParque Tecnológico de Álava,C/ Juan de la Cierva, 101510 Miñano

Tel.: 945 29 70 32Fax: 943 79 69 44

www.ikerlan.es

ORONA IDeO - Innovation cityPol. Industrial Galarreta, Parcela 10.5, Edificio A320120 Hernani

Tel.: 945 29 70 32Fax: 943 79 69 44

IKERLANPº. J. Mª. Arizmendiarrieta, 2

20500 Arrasate-Mondragón

Tel.: 943 71 24 00Fax: 943 79 69 44

Questions?Email: [email protected]

Thanks for your attention: