SlideShare a Scribd company logo
Java course - IAG0040




                 Networking,
             Reflection & Logging



Anton Keks                             2011
Networking
 ●   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 10 38)
      –   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
Java course – IAG0040                                                     Lecture 9
Anton Keks                                                                  Slide 2
Sockets
 ●   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.

Java course – IAG0040                                                   Lecture 9
Anton Keks                                                                Slide 3
Networking Exceptions
 ●
     Most networking exceptions extend
     SocketException
 ●   SocketException extends IOException, showing
     that networking is highly related to all other
     more generic I/O classes




Java course – IAG0040                         Lecture 9
Anton Keks                                      Slide 4
Streaming 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


Java course – IAG0040                                      Lecture 9
Anton Keks                                                   Slide 5
Datagram 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.

Java course – IAG0040                                     Lecture 9
Anton Keks                                                  Slide 6
URL 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
                                                             Lecture 9
                                                               Slide 7
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
                                                         Lecture 9
                                                           Slide 8
Networking 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




                                                       Lecture 9
                                                         Slide 9
Reflection 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)

Java course – IAG0040                                      Lecture 9
Anton Keks                                                  Slide 10
Reflection 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!

Java course – IAG0040                                     Lecture 9
Anton Keks                                                 Slide 11
Examining 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
Java course – IAG0040                                                      Lecture 9
Anton Keks                                                                  Slide 12
Instantiating 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

Java course – IAG0040                                              Lecture 9
Anton Keks                                                          Slide 13
Reflection 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() { ... });
Java course – IAG0040                                                  Lecture 9
Anton Keks                                                              Slide 14

More Related Content

What's hot

Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
Abhi Arya
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
2 second lesson- attributes
2 second lesson- attributes2 second lesson- attributes
2 second lesson- attributes
Mohammad Alyan
 
Core java1
Core java1Core java1
Core java1
Ravi varma
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and Interfaces
PawanMM
 
28 networking
28  networking28  networking
28 networking
Ravindra Rathore
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Just entity framework
Just entity frameworkJust entity framework
Just entity framework
Marcin Dembowski
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
Hitesh-Java
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
Riccardo Cardin
 
Basics of building a blackfin application
Basics of building a blackfin applicationBasics of building a blackfin application
Basics of building a blackfin application
Pantech ProLabs India Pvt Ltd
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
People Strategists
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange opening
Martin Odersky
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
04 sorting
04 sorting04 sorting
04 sorting
martchasera92
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
Hari Christian
 
Java
Java Java
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Skills Matter
 

What's hot (19)

Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
2 second lesson- attributes
2 second lesson- attributes2 second lesson- attributes
2 second lesson- attributes
 
Core java1
Core java1Core java1
Core java1
 
Session 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and InterfacesSession 10 - OOP with Java - Abstract Classes and Interfaces
Session 10 - OOP with Java - Abstract Classes and Interfaces
 
28 networking
28  networking28  networking
28 networking
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Just entity framework
Just entity frameworkJust entity framework
Just entity framework
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Basics of building a blackfin application
Basics of building a blackfin applicationBasics of building a blackfin application
Basics of building a blackfin application
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange opening
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
04 sorting
04 sorting04 sorting
04 sorting
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Java
Java Java
Java
 
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
 

Viewers also liked

Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
Anton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
Anton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
Anton Keks
 
java packages
java packagesjava packages
java packages
aptechsravan
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
Anton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
Anton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
Anton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
Anton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Anton Keks
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 

Viewers also liked (20)

Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
java packages
java packagesjava packages
java packages
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java package
Java packageJava package
Java package
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 

Similar to Java Course 9: Networking and Reflection

Lecture10
Lecture10Lecture10
Lecture10
vantinhkhuc
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
Ivelin Yanev
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
WebStackAcademy
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Lee
jaxconf
 
Java adv
Java advJava adv
NETWORKING EN JAVA CLASSES IN THE JDK...
NETWORKING EN JAVA  CLASSES IN THE JDK...NETWORKING EN JAVA  CLASSES IN THE JDK...
NETWORKING EN JAVA CLASSES IN THE JDK...
Patricio Ligista de Corazon
 
