java course 9: networking and reflection

14
Networking, Networking, Reflection & Logging Reflection & Logging Java course - IAG0040 Java course - IAG0040 Anton Keks 2011

Upload: anton-keks

Post on 26-May-2015

1.281 views

Category:

Technology


1 download

DESCRIPTION

Lecture 9 from the IAG0040 Java course in TTÜ. See the accompanying source code written during the lectures: https://github.com/angryziber/java-course

TRANSCRIPT

Page 1: Java Course 9: Networking and Reflection

Networking,Networking,Reflection & LoggingReflection & Logging

Java course - IAG0040Java course - IAG0040

Anton Keks 2011

Page 2: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 22

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

NetworkingNetworking

● Java provides cross-platform networking facilities

● java.net and javax.net packages contain many useful classes

● API is generally protocol independent, but implementation supports mostly Internet transport protocols, e.g. TCP and UDP

● java.net.InetAddress represents an IP address (immutable)

– Inet4Address represents 32-bit IPv4 addresses (4 billions)

– Inet6Address represents 128-bit IPv6 addresses (3.4 x 1038)

– It is able to detect address types, provides naming services, and various other checks and conversions

– Create using InetAddress.getByAddress(...), getByName(...) or getLocalHost()

– Many getXXX() and isXXX() methods provided

Page 3: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 33

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

SocketsSockets

● Sockets are used as endpoints in network communication

● java.net.InetSocketAddress represents an address-port pair

● There are several types of sockets in Java

– Socket and ServerSocket – connection-oriented streaming reliable client and server sockets (TCP)

– SSLSocket and SSLServerSocket – client and server sockets for secure encrypted communication (TCP via SSL)

– DatagramSocket – packet-oriented unreliable socket for both sending and receiving data (UDP), can be used for both unicasting and broadcasting

– MulticastSocket – datagram socket with multicasting support

● Socket implementations depend on respective factory classes. Direct usage uses the default socket factory for the given socket type.

Page 4: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 44

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Networking ExceptionsNetworking Exceptions

● Most networking exceptions extend SocketException

● SocketException extends IOException, showing that networking is highly related to all other more generic I/O classes

Page 5: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 55

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Streaming SocketsStreaming Sockets● Socket and ServerSocket can be used for streaming

● Underlying Socket implementations are provided by SocketImplFactory classes by the means of SocketImpl classes. Default implementation is plain TCP.

● getInputStream() and getOutputStream() are used for obtaining the streams, both can be used simultaneously

● Various socket options may be set using provided set methods

● There are many informative is/get methods provided

● Stream sockets must be closed using the close() method

– it closes both streams automatically as well

Page 6: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 66

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Datagram SocketsDatagram Sockets

● DatagramSocket is used for sending and receiving of DatagramPackets; receiving is actually 'listening'

● Connection-less, no streams provided

● connect() and disconnect() is used for selecting/resetting the remote party's address and port

● Special addresses can be used for sending/receiving of broadcast packets, e.g. 192.168.0.255

● MulticastSocket can be used for joining/leaving multicast groups of DatagramSockets. Multicast groups have special addresses.

Page 7: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 77

URL and URLConnectionURL and URLConnection

● Java also provides higher-level networking APIs than Sockets

● URI and URL classes provide construction and parsing of the respective Strings (all URLs are URIs, however)

– URI is a newer class and provides encoding/decoding of escaped symbols, like %20

– Conversions back and forth are possible using toURI() and toURL() methods

● URLConnection provides API for reading/writing of the resources referenced by URLs

● url.openConnection() returns a subclass of URLConnection, according to the registered protocol-specific URLStreamHandler

Page 8: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 88

URL and URLConnection (cont)URL and URLConnection (cont)

● Obtained URLConnection can be used for setting various parameters (headers)

– Actual connection is opened using the connect() method

– Both getInputStream() and getOutputStream() are provided

– getContent() returns an Object according to the MIME type of the resource, which ContentHandler is provided by the ContentHandlerFactory

● url.openStream() is a shortcut if you need to just retrieve the data without any extra features

● Proxy/ProxySelector can be used for proxying of traffic

Page 9: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 99

Networking TaskNetworking Task

● Implement the FileDownloader (eg using existing DataCopier implementation)

● Try your code with various Input and Output streams

– Files, Sockets, URLs● Create FileSender and FileReceiveServer classes. Reuse

already written code to send file content over the socket and save content to another file on the server end

Page 10: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 1010

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Reflection APIReflection API

● The reflection API represents, or reflects, the classes, interfaces, and objects in the current JVM– It is possible to dynamically collect information about

all aspects of compiled entities, even access private fields

● Reflection API is in java.lang and java.lang.reflect packages

● Note: Reflection API is also full of generics (for convenience)

Page 11: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 1111

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Reflection API usageReflection API usage

● Where is it appropriate to use it?– various plugins and extensions: load classes by

name, etc– JUnit uses reflection for finding test methods

either by name or annotations– Many other famous frameworks use reflection, e.g.

Hibernate, Spring, Struts, Log4J, JUnit, etc● Caution: use reflection only when it is absolutely

necessary!

Page 12: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 1212

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Examining ClassesExamining Classes● Class objects reflect Java classes

– Every Object provides the getClass() method

– Various methods of Class return instances of Field, Method, Constructor, Package, etc

● methods in plural return arrays, e.g. getFields(), getMethods()● methods in singular return single instances according to search

criteria, e.g. getField(...), getMethod(...)

– Class can also represent primitive types, interfaces, arrays, enums and annotations

● Java supports Class literals, e.g. String.class, int.class

● Class.forName() is used for loading classes dynamically

● Modifiers: Modifier.isPublic(clazz.getModifiers())

● getSuperclass() returns the super class

Page 13: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 1313

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Instantiating ClassesInstantiating Classes

● clazz.newInstance() works for default constructors

● Otherwise getConstructor(...) will provide a Constructor instance, which has its own newInstance(...)

● Singular Constructor and Method finding methods take Class instances for matching of parameters:

– Constructor c = clazz.getConstructor(int.class, Date.class);

● Then, creation (newInstance) or invocation (invoke) takes the real parameter values:

– Object o = c.newInstance(3, new Date());

– Primitive values are autoboxed to their wrapper classes

Page 14: Java Course 9: Networking and Reflection

Lecture 9Lecture 9Slide Slide 1414

Java course – IAG0040Java course – IAG0040Anton KeksAnton Keks

Reflection TipsReflection Tips● Array class provides additional options for dynamic manipulation of arrays

● Even this works: byte[].class

● Retrieve class name of any object: object.getClass().getName()

● Don't hardcode class names in Strings: MegaClass.class.getName() or .getSimpleName() is better

● Accessing private fields:

– boolean wasAccessible = field.getAccessible(); field.setAccessible(true); Object value = field.get(instance); field.setAccessible(wasAccessible);

● Dynamic proxies allow to wrap objects and intercept method calls on them defined in their implemented interfaces:

– Object wrapped = Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() { ... });