Java Course 15: Ant, Scripting, Spring, Hibernate

23
Advanced stuff: Advanced stuff: Ant, Scripting, Ant, Scripting, Spring, Hibernate Spring, Hibernate Java course - IAG0040 Java course - IAG0040 Anton Keks Anton Keks 2011 2011

description

Lecture 15 from the IAG0040 Java course in TTÜ. See the accompanying source code written during the lectures: https://github.com/angryziber/java-course Gives an overview of more advanced Java topics.

Transcript of Java Course 15: Ant, Scripting, Spring, Hibernate

Page 1: Java Course 15: Ant, Scripting, Spring, Hibernate

Advanced stuff:Advanced stuff:Ant, Scripting,Ant, Scripting,

Spring, HibernateSpring, Hibernate

Java course - IAG0040Java course - IAG0040

Anton KeksAnton Keks 20112011

Page 2: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 22

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

AntAnt

● Ant == Another Neat Tool, http://ant.apache.org/http://ant.apache.org/● In short, it is a cross-platform make for Java● Is the de-facto standard build tool for Java projects● You just have to write an XML file, describing the

build process

– usually named build.xml– Java IDEs provides auto-completion, running, and

sometimes debugging of Ant build files● It is also very good for automating of complex tasks

Page 3: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 33

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Hello, Ant!Hello, Ant!

● <?xml version="1.0"?><project name="HelloAnt" default="sayHello"

basedir="."><property name="text.hello"

value="Hello, Ant!"/><target name="sayHello">

<echo>${text.hello}</echo></target><target name=”compile” depends=”sayHello”>

<javac srcdir=”src” destdir=”bin”/></target>

</project>

Page 4: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 44

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Ant essentialsAnt essentials

● The root tag is <project> that defines the name of the project

● <property> defines global properties for usage within the file

– name and value are mandatory attributes

– properties are further referenced as ${name}

● <target> specifies runnable build targets (sequences of actions) that can depend on each other

– name specifies target's name

– if and unless can check whether certain property is set

– depends – comma-separated list of other targets

– description can be used for documenting

Page 5: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 55

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Ant essentials (cont)Ant essentials (cont)

● Within targets, Ant tasks can be used

– There are many predefined tasks, e.g. echo

– You can define tasks yourself or run other targets with <antcall>

– You can use 3rd-party tasks from jar files

● Many tasks use FileSets

– they are filters using patterns to select specific files

– ? matches a character, * matches zero or more characters, ** matches zero or more directories (processed recursively)

– <fileset dir=”${basedir}” includes=”**/*.java”/>

● <include> and <exclude> can be specified within

Page 6: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 66

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Most common Ant tasksMost common Ant tasks● Filesystem tasks:

– copy, delete, get, mkdir, move, rename, touch, chmod

● Remote tasks:

– ftp, scp, sshexec, telnet, setproxy, mail, cvs, cvschangelog

● Compilation and Deployment:

– javac, javadoc, rmic, depend, jar, tar, zip, war, gzip

● Testing

– junit, junitreport

● Miscellaneous

– echo, exec, fail, sleep, buildnumber, condition

● More info at http://ant.apache.org/manual/tasksoverview.htmlhttp://ant.apache.org/manual/tasksoverview.html

● Tons of 3rd party tasks available

Page 7: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 77

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Java ScriptingJava Scripting

● Java 1.6 introduced embedded scripting– allows running of scripts inside of the JVM

● scripts can be written in many languages, e.g. JavaScript, Ruby, Groovy, Python, etc

● each language needs its engine to be available● JavaScript is available by default (Mozilla Rhino)

– Scripts and Java classes can interoperate● Reasons

– Java is a platform, not only a language

– interoperability, faster development of non-critical code, specific domain usage, etc

Page 8: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 88

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Java Scripting APIJava Scripting API

● Java Scripting API is in javax.script package

● ScriptEngine – interface for implementing of different scripting languages

● ScriptEngineFactory – interface for implementing ScriptEngine factories, provides detailed information about the language

● ScriptEngineManager – class for registering and obtaining of ScriptEngines

● ScriptEngineManager mgr = new ScriptEngineManager();ScriptEngine jsEngine =

mgr.getEngineByName("JavaScript");jsEngine.eval("print('Hello, world!')");

Page 9: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 99

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Evaluation / InvocationEvaluation / Invocation

● ScriptEngine's eval() method accepts both String and Reader

– so the script can come from virtually any source– ScriptEngine engine = mgr.getEngineByExtension("js");engine.eval(new InputStreamReader(

this.getClass().getResourceAsStream(“runme.js”)));

● Engines implementing Invocable can invoke individual functions or methods

– engine.eval( "function sayHello() {" + " println('Hello, world!');" + "}");

((Invocable)engine).invokeFunction("sayHello");

● Engines implementing Compilable can precompile scripts– ((Compilable)engine).compile("print('Hello')").eval();

Page 10: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1010

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Java BindingJava Binding● Java classes are available to scripts and can be used

using the language's syntax, e.g. JavaScript:– importPackage(java.util)var javaDate = new Date()var dateString = javaDate.toString()

● ScriptEngine provides put() and get() methods for storing/retrieving bound variables

– engine.put(“javaDate”, new Date());engine.eval(“print(javaDate.toString())”);

● Objects can be returned from scripts to Java using the return from eval() or invokeXXX() methods as Objects

– Rhino maps numbers to Double, strings to String

Page 11: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1111

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Spring FrameworkSpring Framework● http://www.springframework.org/http://www.springframework.org/

● The leading full-stack Java/J2EE application framework

● Spring delivers significant benefits for many projects, reducing development effort and costs while improving test coverage and quality

● Was created as an alternative/companion to J2EE

– J2EE should be easier to use

– Reduces the complexity cost of using interfaces to zero

– JavaBeans offer a great way of configuring applications

– OO design is more important than any implementation technology

– Checked exceptions are overused in Java

– Testability is essential

Page 12: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1212

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Spring FeaturesSpring Features

● Advertised features:

– The most complete lightweight container

– A common abstraction layer for transaction management

– A JDBC abstraction layer

– Integration with Hibernate, Toplink, JDO, and iBATIS

– AOP functionality

– A flexible MVC web application framework● Most of these can be used in both Java SE and Java EE

● Spring allows for reusable business and data access objects that are not tied to specific services (POJO-based approach)

Page 13: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1313

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Spring OverviewSpring Overview

Page 14: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1414

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

AOPAOP● Aspect-Oriented Programming

– a new approach to programming since OOP

● Solves the problem of cross-cutting concerns in the code, e.g. logging or database transactions spread in different places– Usually there is functionality that is spread in many places

– AOP allows to write this code as an aspect

– Aspects alter the behavior of base-code by applying advice (additional behavior) over a quantification of join points

– Join points are points in the structure or execution of a program; they are specified using pointcuts (descriptions of sets of join points)

Page 15: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1515

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Dependency Injection / IoCDependency Injection / IoC● Dependency Injection == Inversion of Control (IoC)

– is a design pattern upon which Spring's core is based

● Is a way to achieve loose coupling– it allows for complete separation of interfaces and

implementations

– concrete implementations of classes are injected on demand as configured

– responsibility of object creation is removed from objects

● Spring defines BeanFactory for that purpose● The container (BeanFactory) injects dependencies

into beans hence the term IoC

Page 16: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1616

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

BeanFactoriesBeanFactories● BeanFactory actually instantiates, configures, and manages state of

beans

● There are several default implementations

– XmlBeanFactory – bean definitions are in XML files

– DefaultListableBeanFactory – bean definitions specified programmatically

● XmlBeanFactory loads XML bean definition file from a specified Resource, i.e. FileSystemResource, ClassPathResource, UrlResource, etc

● ApplicationContext is an extension to BeanFactory, providing additional more complex features

● The following basic methods are provided: getBean, getType, isSingleton, containsBean

Page 17: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1717

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Bean definition XMLBean definition XML● Bean definition file:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans">

<bean id="..." class="...">...</bean><bean id="..." class="...">...</bean>...

</beans>

● Many beans can be defined and configured this way

● Beans define class names, properties, constructor arguments, collaborator beans (dependencies), etc

● Beans can be singletons (scope=”singleton”, default) or prototypes

● Autowiring means injection of dependencies automatically either byName or byType (autowire attribute, default is none)

● A bean can have FactoryBean specified that creates bean instances

Page 18: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1818

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

ORMORM● Object-Relational Mapping

– links relational databases to object-oriented language concepts, creating a “virtual object database”

● The goal is to be able to store and retrieve Java objects or their hierarchies using the database

● The most basic scenario:

– Java class corresponds to a DB table

– Class fields correspond to columns in the table

– Java object (instance) corresponds to a row in the table

● Basic usage (storing and retrieving):

– orm.save(myObject);

– myObject = orm.load(MyObject.class, objectId);

Page 19: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 1919

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

HibernateHibernate● http://www.hibernate.org/http://www.hibernate.org/● Is the de-facto standard open-source ORM

(Object-Relational Mapping) tool– Lets you develop persistent classes following OO

idiom, including association, inheritance, polymorphism, composition, and collections

– Provides its own portable object-oriented HQL language in addition to native SQL as well as Criteria and Example APIs

● Can be used for persisting of POJOs to database

Page 20: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 2020

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Hibernate MappingHibernate Mapping

● Mappings are usually expressed as XML files● Mapping of class Dog to table DOGS using mapping file Dog.hbm.xml:

● <?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>

<class name="net.azib.Dog" table="DOGS"><id name="id" column="uid" type="long">

<generator class="increment"/></id><property name="name"/><property name="dateOfBirth" type="date"/><property name="weight" column="mass"/>

</class></hibernate-mapping>

Page 21: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 2121

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Hibernate SessionsHibernate Sessions● Session is a conversation between the application and the

persistent store (short-lived, single-threaded)

– wraps and hides the real JDBC connection

– is used for storing/retrieving of persistent objects● SessionFactory is used for creation of Sessions. It caches

compiled mappings (long-lived, thread-safe)

● Persistent objects are POJOs, they can be attached to a Session

– Upon retrieval, objects are automatically attached to the session

– Attached objects are automatically checked for changes and stored if needed

● Session provides methods like: get, load, save, update, find, etc

Page 22: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 2222

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Hibernate basic overviewHibernate basic overview

Page 23: Java Course 15: Ant, Scripting, Spring, Hibernate

Lecture 15Lecture 15Slide Slide 2323

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Hibernate complex exampleHibernate complex example