Java seminar.pptx
Java seminar.pptxJava seminar.pptx
Java seminar.pptx
shirindigitel
 
Java training materials for computer engineering.pdf
Java training materials for computer engineering.pdfJava training materials for computer engineering.pdf
Java training materials for computer engineering.pdf
SkvKirupasri
 
04 android
04 android04 android
04 android
guru472
 
Spock
SpockSpock
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
Francesco Nolano
 
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfaces
Kalai Selvi
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
Khurshid Asghar
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
AdilAijaz3
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
WebStackAcademy
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
Kan-Han (John) Lu
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
Martijn Verburg
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
King's College London
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
Michal Malohlava
 

Similar to Java Course 9: Networking and Reflection (20)

Lecture10
Lecture10Lecture10
Lecture10
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Lee
 
Java adv
Java advJava adv
Java adv
 
NETWORKING EN JAVA CLASSES IN THE JDK...
NETWORKING EN JAVA  CLASSES IN THE JDK...NETWORKING EN JAVA  CLASSES IN THE JDK...
NETWORKING EN JAVA CLASSES IN THE JDK...
 
Java seminar.pptx
Java seminar.pptxJava seminar.pptx
Java seminar.pptx
 
Java training materials for computer engineering.pdf
Java training materials for computer engineering.pdfJava training materials for computer engineering.pdf
Java training materials for computer engineering.pdf
 
04 android
04 android04 android
04 android
 
Spock
SpockSpock
Spock
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfaces
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdf
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 

Recently uploaded

EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 
Feature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptxFeature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptx
ssuser1915fe1
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
aakash malhotra
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 
Tailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer InsightsTailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer Insights
SynapseIndia
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
BrainSell Technologies
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
shanihomely
 
(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...
(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...
(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...
Priyanka Aash
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
HackersList
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptxIntroduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
313mohammedarshad
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
bellared2
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes..."Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
Anant Gupta
 

Recently uploaded (20)

EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 
Feature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptxFeature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptx
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 
Tailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer InsightsTailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer Insights
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
Acumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptxAcumatica vs. Sage Intacct _Construction_July (1).pptx
Acumatica vs. Sage Intacct _Construction_July (1).pptx
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
 
(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...
(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...
(CISOPlatform Summit & SACON 2024) Orientation by CISO Platform_ Using CISO P...
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptxIntroduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes..."Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
"Mastering Graphic Design: Essential Tips and Tricks for Beginners and Profes...
 

Java Course 9: Networking and Reflection

  • 1. Java course - IAG0040 Networking, Reflection & Logging Anton Keks 2011
  • 2. Networking ● 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 10 38) – 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 Java course – IAG0040 Lecture 9 Anton Keks Slide 2
  • 3. Sockets ● 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. Java course – IAG0040 Lecture 9 Anton Keks Slide 3
  • 4. Networking Exceptions ● Most networking exceptions extend SocketException ● SocketException extends IOException, showing that networking is highly related to all other more generic I/O classes Java course – IAG0040 Lecture 9 Anton Keks Slide 4
  • 5. Streaming 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 Java course – IAG0040 Lecture 9 Anton Keks Slide 5
  • 6. Datagram 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. Java course – IAG0040 Lecture 9 Anton Keks Slide 6
  • 7. URL 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 Lecture 9 Slide 7
  • 8. 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 Lecture 9 Slide 8
  • 9. Networking 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 Lecture 9 Slide 9
  • 10. Reflection 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) Java course – IAG0040 Lecture 9 Anton Keks Slide 10
  • 11. Reflection 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! Java course – IAG0040 Lecture 9 Anton Keks Slide 11
  • 12. Examining 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 Java course – IAG0040 Lecture 9 Anton Keks Slide 12
  • 13. Instantiating 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 Java course – IAG0040 Lecture 9 Anton Keks Slide 13
  • 14. Reflection 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() { ... }); Java course – IAG0040 Lecture 9 Anton Keks Slide 14