Your SlideShare is downloading. ×
0
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Tutorial 5 - IE Course Information
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Tutorial 5 - IE Course Information

652

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
652
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. IEG 4180 Tutorial 5 Prepared by Zero (Reuse some content from Chau Wai Shing)
  • 2. Outline
    • Project 3 Overview
    • HTTP message exchange
    • AJAX
    • Java Basic
    • Java Network Programming
    • Eclipse
  • 3. Project 3 Overview
    • Project 3 is divided into three parts.
      • Web Console NetProbe Server
      • SuperNetProbe
      • JavaNetProbe
  • 4. Web Console NetProbe Server
    • Extend the NetProbe Server in Project 2
      • Web-UI: open a new TCP port to accept HTTP request from a web browser (Not necessary to use select-base I/O for this port)
    • Use web browser to connect to the NetProbe Server, returning a webpage(a form) for user to configure
      • Maximum number of connections
      • Start/Stop the Server in receiving Clients’ connections
      • Killing a particular client connection
    • Another page (with AJAX) to show
      • Number of concurrent transmissions
      • Statistics of each connection
  • 5. SuperNetProbe & JavaNetProbe
    • SuperNetProbe
      • Threading (Project 2)
      • Message-Driven I/O (Project 2)
      • Alertable overlapped I/O
    • JavaNetProbe (with GUI)
      • Threading
      • New I/O
  • 6. HTTP Request
    • Browser normally analyze the URL in:
    • If no port given, browser normally determines the port number by protocol
    • And send (suppose HTTP is used) the following to { host } at { port }
    GET /{… path …} HTTP/{… version supported …} { protocol }://{ host }{: port }/{… path …}
  • 7. HTTP Response
    • The server then responds:
    • Status
      • HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT
      • Content-Type: text/html Content-Length: 1354
      • <html> <body>
      • </body> </html>
      • 200 OK :
      • The request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body.
  • 8. Introduction
    • AJAX = Asynchronous JavaScript and XML
    • Mainly based on
      • HTML (DOM)
      • JavaScript
      • XML
    • Goods
      • Smoother experience
        • No need to refresh the whole page
        • Asynchronize request
      • Rich Internet Application
    • Reference:
      • http://www.w3schools.com
  • 9. Idea
    • On specific event (e.g.: onload, onClick,…)
      • Create XMLHttpRequest object
      • Use XMLHttpRequest to submit further requests
      • Handle the response when necessary
  • 10. Example xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4){ document.myForm.time.value= xmlHttp.responseText; } } xmlHttp.open(&quot;GET&quot;,&quot;time.asp&quot;,true); xmlHttp.send(null); } </script> <body> <form name=&quot;myForm“> Name: <input type=&quot;text&quot; onkeyup=&quot;ajax ();“ name=&quot;username&quot; /> Time: <input type=&quot;text&quot; name=&quot;time&quot; /> </form> </body> </html> src: http://www.w3schools.com/ajax/ajax_server.asp <html> <script type=&quot;text/javascript&quot;> function ajax () { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp= new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;); } catch (e) { try { xmlHttp= new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } catch (e) { alert(“XMLHttpRequest object not supported!&quot;); return false; } } }
  • 11. Project Code } </script> </head> <body> <h1>NetProbe Server (Display Panel)</h1> <div id=&quot;Ajax&quot;> <p>Current Number of Connections: 0</p> <p>Clients' Statistics</p> <form action=&quot;display&quot; method=&quot;post&quot;> <table width=&quot;800&quot; border=&quot;1&quot;> <tr> <td>Client IP Address</td> <td>Protocol</td> <td>Transmission Rate(Bps)</td> <td>Packet Size(Bytes)</td> <td>Bytes Transmitted(Bytes)</td> <td> Time Elapsed(s)</td> </tr> </table><input name=&quot;Refresh&quot; type=&quot;submit&quot; value=&quot;Refresh&quot;> </form> </div> <a href=&quot;control&quot;>Control Panel</a> </body> </html> <html> <head> <title>Web based console</title> <script type='text/javascript'> var xmlhttp;window.onload=GetStatistic; function GetStatistic(){ var UpdateDiv = document.getElementById('Ajax'); //…object creation in previous page xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ UpdateDiv.innerHTML = xmlhttp.responseText; setTimeout('GetStatistic()', 2000); }else{ setTimeout('GetStatistic()', 2000); } } }; xmlhttp.open('post','ajax',true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //required by POST xmlhttp.send(null); Add statistics
  • 12. Java Basic
    • Write the program
      • Filename extension: .java
      • Filename should be the same as the public class name
      • One public class one source file
    • Compile and run the program
      • “ javac HelloWorldApp.java” (you will have “HellpWorldApp.class”)
      • “ java HelloWorldApp” (no extension)
  • 13. Hello World
    • public class HelloWorldApp { public static void main (String args[]){ System.out.println(“Hello World!”); }
    • }
    Define class name (So filename is HelloWorldApp.java) Application entry point; similar to C
  • 14. Data Type
    • Primitive Type
      • int, boolean, short, char, etc.
    • Reference Type
      • All class object
      • E.g. String, Integer, Socket, etc.
    int a; //a represent the integer itself a = 123; //just declare and use it Integer a; //a is only a reference pointer a = new Integer(123); //you must call new to create the object
  • 15. Illustration
    • Primitive Type
    • Reference Type
    int a; a = 123; a = 456; 1010 123 456 Integer a; a = new Integer(123); a = new Integer(456); null a 1000 123 1000 456 1010 ? a
  • 16. String
    • String variable1 = “Hello”;
    • String variable2 = new String(“Hello”);
    • variable1 += “ World”;
    • Convert String to int
      • int a = Integer.parseInt(“10”);
    • Convert int to String
      • String b = String.valueOf(10);
      • String b = “” + 10;
  • 17. Array
    • Array of primitive  new once
      • int[] arrayInt = new int[10]; // int arrayInt[]
      • arrayInt[0] = 123;
    • Array of reference  new twice
      • ClassApple[] apples = new ClassApple[10];
      • for (int i=0; i<apples.lenght; i++) {
      • apples[i] = new ClassApple();
      • }
  • 18. Creating Array
    • //Primitive type:
    • //int arrayOfInt[100]; <-- this is wrong
    • int arrayOfInt[] = new int[10]; //should be in this way
    • int 2DArrayOfInt[][] = {{1,2},{3,4}}; //Initialize by input array
    • //Reference type:
    • Integer arrayOfInteger[] = new Integer[10];
    • //You have declared 10 reference pointer only
    • //Remember to new an object for each reference pointer
    • for (int i = 0; i < 10; i++) {
    • arrayOfInteger[i] = new Integer(0);
    • }
    • Integer 2DArrayOfInteger[][] = {{new Integer(1), new Integer(2)},
    • {new Integer(3), new Integer(4)}}
  • 19. ArrayList
    • ~ non-fixed sized array
    • add( ), get( ), size( ), clear( ), remove( ), contains( ) and etc
    • Explicit casting on retrieved object from ArrayList
    ClassApple apple = new ClassApple(); ArrayList list = new ArrayList(); list.add(apple); ClassApple apple = (ClassApple)arrayList.get(0);
  • 20. Access Control Public: Everywhere can access it Private: Permitted only when it occurs within the class where it is declared Protected: Permitted only when it occurs within the subclass object where it is declared or in the same package public class HelloWorld { public static void main(String args[]) { /* ... * / } private void aPrivateMethod() { /* ... */ } protected void aProtectedMethod() { /* ... */ } }
  • 21. Access Control   Protected  Private    Public World Subclass Class
  • 22. Memory Management
    • Java programmer never free allocated object manually.
    • JVM will reclaim unreferenced memory through garbage collection .
    • Garbage collection is performed automatically when system is idle or runs out-of memory
    • Force garbage collection to start by calling:
    System.gc(); //Force the system to start garbage collection
  • 23. Inheritance
    • public ClassA extends ClassB implements ClassC, ClassD { … }
    • extends only one Class but implements multiple Interface
    • Interface is like a contract, its subclasses must do all it said (give implementation to all declarations in the interface)
  • 24. Inheritance
    • Interface is a fully abstract class, while general abstract class can implement some methods
    • If methods of ClassB is not override in ClassA, ClassB’s implementation will be used; all methods are implicitly virtual
    • ClassA MUST gives implementation to all methods of ClassC and ClassD
  • 25. Handling Exception
    • To handle exception you either:
      • Catch it:
      • Throw it:
    try { Socket s = new Socket(host, port); // … Thread.currentThread().sleep(10); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { System.out.println(e.toString()); } public void connect() throws IOException { Socket s = new Socket(host, port); }
  • 26. The finally clause
    • Some codes may not be executed due to exception:
    • Using the finally clause:
    try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) out.println(v.elementAt(i)); out.close( ): // may not be executed } catch (IOException e) { System.err.println(“Caught IOException”); } try { PrintWriter out = new PrintWriter(new FileWriter(“out.txt”)); for (int i=0; i<SIZE; i++) out.println(v.elementAt(i)); } catch (IOException e) { System.err.println(“Caught IOException”); } finally { if (out != null) out.close(); }
  • 27. Creating Thread
    • Method 1: Extend the Thread class:
    class Primethread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime } } PrimeThread p = new PrimeThread(143); // create the thread p.start(); // start the thread
  • 28. Creating Thread
    • Method 2: Implement Runnable and run by a thread:
    class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime } } Thread aThread = new Thread( new PrimeRun(143) ); aThread.start();
  • 29. Mutual Exclusion
    • Java has the keyword synchronized for mutual Exclusion
    • It is applicable to a class, method and a block of code
    • Any Java Objects can be used for synchronization while the Built-in type(int, fload…) cannot
  • 30. Mutual Exclusion
    • Synchronization on a Block / Statement Level (Use object for synchronization)
      • Class newThread{
        • Static Object Lock = new Object();
        • public someMethod(){
        • synchronized(Lock){
        • // the code that need mutual exclusion
        • }
        • }
    • As Lock is static, so only one instance exists no matter how many newThread instance exists already. As a result, only one thread can run the “Lock” code concurrently
  • 31. Mutual Exclusion
    • Synchronization on a Method / Instance Level :
    • class newThread implements Runnable{
    • synchronized void someMethod(){
    • }
    • }
    • It ensure that only one thread can call an object’s method at a time
    • But if there are two instances of newThread, then someMethod() can be executed by two different threads concurrently.
  • 32. Mutual Exclusion
    • Synchronization on a Class Level :
    • class newThread implements Runnable{
    • static synchronized void someMethod(){
    • }
    • }
    • This one can be applied for any (Threaded) class methods
  • 33. Java NIO
    • Java New IO package: java.nio
    • New features:
      • Buffer for data of primitive type.
      • Character-set encoders and decoders.
      • Channels, a new primitive I/O abstraction.
      • A multiplexed, non-blocking I/O facility for writing scalable servers.
  • 34. Read/Write Through Channel
    • Read/Write is done through buffer objects instead of input and output streams.
    • Send/Receive chars:
    Charset charset = Charset.forName(&quot;US-ASCII&quot;); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); // write string sChannel.write( encoder.encode(CharBuffer.wrap(&quot;Your msg.&quot;)) ); // read string ByteBuffer dbuf = ByteBuffer.allocateDirect(1024); sChannel .read(dbuf) ; dbuf.flip(); String msg = decoder.decode(dbuf).toString() ;
  • 35. Read/Write Through Channel
    • Read/Write is done through buffer objects instead of input and output streams.
    • Send/Receive raw-bytes:
    // writing raw-bytes // wrap you data in byte array buf into ByteBuffer object ByteBuffer buffer = ByteBuffer.wrap(buf) ; sChannel. write(buffer) ; // read string ByteBuffer buffer = ByteBuffer.allocateDirect(1024) ; sChannel. read(buffer) ;
  • 36. ServerSocketChannel
    • The ServerSocketChannel class is channel-based socket listener.
    • It performs the same basic task as the familiar ServerSocket class.
    • To create a ServerSocketChannel that listen on a particular port.
    ServerSocketChannel ssc = ServerSocketChannel.open() ; ServerSocket serverSocket = ssc.socket (); serverSocket.bind (new InetSocketAddress(1234));
  • 37. SocketChannel
    • SocketChannel acts as the client, initiating a connection to listening server.
    • It is the channel-based counterpart of the Socket class.
    • To create a SocketChannel that connects to remote server:
    SocketChannel socketChannel = SocketChannel.open (); socketChannel. connect( new InetSocketAddress( &quot; someHost &quot; , somePort) ) ;
  • 38. Non-Blocking I/O
    • We can configure the I/O operation of a channel to be blocking and non-blocking.
    • To configure a channel to be non-blocking:
    serverSocketChannel .configureBlocking(false) ; socketChannel. configureBlocking(false) ;
  • 39. Introduction
    • Another IDE
      • Originally for Java
      • C++, PHP, COBOL, etc. are also supported
    • Similar to NetBean
      • Written in Java
      • Require JVM
    • Vast amount of plugins available
  • 40. Where to get it?
    • Project homepage http://www.eclipse.org/
    • GUI building requires Visual Editor (VE) http://www.eclipse.org/vep/WebContent/main.php Download: http:// download.eclipse.org/tools/ve/downloads/index.php
    • Latest VE support up to Eclipse 3.2 http://archive.eclipse.org/eclipse/downloads/drops/R-3.2.2-200702121330/
    • For simplicity, download Eclipse, VE, EMF and GEF from http://download.eclipse.org/tools/ve/downloads/drops/R-1.2.3_jem-200701301117/index.html
  • 41. Startup
  • 42. Step 1
    • “ New”
    • “ Project”
    • ” Java Project&quot;
  • 43. Console Program - Step 2
    • “ New”
    • “ Class” Check the “public static void…” for startup class
  • 44. Console Program - Step 3
    • “ Run…” / “Debug…”
    • “ Java Application” Select (or use the detected) class as “Main class”
  • 45. GUI Program - Step 2
    • “ New”
    • “ Visual Class” Check the “public static void…” for startup class This example use “JFrame”
  • 46. GUI Program - Step 3
    • “ Run…” / “Debug…”
    • “ Java Bean” Select (or use the detected) class as “Java Bean”

×