Java Spaces - PowerPoint PPT Presentation

About This Presentation
Title:

Java Spaces

Description:

Fundamentos de Redes de Computadores ... Java Spaces – PowerPoint PPT presentation

Number of Views:126
Avg rating:3.0/5.0
Slides: 50
Provided by: vicgaete
Category:
Tags: java | spaces

less

Transcript and Presenter's Notes

Title: Java Spaces


1
Java Spaces
2
Definition according to sun
  • JavaSpacesTM technology is a simple unified
    mechanism for dynamic communication,
    coordination, and sharing of objects between
  • JavaTM technology-based network resources
    like clients and servers. In a distributed
    application, JavaSpaces technology acts as a
    virtual space between providers and requesters of
    network resources or objects. This allows
    participants in a distributed solution to
    exchange tasks, requests and information in the
    form of Java technology-based objects. JavaSpaces
    technology provides developers with the ability
    to create and store objects with persistence,
    which allows for process integrity.

3
JavaSpaces is part of the Jini spec.
  • Jini is a collection of service specifications
  • They help services to find each other on the
    network
  • The most common notion people have from Jini is
    that enables jini powered machines to be attached
    to the network and automatically find out which
    services are available, as well as post its own
    services to the rest
  • Jini based machines are servers and client at the
    same time

4
Example
?
5
Services provided by Jini
Lookup Services (reggie)
rmid
JavaSpace (outriggger)
Fiddler Mercury Norm
Transaction Services (mahalo.jar)
HTTP-Server (tools.jar)
6
What does JavaSpaces provides
  • A space in which objects can be stored in,
    retrieved from, copied from.
  • A set of methods write, read, take,
    (readIfExists, takeIfExists)
  • A mechanism to ensure completeness of
    transactions
  • An event notify mechanism

7
The write and read
write
Space
read
A copy
8
The take
write
Space
X
take
Exists only here
9
How can I create a JavaSpace in a host
  • A JavaSpace can be created by starting the
    outrigger service of Jini with a certain name as
    parameter. This will be the name of the space.
  • Before starting the outrigger it is necessary to
    start
  • The http server tools.jar
  • An rmid
  • The lookup server rigger
  • The transaction server mahalo

10
How can I write objects into a Space
  • User defined object classes must declare they
    implement the interface Entry.
  • This does not mean it has to implement any
    methods. It is just a tag to tell the system an
    object of this class can be written in a
    JavaSpace
  • Fields (variables) in this class should be
    objects. If primitives are needed (such as
    integers) use wrappers
  • Integer i new Integer(4)

11
Example of an Entry class
  • import net.jini.core.entry.Entry
  • public class Message implements Entry
  • public String content
  • public Integer counter
  • public Message() //this is mandatory !!!!!
  • public Message(String content, int initVal)
  • this.content content
  • counter new Integer(initVal)
  • public String toString()
  • return content counter " times."
  • public void increment()
  • counter new Integer(counter.intValue()
    1)

12
Storing objects in a space
  • import net.jini.core.lease.Lease
  • import net.jini.space.JavaSpace
  • import java.io.
  • public class WriteMessages
  • public static void main(String args)
  • try
  • BufferedReader in new BufferedReader(
  • new InputStreamReader(System.in))
  • JavaSpace space SpaceAccessor.getSpace(
    )
  • System.out.print("Message ? ")
  • String m in.readLine()
  • Message2 msg new Message2(m,0)
  • space.write(msg, null, Lease.FOREVER)
  • catch (Exception e) e.printStackTrace()

13
The write sentence
  • space.write(msg, null, Lease.FOREVER)
  • The Parameters an Entry object (the Message), a
    transaction object (null for now) and a long
    (leasing time in milliseconds, Lease.FOREVER is
    the value to make it permanent).

14
Retrieving objects in a space
  • import java.io.
  • import net.jini.core.lease.Lease
  • import net.jini.space.JavaSpace
  • public class ReadMessage
  • public static void main(String args)
  • try
  • Message2 template
  • JavaSpace space SpaceAccessor.getSpace()
  • BufferedReader in new BufferedReader(
  • new InputStreamReader(System.in))
  • System.out.print("Message (null)? ")
  • String m in.readLine()
  • template new Message2(m)
  • Message2 result
  • (Message2)space.read(template,null,Long.MAX_V
    ALUE)
  • System.out.println("Got
    "result.toString())
  • catch (Exception e) e.printStackTrace()

15
Rules for retrieving objects
  • The object must match the template according to
    the class and the content
  • Null references in the template act as wildcards
  • There is no rule for deciding which of all the
    matching objects in the space matching the
    template will be retrieved
  • The parameters a template object, a transaction
    (null) and a waiting time before the read
    sentence gives up if it does not find an object
    which matches the template. Long.MAX_VALUE is for
    waiting forever

16
Taking objects
  • It works just like read but the object is deleted
    from the space
  • In order to avoid deadlocks or waiting, it is
    possible to use readIfExists and takeIfExists
  • Their structure is the same as read and take, but
    they will return immediately if they do not find
    any matching object in the space
  • The SpaceAccessor class with the getSpace method
    is not standard, see SpaceAccessor.java

17
Synchronizing clients
  • Customer
  • 1- takes a number,
  • 2- increments Ticket Disp.
  • 3- takes the service object
  • when it has this number
  • 4- waits for being served
  • 5-Increments service number
  • A client will be served
  • Only if it has the service
  • number

Ticket Dispenser
number
Service Number
number
See TicketInit.java Customer.java
18
And of courseChatting
A Tail object indicates which is the number of
the last message Every message has a content
And a number The channel identifies a
chat.-thred
Tail
Channel
position
See Tail.java, MessageChannel.java,
CreateChannel.java, ChatSpace.java
19
Distributed Events
3- an object matching template Enters the space
4- the listener is nofied
2- Notify space about interest With a template
1- Create a Listener object
20
How to write a listener
  • import java.rmi.server.
  • import java.rmi.RemoteException
  • import net.jini.core.event.
  • import net.jini.space.JavaSpace
  • public class Listener implements
    RemoteEventListener
  • private JavaSpace space
  • public Listener(JavaSpace space) throws
    RemoteException
  • this.space space
  • UnicastRemoteObject.exportObject(this)
  • public void notify(RemoteEvent ev)
  • Message template new Message()
  • try Message result
  • (Message)space.read(template, null,
    Long.MAX_VALUE)
  • System.out.println(result.content)
  • catch (Exception e)
  • e.printStackTrace()

21
A program that listens
  • import net.jini.core.lease.Lease
  • import net.jini.space.JavaSpace
  • public class HelloWorldNotify
  • public static void main(String args)
  • JavaSpace space SpaceAccessor.getSpace()
  • try
  • Listener listener new
    Listener(space)
  • Message template new Message()
  • space.notify(template, null,
    listener,
  • Lease.FOREVER, null)
  • catch (Exception e)
  • e.printStackTrace()

22
Calling the notify method
  • After this, if any program writes a message (no
    matter the content) the Listener object of the
    HelloWorldNotify program will be notified, this
    means, the notify method will be called
  • Message msg new Message()
  • msg.content "Hello World"
  • space.write(msg, null, Lease.FOREVER)

23
Transactions
  • A transaction is a set of instructions which
    should be all executed atomically or none at all.
  • In JavaSpaces this refers to write, read, and
    take instructions that can be scheduled to be
    performed in this way.
  • For this, a transaction object should be created
    and passed as an argument in every instruction
    which belongs to the transaction
  • After all write, read, take, etc.instructions
    with (the same) transaction are executed, a
    commit statement will either perform all the
    operations or no one.
  • In the latter case, an exception is thrown

24
An example
  • JavaSpace space SpaceAccessor.getSpace()
  • TransactionManager mgr
  • TransactionManagerAccessor.getManager(
    )
  • //get a reference to the transaction manager
    service
  • Try
  • Transaction.Created trc
  • TransactionFactory.create(mgr, 3000)
  • Transaction txn trc.transaction
  • SharedVar template new SharedVar(url)
  • SharedVar counter
  • (SharedVar) space.take(template, txn,
    Long.MAX_VALUE)
  • counter.increment()
  • space.write(counter, txn, Lease.FOREVER)
  • txn.commit()
  • catch (Exception e)
  • System.err.println("Transaction failed")
    return

25
Java Applets
Applets are java programs which are downloaded
with the HTML page.
Html
Animator.class
Animator.class
Java program running on the client
ltapplet codeAnimator.class gt ltparametersgt lt/apple
tgt
26
Java Script
The code of the java program is written directly
in the HTML page
Html Script
ltscript language JavaScriptgt the
code lt/scriptgt
Java program running on the client
27
Java Servlets
The code of the java program which runs on the
server and can dynamically produce HTML content
according to the particular situation (the client
of a bank)
HTML from page
HTML from servlet
MyServlet.class
HTML-page with a reference to a servlet
28
Java Server Pages (and ...)
  • Like Java Script for applets, JSP is a script
    language programming for servlets
  • The code is written inside the HTML page but it
    is executed on the server
  • The server will dynamically generate HTML code,
    which will be written into the clients browser

29
How can I explain what is an Applet ?
  • For people like you, who already master Java
    programming it is very easy an applet is a Panel
    in an HTML page in which I can program (almost)
    everything I can program in a normal Panel.

Bla Bla Bla Bla
The html viewer
The applet
Bla Bla Bla Bla
30
How do I link an Applet in my HTML Page ?
ltHTMLgt ltHEADgt ltTITLEgt My first Applet
lt/TITLEgt lt/HEADgt ltBODYgt ....... Here is how you
attach an applet to your html page!!! ltAPPLET
CODE MyApplet.class WIDTH150
HEIGTH25gt lt/APPLETgt ..... lt/BODYgt
You must provide an Applet which is programmed in
a file named MyApplet.java and compiled just as
any other class
31
How do I Program an Applet ?
Lets start with a very simple one
import java.applet. import java.awt. public
class MyApplet1 extends Applet public void
paint(Graphics g) g.drawString(Hello
World,50,25)
This tells us the applet is a kind of frame !!
32
Remember the Jalisco Program ?
import java.awt. import java.applet.import
java.awt.event. public class Jalisco1 extends
Applet Label question new Label("Enter a
number ") Label answer new Label("
") TextField number new
TextField(9) public void init()
add(question) add(number) add(answer) set
Background(Color.green) number.addActionListener
( new ActionListener() //this will make
the thexfield react when an enter is typed
public void actionPerformed(ActionEven
t x) String s number.getText()
int n Integer.parseInt(s)
answer.setText("I win with the " (n1))
)

33
The applet has a life cycle
  • When an applet is loaded
  • The applet initializes itself, running the init()
    method if provided
  • The applet starts running, executing the start()
    method if provided
  • When you leave and return to the page
  • when leaving the page (going to another page) the
    applet stops itself, executing the stop() method
    before if provided
  • when returning to the page it srarts again
    executing the start() method
  • When quitting the browser
  • the applet can run the destroy() method if
    provided

34
Secutiry with applets
  • The applet is a running program in my computer
    which I just downloaded from the network how can
    I be sure it will not harm my computer ?
  • Applets cannot read or write the disks of the
    host computer !
  • Because java has not pointer arithmetic a class
    generated by the compiler cannot read or write
    other memory than just the memory of the program
    (in C we have this problem !!)
  • In order to avoid Trojan Horses, every applet is
    signed by the compiler. This means, if a .class
    file was not generated by the compiler, it can be
    easily detected by the applet loader of the
    viewer and it doesn't allow it to run

35
What Applets Can't Do
  • It cannot ordinarily read or write files on the
    host that is executing it.
  • It cannot make network connections except to the
    host that it came from.
  • It cannot start any program on the host that's
    executing it.
  • It cannot read certain system properties.
  • Windows that an applet brings up look different
    than windows that an application brings up.

36
What Applets Can Do
  • Applets can usually make network connections to
    the host they came from.
  • Applets running within a Web browser can easily
    cause HTML documents to be displayed.
  • Applets can invoke public methods of other
    applets on the same page.
  • Applets that are loaded from the local file
    system (from a directory in the user's CLASSPATH)
    have none of the restrictions that applets loaded
    over the network do.
  • Although most applets stop running once you
    leave their page, they don't have to.

37
Servlets
  • Servlets are modules that extend
    request/response-oriented servers, such as
    Java-enabled web servers.
  • A servlet might be responsible for taking data in
    an HTML order-entry form and applying the
    business logic used to update a company's order
    database.
  • Servlets are an effective replacement for CGI
    scripts. They provide a way to generate dynamic
    documents that is both easier to write and faster
    to run.
  • Servlets also address the problem of doing
    server-side programming with platform-specific
    APIs they are developed with the Java Servlet
    API, a standard Java extension.

38
Preliminary Work
  • The javax.servlet package provides interfaces and
    classes for writing servlets
  • This is not part of the standard language, it is
    necessary to download JSDK(2.1) package
  • Not all web servers can serve servlets, you
    should either have one with this capability(e.g.
    Tomcat), download a plug-in, or use the
    servletrunner
  • Each servlet server has it rules how to make
    servers accessible. In most cases, you should
    specify a certain path where servlets are located
  • In order to be able to compile servlets you will
    need to put the jsdk.jar file in the propper
    directory (c\jdk1.3\jre\lib\ext)

39
The Anatomy of a Servlet
  • A new servlet class is defined by extending
    HttpServlet class (in most cases)
  • The most important pre-defined methods of a
    servlet are
  • init() it is called when the servlet is called
    for the first time (uploaded)
  • doGet(HttpServletRequest req, HttpServletResponse
    res) throws ServletException, IOException
  • Called when servlet invoked by a GET Http request
  • doPost(HttpServletRequest req, HttpServletResponse
    res) throws ServletException, IOException
  • Called when servlet invoked by a POST Http
    request

40
Anatomy of a servlet
  • A GET request is always generated when an http
    request is typed into a browser
    (http//www.yahoo.com/ means GET index.html
    Httpx.x )
  • When the server is called for the first time, it
    is initialized and 4-6 threads for attending
    clients are started, this means they may be
    served in parallel
  • In most cases, servlets are contacted by forms in
    html pages. In this cases, it is possible to
    specify some parameters and contact the servlet
    by the POST method.

41
A First example
  • The servlet will be contacted directly by an http
    expression in the browser
  • http//collide.informatik.uni-duisburg.de/servlets
    /SimpleServlet
  • This will cause the doGet method to be called
  • The servlet will answer by writing in the
    clients browser a page with a simple message

42
A Second example
  • The servlet will be contacted by an action
    triggered from the web browser
  • http//collide.informatik.uni-duisburg.de/servlets
    /Servlet1.htm
  • The different buttons will call the doPost and
    the doGet methods

43
A Third Example
  • We will now develop a web counter
  • It will keep track about how many instances of
    the servlet have been created and how many times
    these instances have reacted to clients requests
  • See Count.java

44
Passing parameters
  • It is possible to pass parameters to the doGet
    method in the command line
  • http//hostport/servlet?param1value1param2valu
    e2..
  • The servlet can ask for a value parameter value
  • String value req.getParametervalues(param1)
  • Parameters are only strings
  • See ServletParameter1.java

45
We can use the same with Forms
  • A form will be an html page in which we can write
    a string and send the request to the servlet
  • We can use the same servlet !!!!
  • see ServletParameter1.html
  • Another example with more parameters
  • SurveyServlet with JdcSurvey

46
Obtaining more information about the client
  • We can get a lot of information about the request
    made by the client such like
  • URL request
  • Data about the clients host
  • Parameters names and values
  • Header of the request
  • etc
  • Try SnoopServlet?par1val1par2val2

47
Session Tracking
  • Session tracking is a mechanism that servlets use
    to maintain state about a series of requests from
    the same user (that is, requests originating from
    the same browser) across some period of time.
  • See SessionServlet

48
Using Cookies
  • Cookies are a way for a servlet to send some
    information to a client to store, and for the
    server to later retrieve its data from that
    client.
  • Servlets send cookies to clients by adding fields
    to HTTP response headers.
  • Clients automatically return cookies by adding
    fields to HTTP request headers.
  • Cookies have a name and a value (additionally
    they can have some comments).
  • In addition to a name and a value, you can also
    provide optional attributes such as comments.
  • A server can provide one or more cookies to a
    client.

49
Using Cookies
  • To send a cookie
  • 1.Instantiate a Cookie object
  • 2.Set any attributes
  • 3.Send the cookie
  • To get information from a cookie,
  • 1.Retrieve all the cookies from the user's
    request
  • 2.Find the cookie by its name
  • 3.Get the values of the cookies that
    you found
Write a Comment
User Comments (0)
About PowerShow.com