Java Course 15: Ant, Scripting, Spring, Hibernate


Published on

Lecture 15 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures:

Gives an overview of more advanced Java topics.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java Course 15: Ant, Scripting, Spring, Hibernate

  1. 1. Java course - IAG0040 Advanced stuff: Ant, Scripting, Spring, HibernateAnton Keks 2011
  2. 2. Ant ● Ant == Another Neat Tool, ● 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 tasksJava course – IAG0040 Lecture 15Anton Keks Slide 2
  3. 3. 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>Java course – IAG0040 Lecture 15Anton Keks Slide 3
  4. 4. Ant 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 targets name – if and unless can check whether certain property is set – depends – comma-separated list of other targets – description can be used for documentingJava course – IAG0040 Lecture 15Anton Keks Slide 4
  5. 5. 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 withinJava course – IAG0040 Lecture 15Anton Keks Slide 5
  6. 6. Most 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● Tons of 3rd party tasks availableJava course – IAG0040 Lecture 15Anton Keks Slide 6
  7. 7. Java 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, etcJava course – IAG0040 Lecture 15Anton Keks Slide 7
  8. 8. Java 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!)");Java course – IAG0040 Lecture 15Anton Keks Slide 8
  9. 9. Evaluation / Invocation● ScriptEngines 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();Java course – IAG0040 Lecture 15Anton Keks Slide 9
  10. 10. Java Binding ● Java classes are available to scripts and can be used using the languages 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 StringJava course – IAG0040 Lecture 15Anton Keks Slide 10
  11. 11. Spring Framework ● ● 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 essentialJava course – IAG0040 Lecture 15Anton Keks Slide 11
  12. 12. Spring 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)Java course – IAG0040 Lecture 15Anton Keks Slide 12
  13. 13. Spring OverviewJava course – IAG0040 Lecture 15Anton Keks Slide 13
  14. 14. AOP ● 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)Java course – IAG0040 Lecture 15Anton Keks Slide 14
  15. 15. Dependency Injection / IoC ● Dependency Injection == Inversion of Control (IoC) – is a design pattern upon which Springs 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 IoCJava course – IAG0040 Lecture 15Anton Keks Slide 15
  16. 16. BeanFactories ● 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, containsBeanJava course – IAG0040 Lecture 15Anton Keks Slide 16
  17. 17. Bean definition XML ● Bean definition file: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=""> <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 instancesJava course – IAG0040 Lecture 15Anton Keks Slide 17
  18. 18. ORM ● 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): –; – myObject = orm.load(MyObject.class, objectId);Java course – IAG0040 Lecture 15Anton Keks Slide 18
  19. 19. Hibernate ● ● 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 databaseJava course – IAG0040 Lecture 15Anton Keks Slide 19
  20. 20. Hibernate 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" ""> <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>Java course – IAG0040 Lecture 15Anton Keks Slide 20
  21. 21. Hibernate 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, etcJava course – IAG0040 Lecture 15Anton Keks Slide 21
  22. 22. Hibernate basic overviewJava course – IAG0040 Lecture 15Anton Keks Slide 22
  23. 23. Hibernate complex exampleJava course – IAG0040 Lecture 15Anton Keks Slide 23