Tutorial on J2EE versus .NET for .NET Programmers

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    Tutorial on J2EE versus .NET for .NET Programmers - Presentation Transcript

    1. Advanced Developers Conference 10.-11. Oktober 2004 Agenda Bemerkungen Tec 07 Motivation Comparison J2EE versus .NET • Overall Vision: Java and .NET • Layer-by-Layer comparison of the infrastructures Summary Michael Stal Siemens AG, Corporate Technology Bemerkungen Goal Some Issues This is intended to be an objective If we are going to compare .NET and comparisons of the two platforms Java, what do we mean? • Will we compare Java, the language, with C#? • Will we compare Java, the platform, with .NET, the In will contain criteria to base a decision platform? which platform to use • Will we compare the Java Virtual Machine with the CLR (Common Language Runtime)? In this talk we will try to cover most Interoperability issues aspects. The Naive Approach Bemerkungen Layer-By-Layer Comparison Hello World Example In C# and Java: using System; namespace MyNameSpace { public class MyClass { public static void Main(String [] args) { Console.WriteLine(„Hello, C#!“); } } } package MyPackage; import java.lang.*; public class MyClass { public static void Main(String [] args) { System.out.println(„Hello, Java!“); } } Dein Name – Dein Vortragstitel Pra 01 - S. 1
    2. Advanced Developers Conference 10.-11. Oktober 2004 Layers Bemerkungen is What J2EE Technology? • not just a set of APIs High Level Overview J2EE Technology Purpose Runtime System Object model Platform Specification Describes the minimum feature set of J2EE APIs and standards that vendors Base class libraries must provide Enterprise support Reference implementation Provides a compliant and operational J2EE platform - Component model - Database access J2EE Blueprints Describes how to construct J2EE applications (including JAVA Pet Store) - XML - Server Pages Compatibility Testsuite Validates J2EE platform compatibility to guarantee code portability and eliminate - Remoting vendor lock - Web Services - More Enterprise APIs Bemerkungen What is J2EE Technology? What is J2EE Technology? Java-based Multi-Tier Architectures: J2EE supports appropriate technologies for each tier J2EE is based on J2SE, which includes the following enterprise APIs: • Java IDL and RMI-IIOP • JAAS (Java Authentication and Authorization Service) • JDBC (Java Data Base Connectivity) • JNDI (Java Naming and Directory Interface) • JAXP (Java API for XML Parsing) Multi-tier Architecture Bemerkungen J2EE „standard“ Services Overview Servlets Java Server Pages Java RMI-IIOP and RMI-JRMP JavaIDL JNDI (Java Naming and Directory Interface) JMS (Java Message Service) Java Authentication and Authorization Service (JAAS) Enterprise JAVA Beans JDBC (Java Data Base Connectivity) J2EE Connector Architecture Java Transaction API JavaMail and JAF Java API for XML Parsing Of course I cannot cover them all. Dein Name – Dein Vortragstitel Pra 01 - S. 2
    3. Advanced Developers Conference 10.-11. Oktober 2004 The .NET Framework Class The Runtime System Bemerkungen Library In .NET we distinguish between .NET Framework and .NET CF CLR System.Web System.Windows.Forms Services UI Design ComponentModel Description HtmlControls Base Class Library Support Discovery WebControls Protocols System.Drawing Thread Support COM Marshaler Caching Security Drawing2D Printing Type Checker Exception Manager Configuration SessionState Imaging Text System.Data System.Xml Security Engine Debug Engine ADO SQL XSLT Serialization Design SQLTypes XPath IL to Native Code Garbage Compilers Manager Collector System Collections IO Security Runtime InteropServices Configuration Net ServiceProcess Class Loader Remoting Diagnostics Reflection Text Serialization Globalization Resources Threading Bemerkungen Java Virtual Machine .NET Runtime It is called the Common Language Runtime (CLR) The JVM targets Java and interprets Java Byte Code. It supports all languages compiled for the MSIL Other languages can also be compiled to Java bytecode (e.g. Provides integration for several languages Ada) Provides support for non-OO languages (e.g. tail Just-in-Time compilers exist for different environments and recursion) OSs C# Compiler Compiler VB.NET CLASS- Java Classloader/ MSIL + JIT Loader/ Files Verifier JIT Metadata Verifier C++‘ Garbage Garbage Native Interpreter Managed Collection, Collection, Execution Code Perl Security Manager Security, Code Call-in+Call-out, Multithreading, Multithreading, Hotspot ... ... Differences and Bemerkungen The Object Model Commonalities Commonalities: • Basic infratructure is similar Differences: • Java is intended for interpretation (e.g. type- dependent primitives i_add, ...) • Java allows for custom class loaders and security managers • .NET is optimized for compilation and is thus sometimes faster • .NET CLR provides a command set that also supports functional languages Dein Name – Dein Vortragstitel Pra 01 - S. 3
    4. Advanced Developers Conference 10.-11. Oktober 2004 Object Model (Java) java.lang.Object Bemerkungen Java has primitive types and classes. Base of all Java classes • No automatic boxing/unboxing public class Object { public Object(); public boolean equals(Object obj); Types public final Class getClass(); public int hashCode(); Primitive Types Reference Types public final void notify(); public final void notifyAll(); Arrays Interfaces public String toString(); public final void wait() throws InterruptedException; Classes public final void wait(long timeout) throws InterruptedException; public final void wait(long timeout, int nanos) throws InterruptedException; protected Object clone() throws ClineNotSupportedException; protected void finalize() throws Throwable; } Bemerkungen Object Model (Java) Object Model (.NET) Primitive types cannot be transparently In .NET, everything is a class used as an object. Special Holder classes are necessary. Types Integer i_ref = new Integer (7); Value Types Reference Types List l = ... Pointers Interfaces l.add( i_ref ); System Value User Value Self-describing Types Types There are no special function references. Types Java uses Observer Pattern with Enumerations Classes Arrays callback interfaces and inner classes Delegates Boxed Values User-Defined Bemerkungen System.Object Object Model (.NET) .NET distinguishes between values types The „mother of all .NET classes“ and reference types: public class Object { • value types reside on the stack public virtual int GetHashCode(); • reference types reside on the heap public virtual bool Equals(); public virtual String ToString(); There is no difference between primitive public static bool Equals(object a, object b); types and classes public static bool ReferenceEquals(object a, • Automatic boxing/unboxing provides transparency object b); public Type GetType(); Special strongly-typed function protected object MemberWiseClone(); references protected virtual Finalize()´; • called delegates } • and events Dein Name – Dein Vortragstitel Pra 01 - S. 4
    5. Advanced Developers Conference 10.-11. Oktober 2004 .NET-Types that are not .NET-Types that are not Bemerkungen available in Java available in Java (cont‘d) Delegates & Events: Enumerations (value type): class Sub { enum Color : byte { RED = 1, BLUE = 2, GREEN = 3 }; public void somebodyTurnedOnTheLight( int which ) { Jagged (arrays of arrays) and unjagged // do something useful } Arrays: public Sub(Pub thePub) { thePub.OnLightTurnedOn += new Pub.LightTurnedOn(somebodyTurnedOnTheLight); int [2][] a; a[0] = new int[]{1}; a[1] = new int[]{1,2}; } // ... int [,] a = new int[2,2]; } Structs (value types): class Pub { public delegate void LightTurnedOn(int ID); • Structs are implicitly sealed: public event LightTurnedOn OnLightTurnedOn; public struct not support inheritance • they do String First; Name { public void SomeoneTurnsOntheLight() { public OnLightTurnedOn(myID); public String Last; } // ... } } Commonalities and Bemerkungen Metainformation Differences Commonalities: Java and .NET provide a reflection API • Interfaces are „completely abstract classes“ • to load, execute, and instantiate classes • Both support single inheritance for classes (implementation inheritance) and multiple interface inheritance • and inspect classes (introspection). • Default-Initialization of variables • Namespace-Concept (Java-Package and .NET-Namespace) • Similar visibility attributes (public, private, ...) In addition, .NET allows to annotate • Generic types in .NET and Java (Generics) but .NET Generics much more flexible and available as runtime entities many aspects of a system (classes, • Class constructors (static initializers in Java) Differences: members, operations) with Attributes • In .NET there is no difference between primitive types and classes. Boxing to map between value and reference types. Autoboxing now also available in Java. • Multiple language support in .NET • In Java all methods are implicitly virtual. In .NET this is explicitely specified (virtual, override, new). • Java maps packages to directories. .NET doesn‘t. Bemerkungen Java Example .NET Examples Accessing and using Type information: Using an Atttribute • Note that packages and namespaces are different [AuthorIs(„Michael“)] issues!! class MyClass { ... } • There are several predefined attributes import java.lang.reflect.*; (WebService, WebMethod, ...) try { Class c = Class.forName(„MyPrintComponent“); Object o = c.newInstance(); Defining an Attribute Method m = c.getMethod(„print“, new Class[]{ String.class }); m.invoke(o, new Object[]{„Hallo, Java!“}); [AttributeUsage(AttributeTargets.All] } public class AuthorIsAttribute : Attribute { catch (Exception e) { private string m_Name; // handle it here } public AuthorIsAttribute(string name) { m_Name = name;} } Dein Name – Dein Vortragstitel Pra 01 - S. 5
    6. Advanced Developers Conference 10.-11. Oktober 2004 Commonalities and .NET Example (cont‘d) Bemerkungen Differences Accessing and using Type information Commonalities: • Very similar APIs using System; using System.Reflection; Differences: namespace ComponentClient { • .NET allows additional, user-defined meta class Client { information with attributes. This will also be static void Main(string[] args) { possible in Java using a similar approach. Assembly a = Assembly.LoadFrom(\"Component.dll\"); Type [] allTypes = a.GetTypes(); • Java Reflection is sometimes a bit more clumsy Type t = allTypes[0]; (because of primitive types and classes) object o = Activator.CreateInstance(t); MethodInfo mi = t.GetMethod(\"algorithm\"); • .NET allows to actually create new artifacts at double d = (double) mi.Invoke(o, new object[]{21.0}); runtime and instantiate them or store them in } } assemblies. } Bemerkungen Statements Exceptions Both platforms support basically the Exceptions in Java same language features • Exceptions have to be declared in the throws-clause. Checked versus unchecked exceptions Some Differences: public int insert(int i) throws OverLimitException; • switch-Statement allows Strings, and prevents {…} fallthrough. • Different iterators: foreach(et in ct) to iterate container in .NET versus Exceptions in .NET for (ElementType: ContainerType) in Java. • Exceptions are not declared • Indexers, Operators not available in Java. // only way to tell you about • Properties in Java are handled by coding // OverLimitException thrown below conventions (set, get). public int insert(int i) { … } Bemerkungen Multithreading Multithreading in Java In Java there is a class „Thread“ and an interface Runnable For synchronisation we have to use the keyword synchronized class GlobalData { int m_Value; public synchronized int setValue { return m_Value; } } class Worker implements Runnable { GlobalData m_Global; public Worker(GlobalData global) { m_Global = global; } public void run() { m_Global.setValue(42); Thread.sleep(100); } } // somewhere else: GlobalData g = new GlobalData(); Thread t = new Thread(new Worker()); t.start(); t.join(); 1 Dein Name – Dein Vortragstitel Pra 01 - S. 6
    7. Advanced Developers Conference 10.-11. Oktober 2004 Commonalities and Multithreading in .NET Bemerkungen Differences .NET uses delegates for multithreading Commonalities: • The „ThreadStart“ in the example below • Threading is very similar! There are monitors for synchronization Differences: • The “lock” in the example below • In Java, synchronization is better integrated into the language. Different design philosophies class GlobalData { • Java provides better synchronization and thread int m_Value; communication (wait, notify, ...). public int Value { set { lock(this) { m_Value = value; } } } } • In .NET it is much easier to create a thread from class Worker { any method. Only precondition: method with no GlobalData m_Global; public Worker(GlobalData global) {m_Global = global; } result and no arguments. public void loop() { m_global.Value = 42; Thread.Sleep(100); } } // somewhere else: GlobalData g = new GlobalData(); Thread t = new Thread(new ThreadStart(new Worker().loop)); t.Start(); t.Join(); 1 Bemerkungen Component Models Java .jar files are similar to .NET‘s assemblies • They can be shared or private • They can be signed They contain • types • resources • optionally, metadata in manifest files. There is no versioning and jar-files are just pre-deployment-time entities! Bemerkungen Java Component Models Server Components in Java Enterprise JavaBeans (EJBs) always Client Components and Server reside in a container that hides technical Components aspects (sep. of concerns) JavaBeans are Client Components JNDI Naming • normal Java classes following some conventions Deployment Service Descriptor 1) lookup home • optionally providing metainformation (BeanInfo EJB class) EJB Context EJB Home 2) create bean Jar 2”) find bean Remote Bean Home Interface public class MyJavaBean { new 4 Client private int color; EnterpriseBean public void setColor(int v) { color = v; } ejbCreate Bean EJB ejb... Instance 4) remove Object public int getColor() { return color; } bean-methods 3) Use bean Remote Bean // a lot of more ... Interface } EJB Run-time Application Server (Container) // BeanInfo class not shown here! Dein Name – Dein Vortragstitel Pra 01 - S. 7
    8. Advanced Developers Conference 10.-11. Oktober 2004 Server Components in Java OSGi Bemerkungen cont‘d Additional Frameworks for small evices are available 4 Types of Beans such as OSGi, Pico, or Spring. • Stateless Session-Beans (Service Components) OSGi Framework: a general-purpose, secure, managed • Stateful Session Beans (Session Components) Java execution environment that supports the deployment • Entity-Beans (Entity Components) of extensible and downloadable service applications called bundles. • Message-Driven Beans (asynch. Service Components) Bundle: a software component plugged into the framework that provides some functionality to an end-device such as a gas meter. An EJB bean is in theory portable across Service: a Java object implementing a concisely defined containers (Application Servers) from interface. Installed bundles can register a number of different vendors. services that can be shared with other bundles under strict control of the framework. OSGi Architecture Bemerkungen .NET Component=Assembly=Set of Types • Note that this notion of a name Sharedname Files Types Manifest component is Referenced version Hash Security Assemblies Custom Product Attributes Information very different Type 1 Metadata from that used IL-Code Type 2 with EJB or Module 1 IL-Code Type 3 COM+ IL-Code Resources Bemerkungen Server-Side Components Component Model in .NET Now Component is used like in EJB Private Assemblies are typically only useful by the owning application To use container-provided services like Shared Assemblies are stored in a global synchronisation or transactions COM+ assembly cache and can be used by services can be used several applications. COM+-Interop provides these features. • They are signed by a key • They are versioned!! Runtime uses Application Domains as an abstraction for isolated appartments within a process. Dein Name – Dein Vortragstitel Pra 01 - S. 8
    9. Advanced Developers Conference 10.-11. Oktober 2004 Using COM Components in COM Callable Wrapper Bemerkungen .NET For a COM.DLL it is possible to create a .NET creates a CCW for exporting .NET RCW (Runtime Callable Wrapper). classes as COM servers: This is a wrapper to access COM components (with typelibs) from .NET: COM CCW .NET COM .NET Client Wrapper Component .NET RCW COM .NET COM Client Wrapper Component Future of Distributed .NET: Bemerkungen Indigo Architecture Indigo Messaging Services Service Model Indigo (part of Longhorn) provides common Queuing framework for connected systems (SOA) Declarative Transacted Instance Context Service Type Integration Behaviors Methods Manager Manager Methods • Integrates Web services, .NET Remoting, MSMQ Routing • Extensible Architecture Communication Eventing • Vertical functionality such as security integrated in Indigo Policy Channels Engine (Datagram, Reliable, Peer, …) Service layer completely decoupled from Channel … Security protocol layer. Transport Channels Message (IPC, HTTP, TCP…) For more details browse to Encoder System Services http://msdn.microsoft.com/Longhorn/underst Transaction Communications Manager (Port) anding/pillars/Indigo/default.aspx Federation Hosting Environments ASP.NET .container .exe NT Service DllHost … Ports, Channels, Services, Bemerkungen Indigo Connectors And Messages A Connector is based upon 4 entities: • Messages are in-memory envelopes (SOAP) Service • Services are the targets of messages Port Channel • Ports are representations of network addresses Service • Channels allow sending or receiving through ports Message Applications rely on these concepts Channel directly or indirectly Service Service Channel Dein Name – Dein Vortragstitel Pra 01 - S. 9
    10. Advanced Developers Conference 10.-11. Oktober 2004 Ports And Channels Port/Channel Architecture Bemerkungen A port is a location in network space • Resides in a single AppDomain Service Service • Has one or more affiliated transport channels • Provides a base URI for all addresses Messages flow through a port Port B Port A via channels • Channels impose a message exchange pattern Transport • Channels may add additional processing code Channels Channels Extensions Extensions Bemerkungen Services And Addresses Hosting ServiceReferences are used to identify Services can be self-hosted or activated on message recipients demand via ASP.NET • Absolute URI of service + fixed headers “Indigo” shares activation with ASP.NET • Fully interoperable • Process/AppDomain Startup/Shutdown/Cycle • ServiceAddress is relative version • Health monitoring “Indigo” uses the IService interface to • Management model message recipients URI namespace partitioning relies • Maps ServiceAddress to in-memory object on metabase • Independent of transport (HTTP, TCP, etc.) Bemerkungen On-Demand Activation Services In Action Service Client Admin Cmd line tools Service Mgmt APIs MMC Plugins Service Tools (adsutil, etc) Model Send() Receive() Model Extensions Extensions Proxy Session Process Management W3SVC Metabase Components Port B Port A http.sys TcpListener Mail Listener IPC Listener Listeners Transport Channels Channels Extensions Extensions Dein Name – Dein Vortragstitel Pra 01 - S. 10
    11. Advanced Developers Conference 10.-11. Oktober 2004 [Service] [RemoteObject] Bemerkungen Service-Oriented Object-Oriented [Service] [RemoteObject] public class Hello public class RemObj : MarshalByRefObject Programming Model Programming Model { { [ServiceMethod] public RemObj() { Opt-In Contract Contract based on private string Greeting(string name) Console.WriteLine( public visibility Schema-based { \"Object {0} has been created.\", return String.Format(\"Hello, {0}!\", name); this.GetHashCode().ToString()); integration DLL-based integration } } Broad interop No Interop public string Salutation (string name) public string Hello(string name) { { return Like .NET Remoting, return String.Format(“Howdy, {0}!”, name); String.Format(\"Hello, {0}!”, name); CLR-focused } } } ~RemObj() { Console.WriteLine( \"Object {0} is being torn down.\", this.GetHashCode().ToString()); } } Commonalities and Bemerkungen Database Access in Java Differences Commonalities: Java provides JDBC to access relational • Assemblies and JAR files provide „deployment“ components data • Server Components are available (Assemblies + COM+, EJB). Available component types in COM+ restricted Application • Interop with legacy components in .NET using COM+, in Java using CORBA) Statement Differences: Prepared • EJB are a more mature and proven model Resultset Connection Driver Manager Statement • Special APIs in J2EE to connect to legacy systems (Java Callable JDBC/ Connector Architecture) Statement ODBC Bridge • Much better versioning support in .NET (side-by-side ODBC Driver execution) • Future Outlook: Indigo will provide SOA container, EJB 3.0 will introuce the POJO approach to simplify development ODBC DB Bemerkungen Java Example Database Access in Java There are several other APIs: import java.sql.*; // without error handling: • Embedded SQL with SQLJ (uses JDBC internally) Class.forName(„sun.jdbc.odbc.JdbcOdbcDriver“); • Proprietary ODBMS APIs Connection con=DriverManager.getConnection(„jdbc:odbc:stocks,““,““); • Standardized JDO API to provide (more or less Statement stmt = con.CreateStatement(); transparent) persistence for Java Objects ResultSet rs = stmt.executeQuery(„SELECT * from stocks“); • XML is handled differently! while (rs.next()) { System.out.println(rs.getString(„COMPANYNAME“)); • Java Connector API provides access to other } „connection oriented“ legacy systems (such as SAP rs.close(); R3) stmt.close(); con.close(); Dein Name – Dein Vortragstitel Pra 01 - S. 11
    12. Advanced Developers Conference 10.-11. Oktober 2004 Database Access in .NET ADO.NET Bemerkungen In .NET there is ADO.NET ADO.NET is XML based (XML Infoset) • DataSet dnymically builds an XML schema inside to store the • “connectionless” Client data • Relational data and XML data can be handled in a similar way!! DataSet ADO.NET works offline once the data is fetched • Updating is partly automatic using DataSets Command DataSetCommand DataReader Currently there are three Managed Providers: • SQL Server • ADO Connection Managed Provider • Oracle Data Source Commonalities and Bemerkungen XML Differences Commonalities: • Decoupling of the concrete data model and the user (using DataSets and ResultSets) Differences: • ADO.NET uses XML extensively, JDBC has a more relational flavor (like ADO) • JDBC is mainly connection oriented, ADO.NET always works non-connected, or offline • .NET DataSets are a kind of In-Memory-Database- Cache. • In Java additional O/R solutions such as JDO or SQLJ without .NET counterpart. Bemerkungen XML und Java XML and .NET There are several tools available .NET is very XML-centric • DOM, SAX • Web Services (SOAP) • Xerces/Xalan, JDOM • JAX{M,B,R,RPC} • Configuration Files • Castor • Result sets of a database access (ADO.NET) However, Java‘s libraries have not beed designed • XML processing itself with XML as a basis (Java‘s too old ☺) JAXP (Java API for XML Parsing) supports DOM and SAX). Note that formally, many .NET features Currently under development are based on the XML infoset („XML • JAXM (Java API for XML Messaging) semantics“) and do not necessarily • JAXB (Java API for XML Data Binding) • JAXR (Java API for XML Registries) require megabytes of text data!! • JAX/RPC (Java API for XML based RPC) Dein Name – Dein Vortragstitel Pra 01 - S. 12
    13. Advanced Developers Conference 10.-11. Oktober 2004 XML and .NET (cont‘d) Remoting Bemerkungen The System.Xml Namespace provides a whole lot of classes • DOM processing using XmlNode & Sons • XPath and XslTransform • XmlTextReader und XmlTextWriter similar to SAX, but using a Pull-Modell (Stream-Based) • Schema support Two approaches: one that is closer to the programmer‘s object model and another one that is closer to the DOM. Bemerkungen Remoting in Java Some Facts about RMI Several possibilities: RMI/CORBA/SOAP Registry tool as naming service, started manually or automatically. • RMI can use JRMP or IIOP as a transport protocol On demand activation possible. • Not easily pluggable – changes in the code are necessary Changing lease time for DGC possible (leasing time = time without connection). Client Server Usage of RMISecurityManager to allow class loading across computer boundaries. Stub Stub/Skeleton-Layer Skeleton Object by value out-of-the-box. Other protocols by imlementing proprietary Remote Reference Manager Socket factories. Transport Layer Bemerkungen Example Example (cont‘d) Exeptions and interface definitions Implementation of remote object: import java.rmi.*; // file: BoundaryException.java import java.rmi.server.*; public class BoundaryException extends Exception {} // file: Grid.java public class GridImpl extends UnicastRemoteObject implements Grid { Object[][] values; final import java.rmi.*; static int ROWS = 20; final static int COLS = 20; public GridImpl() throws RemoteException { values = new Object[ROWS][COLS]; public interface Grid extends Remote { } public void setValue(int row, int col, Object val) public boolean isOutOfBoundaries(int r, int c) { if ((r < 0) || (r >= ROWS) || (c < 0) || (c >= COLS)) throws RemoteException, BoundaryException; return true; public Object getValue(int row, int col) else return false; } throws RemoteException, BoundaryException; public Object getValue(int row, int col) public int getColumns() throws RemoteException, BoundaryException { throws RemoteException; if (isOutOfBoundaries(row, col)) throw new BoundaryException(); else return values[row][col]; public int getRows() } throws RemoteException; ... } } Dein Name – Dein Vortragstitel Pra 01 - S. 13
    14. Advanced Developers Conference 10.-11. Oktober 2004 Example (cont‘d) Example (cont‘d) Bemerkungen The Server Main Client import java.rmi.*; import java.rmi.registry.*; import java.rmi.*; import java.rmi.server.*; public class GridClient { public static void main(String args[]) { public class GridServer { try { Grid g = (Grid)Naming.lookup(\"grid\"); public static void main(String args[]) throws g.setValue(4,4, new Integer(42)); Exception { Integer i = (Integer) g.getValue(4,4); System.out.println(i); GridImpl svr = new GridImpl(); g.setValue(33,33, new Integer(88)); Naming.rebind(\"grid\", svr); } System.out.println(\"ready\"); catch (BoundaryException b) { System.out.println(\"Boundary violation\"); } } } catch (Exception e) { System.out.println(e); } } } Bemerkungen Remoting in .NET Remoting in .NET (cont‘d) .NET Remoting provides pluggable transports and formatters Application Domain A Application Domain B • currently TCP and HTTP transport and • binary and SOAP formatters Client Servant Contexts are automatically propagated (very neat feature!!) Only very simple lifecycle management Transparent Proxy Object Context Sinks options for servants (compared to EJB or Real Proxy Server Context Sinks Envoy Sinks CORBA) Channels Channels Network • Singleton (one object for all calls) Formatters Formatters • SingleCall (new instance for each call) • Client-Activated based on leases Commonalities and Bemerkungen Web Differences Commonalities: • Relatively easy to use Differences: • .NET Remoting can be extended more flexibly • Java provides interoperability with CORBA • Asynchronous invocations not directly supported by Java • No activation mechanism provided in .NET Remoting Dein Name – Dein Vortragstitel Pra 01 - S. 14
    15. Advanced Developers Conference 10.-11. Oktober 2004 Java Server Pages and Java Example Bemerkungen Servlets Java allows for server-side scripting • JSPs are based on Servlets Other (1) get a.jsp (2) process Components Web JSP Client Server (5) HTTP file (3) gen. Servlet Servlet Impl. (4) result Servlet Database JVM Complementary Technologies Bemerkungen Java Example in Java Bean and JSP: Servlets are server-side extensions providing functionality. Implemented by Servlet Engine. // Datei MyPerson.java JSPs (Java Server Pages) are scripted Web package MyPackage; pages transformed to servlets. import java.lang.*; Taglibs allow to integrate additional html/xml- public class MyPerson { ike tags. public String getFirstName() { return \"Michael\"; } public String getLastName() { return \"Stal\"; } Java ServerFaces use taglibs to provide Web } components. // Datei MyTest.jsp: <HTML> <BODY> Apache Struts provides a framework for <jsp:useBean id=\"person\" scope=\"session\" implementing MVC applications. class=\"MyPackage.MyPerson\"/> Your name is: <br> <jsp:getProperty name=\"person\" property=\"firstName\"/> <br> <jsp:getProperty name=\"person\" property=\"lastName\"/> </BODY> </HTML> ASP.NET Bemerkungen ASP.NET Example (Server-Side Scripting) ASP.NET Architecture: A simple login screen: Other IIS 5 (1) get a.apx (2) process .NET Assemblies Web Client Assembly Server (4) HTTP file .NET Engine (3) result Database Dein Name – Dein Vortragstitel Pra 01 - S. 15
    16. Advanced Developers Conference 10.-11. Oktober 2004 ASP.NET Example (cont‘d) ASP.NET Example (cont‘d) Bemerkungen <%@ Page language=\"c#\" Codebehind=\"WebForm1.aspx.cs\" // lot of details omitted AutoEventWireup=\"false\" Inherits=\"LoginPage.WebForm1\" %> namespace LoginPage { <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" > public class WebForm1 : System.Web.UI.Page { <HTML> protected TextBox PasswordText, LoginText; <body> protected Button EnterButton; <form id=\"Form1\" method=\"post\" runat=\"server\"> protected Label MessageLabel; <asp:Label id=\"TitleLabel\" runat=\"server\">Please specify your name and private void InitializeComponent() { password</asp:Label> <br> this.EnterButton.Click += <asp:Label id=\"LoginLabel\" runat=\"server\">Login</asp:Label> <br> new System.EventHandler(this.EnterButton_Click); <asp:TextBox id=\"LoginText\" runat=\"server\"></asp:TextBox> this.Load += new System.EventHandler(this.Page_Load); <asp:RequiredFieldValidator id=\"RequiredFieldValidator\" runat=\"server\" } ErrorMessage=\"You need to specify your name\" private void EnterButton_Click(object sender, System.EventArgs e) { ControlToValidate=\"LoginText\"></asp:RequiredFieldValidator> <br> if (!(LoginText.Text.Equals(\"aladdin\") && <asp:Label id=\"PasswordLabel\" runat=\"server\">Password</asp:Label> <br> PasswordText.Text.Equals(\"sesam\"))) { <asp:TextBox id=\"PasswordText\" runat=\"server\" MessageLabel.Text = \" Wrong name or password!\"; TextMode=\"Password\"></asp:TextBox> <br> } <asp:Button id=\"EnterButton\" runat=\"server\" Text=\"Open the entrance\" else { ToolTip=\"Press this after you have specified login and Session[\"user\"] = \"aladdin\"; password\"></asp:Button> <br> Response.Redirect(\"UserArea.aspx\"); <asp:Label id=\"MessageText\" runat=\"server\"></asp:Label> } </form> } </body> } </HTML> } Commonalities and Bemerkungen XML Web Services Differences Commonalities: • Pages are precompiled to accelerate access • Similar syntax and concepts • ASP.NET provides „GUI components“ using Webcontrols, Java provides Taglibs. .. why today‘s Web does not solve all the Differences: problems. • All .NET languages can be used for ASP.NET scripting • Servlets/JSP are available for a wide range of webservers • Many open source implementations, frameworks and tools for Java Why do we care about Service-Oriented Bemerkungen Services Architectures and Web Services What is a service? Cannot take single-vendor approach to IT • A remotely accessible self-contained piece of coarse-grained (because of risk, pricing, etc.) software functionality with at least one unique physical address to which a service consumer can bind using a communication • Embracing heterogeneity protocol supported. • A service exports functionality using standardized service Interoperability is the only viable and interfaces. There might be multiple service interfaces denoting economic approach different types of business functionality or different types of communication protocols. Accelerating change in IT due to globalization, • Services are implementation agnostic in that the implementation technology used (container, programming language, middleware, e-business, etc. underlying server infrastructure) is not made visible. • Services are singletons. In contrast to CORBA, DCOM, RMI there Service-Oriented Architectures/Web Services are no instances. have ubiquitous support of all major vendors • Services are defined using a high level description language (XML) Standardization Dein Name – Dein Vortragstitel Pra 01 - S. 16
    17. Advanced Developers Conference 10.-11. Oktober 2004 Service-Oriented Loosely Coupled Bemerkungen Architectures The central paradigm when using Service-oriented Architecture Basic concepts: as a principle and paradigm is loose coupling. • Self-contained services. Loosely Coupled means (see Doug Kaye‘s book „Loosely Coupled • Messages exchanged between providers and consumers. – The Missing Pieces of Web Services“): • Brokers/Mediators where services are registered and located. • All interactions are basically asynchronous on the transport level. Higher A Broker in this scenario isn‘t necessarily an ORB! It might be a abstraction layers might be introduced to support synchronous communication. directory service or a P2P discovery mechanism. • Messaging Style is Document, not RPC. Components/Containers are often used for the implementation of • Message Paths are routed, not hard-coded. services! • Technology must support heterogeneity (interface is standardized, not code). Service • Data Types are technology independent. Repository • Syntactic Definition using a schema. Contract defines structure (what Enter service documents are exchanged) and behavior (e.g., order and rules of document exchange, QoS). • Binding is delayed, not fixed and early. BROKER search register • Semantic Adaptation by transformation, not re-coding (e.g. use intermediaries for currency calculations). • Objective: More on broad applicability than on re-use or efficiency. SERVICE SERVICE PROVIDER CONSUMER consume SOA: Message Passing Web Services as Middleware Solution: Bemerkungen Paradigm The Web is the Computer Under the hood each communication in a SOA is based upon asynchronous message Message Message exchanges: Broker 1 exchange exchange * 1 Client-side Proxy * Server-side Proxy register_server marshal marshal find_server unmarshal unmarshal Peer 1 Peer 2 establish_commu receive_result dispatch nication service(proxy) receive_request * * calls Any other communication style / semantics calls can be provided using message passing, e.g.: 1 1 • Request/Response (use correlation info to associate Client Service messages) call_service_p start_up start_task main_loop • Multicast: Send same message to different peers service(impl.) • ... Bemerkungen Dynamics How to implement this Client Service Client Proxy Broker Server Proxy paradigm register_service method find_service (proxy) server descr. marshal receive_request unmarshal Request Message dispatch method (impl.) result marshal receive_result Response unmarshal Message result Between the proxies both a message exchange format and a transport protocol are required Dein Name – Dein Vortragstitel Pra 01 - S. 17
    18. Advanced Developers Conference 10.-11. Oktober 2004 Step 1: Define a Transport Marshalling Flavors Bemerkungen Protocol SOAP bodies can be formatted A protocol defines syntax, semantics and order of • RPC style: method name and parameter names messages exchanged are mapped to XML elements with same names between peers. • Document Style: XSD Schema is used instead. For a Web-based transport Web service can carry any document. protocol we need: • HTTP and other Internet Protocols Options for parameter encoding: as transport layer. • a self-describing data • Literal: Encoding using XML Schema representation format using XML. • Encoded: Encoding using SOAP Each request and each response is wrapped as a XML Conforming to the standard toolkits message and transfered over should use Document Style and Literal the wire. SOAP formerly known as Simple Object Access Protocol. Step 2: Define a Service Bemerkungen Why is SOAP important? Description Language SOAP defines a transport protocol based upon XML and HTTP (or other protocols). Leveraging HTTP helps clients and servers to circumvent firewalls. Using SOAP, web servers can be extended to full blown Broker architectures. SOAP can bridge disparate infrastructures and applications. Step 3: Define a global Bemerkungen WSDL Elements Service Directory UDDI is a Port global registry Instead of using UDDI we Publisher API • Concrete net address Registration might also use other central UDDI of Web Service (incl. possible at any registries, hard coded URLs, URL and port) node Inquiry API or P2P discovery mechanisms Service Registrations • Collection of ports replicated at 1. search for web service • Physical location of daily basis 2. return service URL end point Common SOAP Description Message protocol used of Web Service (WSDL) • Format for single 3. read service description transfer • Request and Reponse are separate messages PortType 5. forward request 4. send request using to service • Logical grouping of SOAP over HTTP Web Server Client messages to operations Web Service 7. send result using Binding SOAP over HTTP 6. return result • Maps PortType to implementation (e.g., SOAP) C i f f Dein Name – Dein Vortragstitel Pra 01 - S. 18
    19. Advanced Developers Conference 10.-11. Oktober 2004 Step 4: All you need are SOAP+WSDL+UDDI is not Bemerkungen Generators sufficient Introduce tools that generate glue for connecting you with the Web ORB, i.e., • Client Proxies for connecting the client with services. • Server Proxies for seamless service deployment. Client Proxy WSDL Server Proxy Source: IBM WS Implementations and Bemerkungen Web Services in Java Complementary Technologies Tools: Java (J2EE 1.4) provides a Web Service API for Java: JAX-RPC is the • .NET: ASP.NET WebServices (will be integrated in Indigo), WSE (Web Services Enhancements) includes Attachments, Currently there are different solutions Security, ... • Some specific SOAP toolkits: • J2EE: JAX-RPC which is implemented by many vendors such - Apache Axis as Apache Axis, WS is part of EJB 2.1 (Enterprise JavaBeans) • MS-SOAP for COM - IBM Web Services Toolkit • All major IDEs support WS such as IBM, Microsoft, BEA, - GLUE Borland, ... • Some integrated with the major application servers Complementary Technologies: - Silverstream • P2P (Peer-to-Peer Computing): Use discovery instead of - IONA central repository - Weblogic • Grid Computing: Sharing common resources on a network - ... Bemerkungen GLUE There are a lot of different solutions for Java. Case Study: Web Services One typical example is GLUE from „The MIND Electric“. in Java using GLUE GLUE allows to implement Web services in Java. It provide its own little HTTP server and can integrate EJB, JMS, ... Dein Name – Dein Vortragstitel Pra 01 - S. 19
    20. Advanced Developers Conference 10.-11. Oktober 2004 GLUE (cont‘d) GLUE Example (1) Bemerkungen It also enables to parse WSDL files and Provide an interface IHello.java: generate proxies. Interoperates with most vendors such import java.*; as .NET or IBM WSTK. Offers both command line tools and public interface IHello { JBuilder support. public String echo(String input); public String hello(); } Bemerkungen GLUE Example (2) GLUE Example (3) Implement the interface in Hello.java: Implement main (HelloMain.java): import electric.registry.Registry; import java.*; import electric.server.http.HTTP; public class HelloMain { public static void main( String[] args ) // throws Exception { public class Hello implements IHello { try { // start a web server on port 8004 public String hello() { HTTP.startup( \"http://localhost:8004/glue\" ); return \"Hello, here is GLUE\"; // publish an instance of Exchange Registry.publish( \"hello\", new Hello() ); } } public String echo(String input) { catch(Exception e) { e.printStackTrace(); return input; } } } } } Bemerkungen GLUE Example (4) GLUE Example (5) Now start server // calling it: IHello svc = new IHelloHelper().bind(); Using a web service is also simple: String res = svc.echo(„Hello“); • Use wsdl2java to generate a proxy implementation. • Instantiate and invoke it from your client application. • GLUE also provides tools such as java2wsdl. Dein Name – Dein Vortragstitel Pra 01 - S. 20
    21. Advanced Developers Conference 10.-11. Oktober 2004 Web Services in .NET Datatypes supported Bemerkungen .NET provides a very comfortable and String Char Byte well-integrated way to build them: Boolean Int16 Int32 namespace WebService1 { public class Service1 : System.Web.Services.WebService { Int64 UInt16 UInt32 // lot of stuff omitted [WebMethod] UInt64 Single Double public double DM_to_Euro(double value) { return value / 1.95583; Guid Decimal DateTime } [WebMethod] public double Euro_to_DM(double value) { XMLQualifiedName class struct return value * 1.95583; } XmlNode DataSet } } Commonalities and Bemerkungen Using Web Services Differences Using it is also simple Commonalities: • Some steps have been omitted • Both .NET and Java strive for conformance to existing standards (SOAP, WSDL, UDDI). localhost.Service1 s1 = new localhost.Service1(); double result = s1.Euro_to_DM(200); • „Look & Feel“ very similar: WSDL-based parsers that generate proxies. Asynchronous „Style“: Differences: • For Java there is a whole bunch of available localhost.Service1 s1 = new localhost.Service1(); solutions. IAsyncResult ar = s1.BeginEuro_to_DM(200, null, null); While (!ar.IsCompleted) { Additional remark: // enjoy your coffee • Standards are open to interpretation. Thus, } double result = s1.EndEuro_to_DM(ar); interoperability doesn‘t come for free. Bemerkungen More Enterprise APIs Enterprise APIs Naming: • JNDI in Java (as an interface to CORBANaming, LDAP, ...) • Active Directory in .NET (Windows-specific) Message-oriented Middleware: • JMS in Java (JAXM is on the horizon) • .NET can use MSMQ. Dein Name – Dein Vortragstitel Pra 01 - S. 21
    22. Advanced Developers Conference 10.-11. Oktober 2004 JMS – Messaging in Java Example Bemerkungen JMS is an API to integrate existing MOM Here is an example scenario for solutions (JMS Providers). Queuing: Point to Point approaches are supported as well as Publish/Subscribe (Message Listeners). Queues (~ mailbox) and Topics (~ newsgroup). Different kinds of message bodies are provided: stream, text, serialized object, bytes, Session map. Session myQueue Sender Receiver Connection Connection Session Session Session Bemerkungen Example (cont‘d) Example (cont‘d) Here is a sample peer-to-peer client: ... sample continued ... // Establish a session: QueueSession session // First, we need a Connection Factory: = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueConnectionFactory factory; // Get a QueueSender to send messages using <queue>: Context msg = new InitialContext(); // JNDI lookup QueueSender sender = session.createSender(queue); factory = (QueueConnectionFactory) msg.lookup(„QCFactory“); // Get a QueueReceiver to receive messages using <queue>: // Getting a message queue: QueueReceiver receiver = session.createReceiver(queue); myQueue = (Queue) msg.lookup(„MyQueue“); // Creating a Text Message: // Connect: StringBuffer myText; QueueConnection con; TextMessage message; con = fac.createQueueConnection(); // create JMS connection message = session.createTextMessage(); message.setText(myText); Bemerkungen Example (cont‘d) MSMQ - Messaging in .NET There is also a messaging API to access ... sample continued ... // Send the message: MSMQ: sender.send(message); // receiving response: using System; TextMessage newText; using System.Messaging; newText = (TextMessage) receiver.receive(); That‘s it! namespace Messaging { class Class1 { static void Main(string[] args) { MessageQueue mq = null; if (!MessageQueue.Exists(@\".\\Private$\\myQueue1\")) { mq = MessageQueue.Create(@\".\\Private$\\myQueue1\"); } else mq = new MessageQueue(@\".\\Private$\\myQueue1\"); mq.Send(\"Hallo\"); Message msg = mq.Receive(); Console.WriteLine(msg.Body.ToString()); } } } Dein Name – Dein Vortragstitel Pra 01 - S. 22
    23. Advanced Developers Conference 10.-11. Oktober 2004 Legacy-Integration Bemerkungen Accessing Directory Services There is a special API in .NET to access In .NET using the Microsoft Host LDAP-based directories such as Active Integration Server Directory. In Java using the Connector In Java JNDI serves as an adapter to Architecture. JCA defines standard way existing directory services. to build connectors and integrate them with EJB containers Both very similar. Comparison: Java provides a much Java much more flexible. simpler way. Connectors can be implemented relatively straight forward. Bemerkungen Interoperability Interoperability (cont‘d) Java provides access to C/C++ using In .NET there is a way to interoperate JNI (Java Native Interface). Relatively with COM+ and COM+ Services. complex call-in, call-out. Java provides CORBA interoperability JMS provides integration with MoMs .NET provides PInvoke (Platform In .NET, the interoperability between Invoke): .NET languages is easy • Use the same assemblies, class libraries… class PInvokeTest { [DllImport(\"user32.dll\")] • Languages have to be adapted a little bit (e.g. static extern int MessageBoxA(int hWnd, string m, string c, int t); Managed C++ does not provide multiple static void Main(string[] args) { MessageBoxA(0, \"Hello DLL\", \"My Window\", 0); inheritance) } } Bemerkungen Controlling Resouce Access Access Control in Java In Java access control is implemented by the SecurityManager (delegates to java.security.AccessController). SecurityManager uses policy files. Use policytool to create policies. Permissions in policies control access to resources. Customized permission types possible. Jar-files can be signed (keytool). Dein Name – Dein Vortragstitel Pra 01 - S. 23
    24. Advanced Developers Conference 10.-11. Oktober 2004 BemerkungenControl in .NET Access Access Control in .NET (cont‘d) • Support in .NET Framework: Code Access Security - System.Security.Permissions • managed by CLR - System.Security.Policy • Evidence-based security (works in tandem with - System.Security.Principal Windows security). • Permissions can be requested programmatically or • Code Groups defined by membership condiions declaratively. such as zone, publisher, URL, site, publisher, • Configuration stored in XML-bsed .config files. strong name Role-Based Security • Tool caspol.exe (code access security tool) to administer code groups. • Principal: user‘s identity can be Windows account, • Code Access Permissions and Permissions Sets Passport account, ASP.NET cookie authentication specifies what assemblies are allowed to do. • Roles according to technology used. • Policy Levels: User, Machine, Enterprise. Commonalities and Bemerkungen Mobile and Embedded Differences Both approaches very similar. Differences in implementation of access control: • In .NET CLR collects evidence to grant or deny permissions. • In Java the SecurityManager is used by JVM to ask for permission. Bemerkungen Profiles and devices Profiles and devices (cont‘d) .NET Universe There are the following variants of Java • .NET: Framework for Standard und Enterprise • J2SE (Java 2 Platform Standard Edition) • .NET Compact Framework for Windows CE (and other • J2EE (Java 2 Platform Enterprise Edition) embedded OS) - Design Goals: • J2ME (Java 2 Platform Micro Edition) > Resource saving - Configurations, > Adaptability regarding device properties - and Profiles > Compatibility with the standard IDEs > Easy integration • JavaCard > Seamless connectivity - No ASP.NET, Reflection.Emit, Optimized JIT - Depending on machine stack - Simplified versioning and security, but similar formats Dein Name – Dein Vortragstitel Pra 01 - S. 24
    25. Advanced Developers Conference 10.-11. Oktober 2004 Tools Bemerkungen Profiles and devices (cont‘d) Microsoft .NET applications are mainly .NET Mobile Web Framework developed using Microsoft‘s Visual • Abstraction for the developer Studio .NET. • Several markup languages (WML, HTML, ...) • Borland will also provide support (e.g., Sidewinder, • Configurable and extendible a C# IDE) • ASP.NET can be used • Rational XDE support .NET • Emulators for devices are available for testing and • Language implementers such as ISE, ActiveState debugging purposes provide Visual Studio Plug Ins Java tool support comes from many • Extends ASP.NET with special controls different companies and organizations: • Sun, Borland, BEA, Rational, IBM, Eclipse, Compuware, ... Bemerkungen Open and Shared Source Selecting one of the two Microsoft .NET: • Shared Implementation (Rotor) available for BSD Unix and Windows. • Mono developed as open source to implement full .NRT support for Linux; still immature • Dot GNU will provide another open source approach; when will it arrive? Java: • Countless mature open source products available - JBoss (EJB), OpenEJB, Eclipse, Apache (Tomcat, Struts, ...), .... Bemerkungen .NET and/or Java ? .NET and/or Java ? .NET is a product, JVM/J2EE are specifications .NET language independence is not for free and not completely transparent Both adress the web (among other things) For „real big systems“ J2EE is better suited #pragma once using namespace System; // .NET mit C++ namespace CPPBase { The rule-of-thumb „Java is platform- public __gc class CPPBaseClass { public: virtual System::String __gc* Echo(System::String __gc *s); independent,´.NET is language independent“ }; } must be considered carefully: System::String __gc * CPPBase::CPPBaseClass::Echo(System::String __gc *s) • ECMA works on the standardization of C# and parts of .NET. { return s; } However, only subset standardized. JCP (Java Community In a real project you might want to use only Process) works very efficiently. • Other languages can be compiled to the JVM such as Jython, one language ComponentPascal, Beta, ... • But sometimes... ☺ Dein Name – Dein Vortragstitel Pra 01 - S. 25
    26. Advanced Developers Conference 10.-11. Oktober 2004 .NET and/or Java ? Noch Fragen? Bemerkungen Windows Applications are better done with .NET than Java (can Eclipse SWT change this?) Java should be used when platform (vendor-) independence is necessary Java is more mature, .NET is more modern There is also Java for .NET • But syntax is not the issue here! Both can be used for Web services - .NET is „nicer“, J2EE is more scalable Migration from COM to .NET seems to be a big issue. Analysts foresee a fifty/fifty situation for Java and .NET Bemerkungen Development for Professionals! Bemerkungen Dein Name – Dein Vortragstitel Pra 01 - S. 26

    + defzadefza, 3 years ago

    custom

    1381 views, 0 favs, 0 embeds more stats

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 1381
      • 1381 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 183
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories