+ All Categories
Home > Documents > Java 7 featurs

Java 7 featurs

Date post: 06-Aug-2015
Category:
Upload: brinal
View: 16 times
Download: 0 times
Share this document with a friend
Description:
Java 7 featurs byRony KerenInternet TeamJohnbryce Training Center
Popular Tags:
37
Java 7 New Features Rony Keren Internet Team Johnbryce Training Center Topics Open JDK Java 7 Features: Invoke Dynamic Class Loading JVM & GC Syntax enhancements Concurrency Collection API I18N I/O & Networking XML and Web-Services JDBC Objects utility class Known issues
Transcript
Page 1: Java 7 featurs

Java 7 New Features

Rony Keren

Internet Team

Johnbryce Training Center

Topics

• Open JDK

• Java 7 Features:• Invoke Dynamic

• Class Loading

• JVM & GC

• Syntax enhancements

• Concurrency

• Collection API

• I18N

• I/O & Networking

• XML and Web-Services

• JDBC

• Objects utility class

• Known issues

Page 2: Java 7 featurs

Open JDK Project

• Collaborate on Java standard edition

• Members – individuals that want to contribute

• Groups – people who gather to discuss issues

• Creation of new code, enhancing & maintaining code

• Members are old-timer contributors

Open JDK Project

• Projects - collaborative effort to produce a specific artifact• Member or group can propose a project to the

announcement list [[email protected]]

• With replies directed to the general discussion [[email protected]]

• Groups may decide to sponsor projects (members vote) within 2 weeks

• Unsponsored projects sent back to the sender group and removed from list

Page 3: Java 7 featurs

Invoke Dynamic

• JSR 292: Supporting Dynamically Typed Languages on the

Java Platform

• Goal: dynamically typed languages will run as fast as Java

• Follows JSR 223 (Scripting for Java platform)

• Rhino Scripting Engine – support for Jscript

• Scripting project has more than 20 additional engines

• Designed for statically typed languages / coding

Invoke Dynamic

• What is dynamic invocation ?• Fields and methods can be defined with no binding to a class

• Then they can be assigned to any appropriate object

• Is it also available in Java code ?• No. Java allows methods and fields to be created in a class context

• Reflection mechanism is also class driven (Method/Field derived from

Class)

• Most dynamic is to manipulate class byte via instrumentation API

• it’s more dynamic but not dynamically invoked

• it is also done in a class context

Page 4: Java 7 featurs

Invoke Dynamic

• Jscript dynamic invocation examples

Methods can be passed as arguments

and assigned to different types of objects

function main (function, arg1, arg2){

window[function](arg1,arg2);

}

function dynamicFunc(x, y){

alert(x+y);

}

//invoking:

main('dynamicFunc','hello‘,'world');

function getDynamic(x){

var f = doSomething(x){

if(x>y) return true;

else return false;

}

return f;

}

Invoke Dynamic

• JSR 292: Supporting Dynamically Typed Languages on the

Java Platform

• Provides support for dynamically typed languages

• Enhanced compilers

• Engines can use additional instructions in order to compile code• Invokedynamic – new bytecode instruction that allows to translate method invocation

without relating to the object holds it

• Java.dyn.MethodHandler – bounded to each Invokedynamic instruction

- holds reference to a JVM method

- cached

• Both invokedynamic and MethodHandlers are updated during runtime

Page 5: Java 7 featurs

Class Loading

• Major changes made in Java 6

• Endorsed directory

• Escape analysis – experimental

• General continues improvements

• Performance

• Avoiding dead-locks in non-hierarchical structures

• URLClassLoader close() method

• New classes cannot be loaded

• Irreversible

Class Loading

• Multithreaded class loading CL

• How CL usually works?

• Each CL has a parent (except Bootstrap CL)

• When a class is required, the CL first check on its parent

• If not loaded yet, CL asks its parent to load it

• If cant be loaded from parent – loaded by CL

• Note ! Loading classes operation is synchronized

Page 6: Java 7 featurs

Class Loading

• Multithreaded class loading CL

• The problem:

• In this scenario

• D extends C and B extends A

• Thread1 wants to create a B instance

• Uses CL1 as parent and CL2 as child (locks CL1 and then CL2)

• Thread2 wants to create a D instance via CL2

• Uses CL2 as parent and CL1 as child (locks CL2 and then CL1)

• A deadlock situation:

• Thread1 – CL1(parent) doesn’t have B – so CL2 loads it and gets locked

• Thread2 – CL2(parent) doesn’t have D – so CL1 loads it and gets locked

• Since both A & C are loaded from parents, threads must call them – but they are locked

CL1

CL2

Client 1

Client 2

Class Loading

• Multithreaded class loading CL• Synchronization is no longer done according to CL

• It is applied to the combination of CL + class name

• Back to our scenario:

• Thread1 will lock CL1 to load parent class A (lock CL1+”A”)

• Then will lock CL2 to load B (lock CL2+”B”)

• Thread2 will lock CL2 to load parent class C (lock CL2+”C”)

• Then will lock CL1 to load D (lock CL1+”D”)

• Problem solved – we have 4 different locks instead of 2…

Page 7: Java 7 featurs

Class Loading

• Multithreaded class loading CL

• How to use it ?

• Basically this feature is turned off for backward compatibility

• To turn on – call this method on your custom CL:

• registerAsParallelCapable()

• If the custom CL overrides findClass(…), then no further changes are needed

• If the custom CL overrides loadClass(…)

• Method defineClass() must be invoked ONCE for any CL & class name pairs

• Define class obtains a lock on the parent CL to fully load class structure

JVM & GC

• Compressed 64-bit ordinary object pointers (oops)

• Java uses 32 bit offsets + 32 bit for a specific address

• Offsets are the prefixes of the whole virtual address

• Instead of : we get:

• G1 (Garbage First)

• A long run replacement for CMS (Concurrent Mark Sweep GC)

• Available in Java 6 update 14

AB27D 147C3

AB27D 26AB2

AB27D D62A1

AB27D A432B

AB27D

147C3

26AB2

D62A1

A432B

Page 8: Java 7 featurs

JVM & GC

• More on G1

• Instead of sweeping – compacts and defragments

• Also generational (acts on OLD region)

• Based on concurrent / parallel behavior

• Like CMS, a low-pause GC

• Usage: --XX: +UseG1GC

• In Java 6 activate feature first with: -XX:+UnlockExperimentalVMOptions

JVM & GC

• G1 – How does it work ?

• Compaction occurs first on regions where most reclaimable

objects exist

• Compaction means:

• remove all phantom objects from memory

• Merge referenced objects locations with others to create large ‘clean area’ in the heap

• When JVM needs new space for a new object – is seeks the largest clear

area

• More efficient footprint management, more efficient allocations

• Good only for OLD region

• G1 seeks for areas where most phantom object exists

• Therefore, compaction will be highly effective (not much left…)

Page 9: Java 7 featurs

JVM & GC• Tiered Compilation

• Client VM – faster launching

• Startup: Less profiling, more interpreting

• Runtime: most classes are loaded during execution

• Server VM - slow launching

• Startup & peeks: More profiling

• Runtime: most classes are loaded and ready to serve

• Tiered Compilation

• Server VM also uses the client compiler

• Server VM does most of profiling and meanwhile client VM

interpret profiling results

JVM & GCEscape Analysis

• When a stack creates an object and hands it to

an outside caller

• Non-escaped references

• When a stack is the only one uses an object

• When a caller assigns an object to a stack and get rid of his

reference

public Object method (){

Object o = new Object();

otherMethod(o) // Object escaped…

}

public Object method (){

Object o = new Object();

}

Page 10: Java 7 featurs

JVM & GC

• What is ‘escape analysis’ ?

• Tracking non-escape references

• Turning the non-escape object state to be part of

the stack that uses it instead of being allocated on

the heap

public Object method (){

Pixel p = new Pixel(100,30);

}

public Object method (){

int x=100;

int y=30;

}

JVM tracks non-escape references

And turns the object state to be

part of the stack that uses it

JVM & GC

• Done during interpretation phase

• Supported in Java SE 6 update 23

• To activate use:

• XX: +DoEscapeAnalysis

Page 11: Java 7 featurs

Syntax Enhancements

• Strings in switch

• Language support for Collections

String value=“one”;

….

switch(value){

case “one”: ………

case “two”: ………

default: …….

}

List<String> nums = [“one”,”two”];

String num = nums[0];

Set<String> nums = {“one”,”two”};

Map<String, Integer> nums = {“one" : 1,”two” : 2};

int num = nums[“one"];

Syntax Enhancements

• ARM – Automatic Resource Management

• Opening / closing resource connection is not part of the

try-catch block

• Instead of:

• We use:

public void doIO() throws IOException{

FileInputStream in=null;

try{

in=new FileInputStream (“file”);

int data = in.read();

}catch(FileNotFoundException e){

in.close();

}

}

public void doIO() throws IOException{

try(FileInputStream in= new FileInputStream (“file”)){

int data = in.read();

}

}

Page 12: Java 7 featurs

Syntax Enhancements

• More on ARM

• Manages “AutoCloseable” implementations only(!)

• Whether try block pass or fails – close() will be invoked

• Can declare and use more than one resource:

• Close() method is called according to resource declaration

order in the try clause

try(FileInputStream in= new FileInputStream (“file1”);

FileOutputStream out= new FileOutputStream(“file2”) ){

int data = in.read();

out.write(data);

}

Syntax Enhancements• Improved generic type creation

• Instead of:

• We use:

• Binary literals

• We already have 0 (octal) & 0x (hexadecimal)

• Now we have 0b (binary) as well:

• Underscores for numeric literals

Map<String,List<Integer>> map=new Map<String,List<Integer>>();

Map<String, List<Integer>> map=new Map<>();

int binary = 0b11011101;

int million =1_000_000;

Page 13: Java 7 featurs

Syntax Enhancements

• Multi-catch

• Relating to different exceptions in a single catch block

• Instead of:

• We use:

try{

FileInputStream in=new FileInputStream (“file”);

Connection con = DriverManager.getConnection(….);

….in.read();

….con.createStatement();

}catch(IOException e){

….

}catch(SQLException e){

….

}

try{

…..

}catch(IOException | SQLException e){ …. }

Concurrency

• Lightweight processing with ForkJoinTask<V> & Pool

• Some terms:

• Heavyweight processing = processing in separate stack

• Threads helps in that

• Stack values has to be re-assigned every time thread uses CPU time

• Synchronization might be needed

• Known as ‘fork’

• Lightweight processing = processing in the same stack

• Linear processing

• Processing time might be short, long or very long..

• For short time – we can use the same thread or new thread

• For long time – we can use new thread

Page 14: Java 7 featurs

Concurrency• For very long tasks we might want to:

• Split task into small independent parts

• Fork each part to solve it separately

• In the same thread pool dedicated to that long task

• Join all parts

• Compose the result out of them

Concurrency• Java 7 offers:

• ForkJoinTask – lightweight task (like Callable-Future)

• RecursiveAction – a task that doesn’t return a result

• RecursiveTask<E> - a task that results in E type

• Both has invokeAll(..) method to fork other subtasks

• ForkJoinPool – An ExecutorService implementation

• Designed for forking tasks and its subtasks

• Takes number of processors to its constructor

• Default constructor is set according to the Runtime.availableProcessors()

Page 15: Java 7 featurs

Concurrency• Example:

public class ElementTask extends RecursiveAction{

private Node n;

public ElementTask(Node n) {this.n=n;}

@Override

public void compute(){

if(node.getNodeValue().equals(“leaf”)){

….. Process node data

}else { // node is composite of sub-leafs…..

NodeList subs=n.getChildNodes();

Collection<ElementTask> subTasks=new HashSet<>()

for(int i=0;i<subs.getLength();i++){

subTasks.add(new ElementTask(subs.item(i)));

}

invokeAll(subTasks ); //registers more tasks to the pool..

}

}

}

ElementTask t=new ElementTask(xmlDocumentNode);

ForkJoinPool pool=new ForkJoinPool ();

pool.invoke(t);

Concurrency• Threads sharing Random

• Random allows to obtain random numeric values in a thread-safe way

• Means – poor performance

• Java 7 offers a subclass named: ThreadLocalRandom

• Acts like Random but holds a random generation context for each thread

• Use current() method to load the relevant ThreadLocalRandom for the caller thread

ThreadLocalRandom tlr = ThreadLocalRandom.current();

tlr.setSeed(1234);

..

int x = ThreadLocalRandom.current().nextInt();

Long y = ThreadLocalRandom.current().nextLong();

Page 16: Java 7 featurs

Collection API

• Java 5 – Queue & BlockingQueue

• Java 6 – Dequeue & BlockingDequeue• Double ended queue

• BlockingQueue• blocks producers when queue is full

• Blocks consumers when queue is empty

• Java 7 – TransferQueue• Is a BlockingQueue extension

• Provides transfer(Object) method• Blocks until an object is handed from a producer to a consumer

• Like the Java 6 SynchronousQueue implementation class

I18N

• Updating from UNICODE 5.1 to UNICODE 6.0

• More signs… more values…

• Locale support for BCP47

• BCP47 – extended tags for identifying languages

• Uses ‘u’ for extra data (key-value): en-GB-u-kn-true

• Java 7 provides Locale.Builder

• Locale inner class

• Helps in constructing extended locales

• After created and set – call ‘build()’ method to construct a Locale

Page 17: Java 7 featurs

I18N

• Locale support for UTR35

• UTR 35 – XML based Locale Data Markup Language (LDML)

• Supports basic locale data with currencies and formatting settings

• Supports BCP47 extensions

• Supported by Locale.Builder

• Locale.Category inner class

• Allows to fetch Locale data in two modes:

• FORMAT – full programmatic locale data

• DISPLAY – a version of locale data for UI

I/O & Networking

• NIO Enhancements for File System API – NIO.2• java.nio.file (& sub-packages: attribute & spi)

• Provides an extensible file system implementations

• SystemProvider extensions can focus on JAR/ZIP and others

• What is wrong with existing Java FS solution ?

• All in one class – java.io.File

• Usage is not clear

• is it abstract ? real ? both ?

• Is it a file ? directory ? absolute directory ? partition ?

• Many modern FS features are missing

Page 18: Java 7 featurs

I/O & Networking

• Main services:

• FileSystem – FS interface. Manages access to files on the

local file system

• delete(path), copyFile(..),moveFile(..), getFileStores()…

• isOpen(),isReadOnly(), isSameFile(path1, path2)…

• FileRef – provides methods to read/write to a file. Can also

change file attributes

• Obtaining: File.toPath(), URL.toFileRef()

• get/setAttribute(), newInputStream(), newOutputStream()…

• Using:

file.setAttribute(“dos:hidden”, true);

I/O & Networking

• Main Services cont. – NIO.2

• Path –points to a file/directory with system dependant path• compareTo(path), equals(path)

• getNameCount(), iterator(), normalize() (get rid of ‘.’ & ‘..’)

• toFile(), toAbsolutePath(), relativize() (creates relative path between this & the given)

• FileStore – reflects file storage area (like pool, device, partition, volume, OS file system)

• getTotalSpace(), getUnallocatedSpace(), getUnusableSpace()

• Files - utility class • create(), copy(), delete()

• exists(), getLastModified(), getAttribute(), isHidden(), isExecutable(), isDir()

• getFileStore() , getOwner () (returns UserPrincipal)

Page 19: Java 7 featurs

I/O & Networking

• NIO Enhancements for File System API – NIO.2

• Simple example:

Path src=Path.get(“C:/temp/data.bkp”);

Path target=Path.get(“E:/info/data.bkp”);

Files.copyTo(src,target, StandardCopyOption.REPLACE_EXISTING);

I/O & Networking

• File change automation

• Allows listening to events on directories

• Events are detailed in StandardWatchEventType ENUM

• ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY

• Use WatchService to obtain service

• Use WatchKey to register service to a path (directory)

• Use WatchEvent to obtain event count, type and context

• Flow:

• When event is detected the key is signaled

• Signaled key enters to a watch service queue

• Until consumed, the key might experience more events

• All key events get handled when key is consumed from the queue

Page 20: Java 7 featurs

I/O & Networking

• File change automation – NIO.2

• Example:

WatchService ws = FileSystem.getDefault().newWatchService();

Set<StandardWatchEventType> events = EnumSet.of(ENTRY_DELETE);

WatchKey key = someDirPath.register(ws, events);

while(true){

key=ws.take(); //blocks until key is signalled

List<WatchEvent<?>> le=key.pollEvents();

// process all deletion events

key.reset(); //out of the queue, back to initial state

}

I/O & Networking

• Asynchronous I/O

• Goal: connect, read and write will be forked transparently

• Supported for files and sockets

• AsynchronousFileChannel

• AsynchronousSocketChannel, AsynchronousServerSocketChannel

• Can be implemented in 2 ways:

• Initiate I/O operation that results with Future [use Executor-Callable]

• Register CompletionHandler when invoking I/O operation [use Observer]

Page 21: Java 7 featurs

I/O & Networking

• Asynchronous I/O

• Example using Future:

• Results in Future for connect, read & write operations

AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();

Future<Void> result = ch.connect(new InetSocketAddress(ip,port));

….

// Future.get() return null on success

if(result.get()==null){

ByteBuffer b = …..

// wait read operation to complete

Future<Integer> data = ch.read(b);

}

I/O & Networking

• Asynchronous I/O

• Example using CompletionHandler:

• Handles connect, read & write operations

ByteBuffer b = …..

// read using the buffer.

// we may assign an attachment - attachments are returned on

// completion. We don’t need one here so we assign null

ch.read(b,null,new CompletionHandler<Integer,Void> (){

public void completed(Integer result, Void attachment ){

//process result data

}

public void failed(Throwable ex, Void attachment){

//process failure

}

});

Page 22: Java 7 featurs

XML, Web Services

• XML - JAXP enhancements

• DOM, SAX bug fixes

• StAX upgrade to 1.2

• Allows to get XML events like SAX as a stream

• Unlike DOM/SAX – allows to control the parsing process:

• Pause

• Get next event

• Get next tag

XML, Web Services

Web Services - intro

• XML based RPC mechanism

• WS Standards

• WSDL – Web service description language

• SOAP – Simple Object Access Protocol

Page 23: Java 7 featurs

XML, Web Services

• Web Services Architecture

Search / Browse

WSDL Link

Application

S

O

A

P

G

A

T

E

W

A

YSOAP Messaging

Application

UDDI Portal

Business

W

S

D

L

SOAP Stub

XML, Web Services

WSDL

• Describes

• data structures

• functions (operations)

• Unidirectional & bidirectional

• endpoints

• Functions are invoked according to specific URLs

Page 24: Java 7 featurs

XML, Web Services

SOAP

• Method invocation protocol

• Bidirectional – means there are SOAP request followed by SOAP response

• Unidirectional – means there is SOAP request only

• Can be used in JMS

• In HTTP – results with an empty HTTP response

• Uses XSD types to describe primitives and objects

• SOAP Actions

• HTTP header that carries the endpoint data

• Helps in mapping request to objects during HTTP processing phase

XML, Web Services

• What WS tools should provide ?

• For server side:

• Ability to map class methods to be available as WS

• WSDL generator

• SOAP skeleton generator

• Server / container to deploy WS and listen to clients

• For client side

• A tool that downloads WSDL from a given URL and

generates stub and classes

Page 25: Java 7 featurs

XML, Web Services

• JAX-WS – Java API for XML – Web Services

• Provides • Annotations for WS mapping

• Tool for client code generation

• Embedded HTTP server• light-weight

• Implemented as a java object

• Can be started programmatically

• Endpoint.publish(“……..”)

• Listens to port 8080 by default

XML, Web Services

• Mapping class methods via JAX-WS annotations

import javax.jws.WebService;

import javax.jws.soap.SOAPBinding;

@WebService

@SOAPBinding(style=SOAPBinding.Style.RPC)

public class Business {

@WebMethod

public int sum(int x,int y){

return x+y;

}

}

Page 26: Java 7 featurs

XML, Web Services

• Publishing as WS with a given endpoint

import javax.xml.ws.Endpoint;

public class Publisher {

public static void main(String[] args) {

Endpoint.publish("http://localhost:8080/calc",new Business());

}

}

XML, Web Services• WSDL View

Page 27: Java 7 featurs

XML, Web Services

• Generating clients

• P – package

• S – source location

• D – output location

Regarding generated output:• a ‘service’ factory is generated

• the factory creates all types for WS functions invocation

• In our example we expect to have:

wsimport –s c:\src –p core.people http://localhost:8080/calc?wsdl

core.people.BusinessService core.people.Businesscreates

XML, Web Services

• Client code example:

public class Client {

public static void main(String[] args){

BusinessService service = new BusinessService();

Business calc = service.getBusinessPort();

System.out.println(“Call Started…");

System.out.println(calc.sum(100,200));

System.out.println(“Call Ended…");

}

}

Page 28: Java 7 featurs

JAXB

• What’s Wrong With DOM:

– DOM API ignores schema any information

– Therefore DOM objects are forced to hold both structural information and data loaded from XML

– DOM objects are heavy and inefficient

– Plain API causes low quality and unreadable code especially when dealing with complex XML structures

JAXB

• Java API for XML Binding

• Binding means:

• Turning XML elements into Java lightweight objects

• Un-marshal

• Turning Java lightweight objects into XML stream

• marshal

Page 29: Java 7 featurs

JAXB

• JAXB Architecture

Schema

Document

XSDJAXB

Compiler Interface

Application

XML

Document JAXB API

Object

Object

Object

Object

Class

InterfaceClass

Class

JAXB

• Back to the simple structure:

• Assume we have a schema (XSD) for it

• JAXB generated classes will be more like:

AgeAgeAge NameName Name

PersonPersonPerson

People

-Collection persons

+getPersons()

People-String name

-int age

-GenderType

+getName()

+setName(String)

+setAge()

+setAge(int)

+getGenderType()

+setGenderType(type)

PersonType

1

8

Gender (M/F)

+M

+F

GenderType<enum>

1 1

Page 30: Java 7 featurs

JAXB

• With JAXB we get:

• Classes that relates to a schema

• Lightweight Java objects

• JAXB provides:

• Efficient way to deal with XML based data in memory

• Simpler, more clear code even when dealing with

complex structures

JAXB

• Un-marshal

• Convert from XML to objects

• Classes are generated by Binding Compiler

• Each complex type is turned into

• Interface (or inner interface)

• Class Implementation (or inner class)

Page 31: Java 7 featurs

JAXB• Un-marshal

• Standalone classes are determined according to

the declaration in the schema

• If an element is declared in a separate <complexType>

tag, it will have a separate stand alone class<xsd:element name=“people”>

<xsd:complexType>

<xsd:sequence>

<xsd:element name=“person” type=“personType” maxOccurs=“unbounded”/>

</xsd:sequence>

</xsd:complexType>

</xsd:element>

<xsd:complexType name=“personType”>

<xsd:sequence>

<xsd:simpleType name=“name” type=“xsd:string”/>

<xsd:simpleType name=“age” type=“xsd:integer”/>

</xsd:sequence>

<xsd:attribute> <xsd:simpleType name=“gender” type=“genderType”/> </xsd:attribute>

</xsd:complexType>

personType has its own

separate declaration

JAXB• Un-marshal

• If the <complexType> definitions are inside other

element <sequence>, then an inner class will be

generated

<xsd:element name=“people”>

<xsd:complexType>

<xsd:sequence>

<xsd:element name=“person” maxOccurs=“unbounded”>

<xsd:complexType>

<xsd:sequence>

<xsd:simpleType name=“name” type=“xsd:string”/>

<xsd:simpleType name=“age” type=“xsd:integer”/>

</xsd:sequence>

<xsd:attribute> <xsd:simpleType name=“gender” type=“genderType”/> </xsd:attribute>

</xsd:complexType>

</xsd:element>

</xsd:sequence>

</xsd:complexType>

</xsd:element>

personType is

declared as an

inner type

Page 32: Java 7 featurs

JAXB

• Marshal

• Export objects from memory into XML stream

• Marshal operation takes:

• The root element of the content tree (objects)

• Output stream for writing XML

JAXB

• JAXB Flow options:

• Un-marshal � Use XML origin data as objects

• Build objects with data � Marshal to XML stream

• Un-marshal � Manipulate data in memory � marshal

Page 33: Java 7 featurs

JAXB

• Example:• Generating classes from a given Schema / DTD

• Done via “Binding Compiler” tool [xjc]

• Supports both DTD and Schema(XSD)

• P – package

• D – source location

• NV – no validation (default is to validate)

• JAXB annotations also allows to denote java classes in order to generate an XSD

xjc -p core.data -d src people.xsd

JAXB• Example:

• Generated classes view@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(name = "", propOrder = {"person“})

@XmlRootElement(name = "People")

public class People {

@XmlElement(name = "Person", required = true)

protected List<PersonType> person;

public List<PersonType> getPerson() {

if (person == null) {

person = new ArrayList<PersonType>();

}

return this.person;

}

}

@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(name = "PersonType", propOrder = {

"name",

"age",

"birthDate"

{(public class PersonType {

@XmlElement(name = "Name", required = true)

protected String name;

@XmlElement(name = "Age")

protected int age;

@XmlElement(name = "BirthDate")

@XmlSchemaType(name = "date")

protected XMLGregorianCalendar birthDate;

@XmlAttribute(name = "gender", required = true)

protected GenderType gender;

public String getName() {

return name;

{public void setName(String value) { this.name = value; }

public int getAge() { return age; }

public void setAge(int value) { this.age = value; }

public XMLGregorianCalendar getBirthDate() { return birthDate; }

public void setBirthDate(XMLGregorianCalendar value) { this.birthDate =

value;}

public GenderType getGender() { return gender; }

public void setGender(GenderType value) { this.gender = value; }

}

@XmlType(name = "GenderType")

@XmlEnum

public enum GenderType {

M,F;

public String value() {

return name();

{public static GenderType fromValue(String v) {

return valueOf(v);

}

}

Page 34: Java 7 featurs

JAXB• Example:

• Marshal and un-marshal with XML and JAXB

//un-marshal XML document

JAXBContext jc = JAXBContext.newInstance("core.people");

Unmarshaller unmarshaller = jc.createUnmarshaller();

People people=(People)unmarshaller.unmarshal(new File("c:/work/People.xml"));

//create new person data

PersonType person=new PersonType();

person.setName("Newbe");

person.setAge(1);

person.setGender(GenderType.M);

//add to people

List<PersonType> persons=people.getPerson();

persons.add(person);

//marshal back to XML document

Marshaller marshaller=jc.createMarshaller();

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

marshaller.marshal(people, new FileOutputStream("c:/work/PeopleUpdated.xml"));

//set marshaller validate structure

SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema schema = sf.newSchema(new File("c:/work/PeopleSchema.xsd"));

marshaller.setSchema(schema);

JDBC

• Java 7 includes:• JDBC 4.1

• Rowset1.1

• JDBC 4.1 enhancements• Connection, Statement & ResultSet implements AutoClosable

• Can be used in try-with-resource statements

• ResultSet new method - getObject(..)

try(Statement stmt = con.createStatement()){

}

Page 35: Java 7 featurs

JDBC

• Rowset 1.1 enhancements

• WebRowSet

• Support for XML usage

• XML documents are used to insert, merge & delete data

• Queries can result in XML

• Uses a dedicated schema (XML format)

• XML documents contains:

• Properties – Rowset properties

• Metadata – mapping between XML and ResultSet tabular structure

• Data – the original data (originated from XML or DB)

Objects Utility Class

• 9 static method to work with objects

• Mainly for saving us from NullPointerException headache

DescriptionMethod

Returns c.compare(a,b). Zero means the two objects are logically identicalcompare(T a, T b, Comparator c)

Checks if the two objects identical. For arrays – checks length and 1st level elementsequals(Object o1, Object o2)

Same as equals(..), but for arrays uses Arrays.deepEquals(..) methoddeepEquals(Object o1, Object o2)

Generates a hash from the given objectshash(Object…values)

Returns o.hashCode(). If object is null – returns zerohashcode(Object o)

Returns object if not null. Else (object = null) – throws NullPointerExceptionnonNull(T object)

Same, but if null – a NullPointerException with the given message is thrownnonNull(T object, String message)

Calling the o.toString(). If the object is null – returns “null”toString(Object o)

Same – but if object is null – returns the nullMsgtoString(Object o, String nullMsg)

Page 36: Java 7 featurs

Known Issues

• Type-safe missed by the compiler

• Meanwhile – workaround:

interface A { List<Number> getList(); }

interface B { List getList(); }

interface AB extends A, B {}

class Test {

public void test(AB ab) {

Number n = ab.getList().get(1); //error here

}

}

Number n = ((A)ab).getList().get(1);

Known Issues

• Loops refactoring

• Rare bug, occurs when using

• Nested loops

• Large and complex loop body

• Results in wrong execution (!!)

• Meanwhile – disable loop optimization

• -XX:-UseLoopPredicate

Page 37: Java 7 featurs

7


Recommended