SlideShare a Scribd company logo
1 of 14
Download to read offline
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 .NETAbhi 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- attributesMohammad Alyan
 
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 InterfacesPawanMM
 
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 2Sagar Verma
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange openingMartin 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 Dragos3Pillar Global
 
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 IVHari Christian
 
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 & CollectionsAnton 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 & EncodingsAnton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problemAnton 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 & ServletsAnton 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, HibernateAnton 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 engineerAnton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to AgileAnton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: IntroductionAnton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsAnton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton 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

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, 11Ivelin 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 - ThreadsWebStackAcademy
 
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 Leejaxconf
 
04 android
04 android04 android
04 androidguru472
 
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfacesKalai Selvi
 
Lecture 5 interface.pdf
Lecture  5 interface.pdfLecture  5 interface.pdf
Lecture 5 interface.pdfAdilAijaz3
 
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
 
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
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 

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
 
Java seminar.pptx
Java seminar.pptxJava seminar.pptx
Java seminar.pptx
 
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?
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

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