Languages and Compilers (SProg og Oversættere)
description
Transcript of Languages and Compilers (SProg og Oversættere)
1
Languages and Compilers(SProg og Oversættere)
Bent ThomsenDepartment of Computer Science
Aalborg University
With acknowledgement to Mitch Neilsen whose slides this lecture is based on.
2
Language issues in client/server programming
• Communication mechanisms– RPC, Remote Objects, SOAP
• Data representation languages– XDR, ASN.1, XML
• Parsing and deparsing between internal and external representation
• Stub generation
3
The Stub Generation Process
Interface Specification
Stub Generator
ServerStub
CommonHeader
Client Stub
ClientSource
RPCLIBRARY
ServerSource
Compiler / Linker
RPCLIBRARY
ClientProgram
ServerProgram
Compiler / Linker
4
Client/server example
• The basic organization of the X Window System
• A major task of most clients is to interact with a human user and a remote server.
5
Servers: General Design Issues
a) Client-to-server binding using a daemon as in DCE
b) Client-to-server binding using a superserver as in UNIX
6
Client-Side Software for Distribution Transparency
• A possible approach to transparent replication of a remote object using a client-side solution.
7
RPC and the OSI Reference Model
Application Layer
Presentation Layer (XDR)
Session Layer (RPC)
Transport Layer (UDP)
8
Representation
• Data must be represented in a meaningful format.• Methods:
– Sender or Receiver makes right (NDR).• Network Data Representation (NDR).• Transmit architecture tag with data.
– Represent data in a canonical (or standard) form • XDR• ASN.1• Note – these are languages, but traditional DS
programmers don’t like programming languages, except C
9
XDR - eXternal Data Representation
• XDR is a universally used standard from Sun Microsystems used to represent data in a network canonical (standard) form.
• A set of conversion functions are used to encode and decode data; for example, xdr_int( ) is used to encode and decode integers.
• Conversion functions exist for all standard data types– Integers, chars, arrays, …
• For complex structures, RPCGEN can be used to generate conversion routines.
10
RPC Example
gcc
RPClibrary
-lnsl
clientclient.c
date_proc.c gcc date_svc
date.x RPCGEN
date_clnt.c
date_svc.c
date_xdr.c
date.h
11
XDR Example
#include <rpc/xdr.h>..XDR sptr; // XDR stream pointerXDR *xdrs; // Pointer to XDR stream pointerchar buf[BUFSIZE]; // Buffer to hold XDR dataxdrs = (&sptr);xdrmem_create(xdrs, buf, BUFSIZE, XDR_ENCODE);..int i = 256;xdr_int(xdrs, &i);printf(“position = %d. \n”, xdr_getpos(xdrs));
xdrs
sptr
buf
12
Abstract Syntax Notation 1 (ASN.1)
• ASN.1 is a formal language that has two features: – a notation used in documents that humans read– a compact encoded representation of the same information used in communication
protocols. • ASN.1 uses a tagged message format:
– < tag (data type), data length, data value >• Simple Network Management Protocol (SNMP) messages are encoded using ASN.1.
13
Distributed Objects
• CORBA• Java RMI• SOAP and XML
14
Distributed ObjectsProxy and Skeleton in Remote Method
Invocation
object A object BskeletonRequest
proxy for B
Reply
CommunicationRemote Remote referenceCommunication module modulereference module module
for B’s class& dispatcher
remoteclient server
15
CORBA
• Common Object Request Broker Architecture• An industry standard developed by OMG to help in distributed
programming• A specification for creating and using distributed objects• A tool for enabling multi-language, multi-platform communication• A CORBA based-system is a collection of objects that isolates the
requestors of services (clients) from the providers of services (servers) by an encapsulating interface
16
CORBA objects
They are different from typical programming objects in three ways:
• CORBA objects can run on any platform• CORBA objects can be located anywhere on the
network• CORBA objects can be written in any language that has
IDL mapping.
17
Client ClientObject Implementation Object Implementation
ORB ORB
NETWORK
IDL IDLIDL IDL
A request from a client to an Object implementation within a network
18
IDL (Interface Definition Language)
• CORBA objects have to be specified with interfaces (as with RMI) defined in a special definition language IDL.
• The IDL defines the types of objects by defining their interfaces and describes interfaces only, not implementations.
• From IDL definitions an object implementation tells its clients what operations are available and how they should be invoked.
• Some programming languages have IDL mapping (C, C++, SmallTalk, Java,Lisp)
19
IDL File
IDL Compiler
Client StubFile
ServerSkeleton File
ClientImplementation
ObjectImplementation
ORB
20
The IDL compiler
• It will accept as input an IDL file written using any text editor (fileName.idl)
• It generates the stub and the skeleton code in the target programming language (ex: Java stub and C++ skeleton)
• The stub is given to the client as a tool to describe the server functionality, the skeleton file is implemented at the server.
21
IDL Example
module katytrail { module weather { struct WeatherData { float temp; string wind_direction_and_speed; float rain_expected; float humidity; }; typedef sequence<WeatherData> WeatherDataSeq interface WeatherInfo { WeatherData get_weather( in string site ); WeatherDataSeq find_by_temp( in float temperature ); };
22
IDL Example Cont.
interface WeatherCenter { register_weather_for_site ( in string site, in WeatherData site_data ); }; };};
Both interfaces will have Object Implementations.A different type of Client will talk to each of theinterfaces.
The Object Implementations can be done in oneof two ways. Through Inheritance or througha Tie.
23
Stubs and Skeletons
• In terms of CORBA development, the stubs and skeleton files are standard in terms of their target language.
• Each file exposes the same operations specified in the IDL file.• Invoking an operation on the stub file will cause the method to be
executed in the skeleton file• The stub file allows the client to manipulate the remote object
with the same ease with each a local file is manipulated
24
Java RMI
• Overview– Supports remote invocation of Java objects– Key: Java Object Serialization
Stream objects over the wire – Language specific
• History– Goal: RPC for Java– First release in JDK 1.0.2, used in Netscape 3.01– Full support in JDK 1.1, intended for applets– JDK 1.2 added persistent reference, custom protocols, more support for
user control.
25
Java RMI
• Advantages– True object-orientation: Objects as arguments and values– Mobile behavior: Returned objects can execute on caller– Integrated security– Built-in concurrency (through Java threads)
• Disadvantages– Java only
• Advertises support for non-Java• But this is external to RMI – requires Java on both sides
26
Java RMI Components
• Base RMI classes– Extend these to get RMI functionality
• Java compiler – javac– Recognizes RMI as integral part of language
• Interface compiler – rmic– Generates stubs from class files
• RMI Registry – rmiregistry– Directory service
• RMI Run-time activation system – rmid– Supports activatable objects that run only on demand
27
RMI Implementation
Java Virtual Machine
ClientObject
Java Virtual Machine
RemoteObject
Stub Skeleton
Client Host Server Host
28
Java RMI Object Serialization
• Java can send object to be invoked at remote site– Allows objects as arguments/results
• Mechanism: Object Serialization– Object passed must inherit from serializable– Provides methods to translate object to/from byte stream
• Security issues:– Ensure object not tampered with during transmission– Solution: Class-specific serialization
Throw it on the programmer
29
Building a Java RMI Application
• Define remote interface– Extend java.rmi.Remote
• Create server code– Implements interface– Creates security manager, registers with registry
• Create client code– Define object as instance of interface– Lookup object in registry– Call object
• Compile and run– Run rmic on compiled classes to create stubs– Start registry– Run server then client
30
Java RMISample interface
import java.rmi.Remote;import java.rmi.RemoteException;public interface Hello extends Remote {String sayHello() throws RemoteException;}
31
Java RMISample Client
import java.rmi.Naming;import java.rmi.RemoteException;
public class HelloClient { public static void main(String args[]) { String message = "blank"; Hello obj = null; try { obj = (Hello)Naming.lookup("//myhost/HelloServer"); message = obj.sayHello();
System.out.println(message); } catch (Exception e) { System.out.println("HelloClient exception: " + e.getMessage()); e.printStackTrace(); } } }
32
Java RMI:Example Server
import java.rmi.Naming;import java.rmi.RemoteException;import java.rmi.RMISecurityManager;import java.rmi.server.UnicastRemoteObject;public class HelloServer extends UnicastRemoteObject implements Hello { public HelloServer() throws RemoteException { super(); } public String sayHello() { return "Hello World!"; } public static void main(String args[]) {
if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); }try { HelloServer obj = new HelloServer(); Naming.rebind("//myhost/HelloServer", obj); System.out.println("HelloServer bound in registry");} catch (Exception e) { System.out.println("HelloServer err: " + e.getMessage()); e.printStackTrace();
} } }
33
Parameter Passing
• Primitive types– call-by-value
• Remote objects– call-by-reference
• Non-remote objects– call-by-value– use Java Object Serialization
34
Java Serialization
• Writes object as a sequence of bytes• Writes it to a Stream• Recreates it on the other end• Creates a brand new object with the old data• Objects can be transmitted using any byte stream
(including sockets and TCP).
35
Codebase Property
• Stub classpaths can be confusing– 3 VMs, each with its own classpath– Server vs. Registry vs. Client
• The RMI class loader always loads stubs from the CLASSPATH first
• Next, it tries downloading classes from a web server– (but only if a security manager is in force)
• java.rmi.server.codebase specifies which web server
36
CORBA vs. RMI
• CORBA was designed for language independence whereas RMI was designed for a single language where objects run in a homogeneous environment
• CORBA interfaces are defined in IDL, while RMI interfaces are defined in Java
• CORBA objects are not garbage collected because they are language independent and they have to be consistent with languages that do not support garbage collection, on the other hand RMI objects are garbage collected automatically
37
SOAP Introduction
• SOAP is simple, light weight and text based protocol• SOAP is XML based protocol (XML encoding)• SOAP is remote procedure call protocol, not object oriented completely• SOAP can be wired with any protocol
SOAP is a simple lightweight protocol with minimum set of rules for invoking remote services using XML data representation and HTTP wire.
• Main goal of SOAP protocol – Interoperability
• SOAP does not specify any advanced distributed services.
W indow s
E-Com m erce
Unix
MainFrame
SOAP
38
Why SOAP – What’s wrong with existing distributed technologies
• Platform and vendor dependent solutions (DCOM – Windows) (CORBA – ORB vendors) (RMI – Java)
• Different data representation schemes (CDR – NDR)
• Complex client side deployment • Difficulties with firewall
Firewalls allows only specific ports ( port 80 ), but DCOM and CORBA assigns port numbers dynamically.
• In short, these distributed technologies do not communicate easily with each other because of lack of standards between them.
39
Base Technologies – HTTP and XML
• SOAP uses the existing technologies, invents no new technology.• XML and HTTP are accepted and deployed in all platforms.• Hypertext Transfer Protocol (HTTP)
– HTTP is very simple and text-based protocol.– HTTP layers request/response communication over TCP/IP. HTTP
supports fixed set of methods like GET, POST.– Client / Server interaction
• Client requests to open connection to server on default port number• Server accepts connection• Client sends a request message to the Server• Server process the request• Server sends a reply message to the client• Connection is closed
– HTTP servers are scalable, reliable and easy to administer.• SOAP can be bind any protocol – HTTP , SMTP, FTP
40
Extensible Markup Language (XML)
• XML is platform neutral data representation protocol.• HTML combines data and representation, but XML contains just
structured data. • XML contains no fixed set of tags and users can build their own
customized tags.<student>
<full_name>Bhavin Parikh</full_name><email>[email protected]</email>
</student>• XML is platform and language independent.• XML is text-based and easy to handle and it can be easily
extended.
41
Architecture diagram
Client Application(CO M clien t or C O RBA clien t or
Java RM I c lient)
W eb ServicesDescriptionLanguage
XML Parser SOAP Library
Proxy O bject
Server Application(C O M ob ject or C O RBA ob ject or
RM I O bject)
HTTP Server
SOAP Listener
SOAP Request
Calldirect
Call throughproxy
SOAP Response
SOAP = HTTP +XM L + RPCOR
SOAP = HTTPS +XM L + RPC
1. C lient call rem ote serviceusing SO AP
2. Client can use proxy object tohide all SOAP details
MappingTool
4. Mapping tool m aps SO AP request torem ote serice
3. SOAP Listener can be im plem entedas ASP, JSP, CG I or SERVLET
XML Parser
SOAP Library
42
Parsing XML Documents
• Remember: XML is just text• Simple API for XML (SAX) Parsing
– SAX is typically most efficient– No Memory Implementation!
• Left to the Developer• Document Object Model (DOM) Parsing
– “Parsing” is not fundamental emphasis.– A “DOM Object” is a representation of the XML document in
a binary tree format.
43
Parsing: Examples
• SaxParseExample– “Callback” functions to process Nodes
• DomParseExample– Use of JAXP (Java API for XML Parsing)
• Implementations can be ‘swapped’, such as replacing Apache Xerces with Sun Crimson.
– JAXP does not include some ‘advanced’ features that may be useful.
– SAX used behind the scenes to create object model
44
<bigwig>
• A domain-specific high-level programming language for developing interactive Web services.
<bigwig>
HTML
CGI Scripts
JavaScript
HTTP Auth.
Java Applets
Service Specification
45
A collection of DSLs
• C-like skeleton language with• Runtime system• Concurrency control• Database• Dynamic documents: DynDoc• Input validation language: PowerForms• Security• Cryptographic security• Syntactic-level macros
46
A Page Counter
service { session Access() { shared int counter; string name; show EnterName receive [name=name]; counter = counter + 1; show AccessDoc <[counter = counter]; }}
47
A Page Counter
if (counter == 100) { counter = 0; show Congratulations <[name = name]; } else { counter = counter + 1; show AccessDoc <[counter = counter]; }
48
PowerForms
• Domain specific language:– targeted uniquely for input validation
• Declarative nature (regexps):– abstracts away operational details
PowerFormsDeclarativeSpecification
JavaScript(subset)