55
Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved Welcome Java/.NET Interoperability by Alexander Krapf WebTech Meeting, Waltham December 16 th

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved Welcome Java/.NET Interoperability by Alexander Krapf WebTech Meeting, Waltham December 16 th

Embed Size (px)

Citation preview

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Welcome

Java/.NET Interoperability

by

Alexander Krapf

WebTech Meeting, WalthamDecember 16th

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Speaker

Co-founder & President of Codemesh, Inc.

15 years of C++ development experience

7 years of Java development experience

1 year of .NET experience 5 years of integration of Java with other languages

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Agenda

Why Integrate?

General Solution Approaches

Integration Details

Type Mapping

Integration Architecture

P/Invoke & JNI

Demonstration

Q & A

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Integrating Java and .NET ... Why?

.NET is becoming the de-facto standard for Microsoft-centric development

Java has a huge installed base on the server side (J2EE)

Enterprises are more and more agnostic

regarding server architectures

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Integrating Java and .NET ... Why?

Example 1: Enterprise Messaging using JMS

Matching Engine

Audit

Reporting

Trader

Trader

Java

Supervisor

Trader

Compliance

.NET

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Integrating Java and .NET ... Why?

Example 2: J2EE Client Server Applications

J2EE Server

Client

Java

Client

3rd Party App

.NET

Web

Client

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Application

Integrating Java and .NET ... Why?

Example 3: Reusing Existing Infrastructure

Java

.NET

JNDI JDBC / JDO IO / NIO

Data AccessObjects

LoggingConfiguration /

Discovery3rd PartyLibrary

Application #2Application #1

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Integrating Java and .NET ... Why?

Example 5: Workflow with Backoffice Apps

EJB

JMS

Excelpopulate data

Word

Word

Word

publish report

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Definition of Java

What is the Java platform?

JVM Spec

Language Spec

Class Libraries

Runtime Environment

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Definition of .NET

What is the .NET platform?

CLR

CTS

CLS

CIL

C#Language

Spec

VB.NETLanguage

Spec

mC++Language

Spec

HostSpec

CLR: Common Language Runtime

CIL: Common Intermediate Language

CTS: Common Type System

CLS: Common Language Specification

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

What we really want

Define the goals

Write C#, VB, C++, etc. source code that “links with” arbitrary Java code easily

Use all important Java language features from .NET, including callbacks

Impose no prohibitive performance penalty

Write C#, VB, C++, etc. source code that allows natural use of all native features

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

What we really want (cont.)

[STAThread]static void Main(string[] args){ Hashtable ht = new Hashtable();

ht.put( Context.PROVIDER_URL, “file://mydir” ); ht.put( Context.INITIAL_CONTEXT_FACTORY, “MyICtx” );

InitialContext ictx = new InitialContext( ht ); Context ctx = (Context)ictx.lookup( “test” );

… }

Write C# code like this:

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

What we really want (cont.)

[STAThread]static void Main(string[] args){ Hashtable ht = new Hashtable();

ht.put( Context.PROVIDER_URL, “file://mydir” ); ht.put( Context.INITIAL_CONTEXT_FACTORY, “MyICtx” );

InitialContext ictx = new InitialContext( ht ); Context ctx = (Context)ictx.lookup( “test” );

… }

Lots of Problems in a short snippet!

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Integrating Java with .NET ... How?

Translation-based:

Java to C#, Bytecode to IL

Serialization/Message-based:

CORBA, Webservices, MOM, custom

Proxy-based:

Java Native Interface

managed C++ or PInvoke

Architectural Alternatives

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Translation-Based Integration

Large set of classes involvedtransitive closure for Object: ~ 260 classes

Still need JRE or reimplementation of all native libraries IL is very different from JVM bytecode

Interface/Implementation designs are problematic

Reflection, Class.forName() are problematic

Promising at first, but very problematic

“Stale bits” are uncheckable

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Serialization/Message-Based

CORBA

WebServices

MOM

Custom

- database

- filesystem

- sockets

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Serialization/Message-Based

Different technologies, same principles

- argument/result serialization through

IIOP, SOAP, XML, ...

- object/service discovery through

naming service, UDDI, custom registries

- several processes or “objects” involved

Java process, .NET process,

file locks, table rows, helpers

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

WebService Architecture

.NET Webservice client

HTTP Server

Java ApplicationWebservice

UDDI Registry

ServerProcesses

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

WebService Development Process

Tools

- JAX APIs for class to message and

message to class mapping

- proprietary webservice vendor tools

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

WebService Summary

appropriate for WebService and SOA use

distributed

loosely coupled

unknown participants

inappropriate for mere language integration

weakly typed

not all types expressible

wrong modularity

really bad performance

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Serialization/Message-Based

Pros

- big performance penalty

- usable without JRE

- complex deployment

Cons

- difficult callback design

- not 100% reliable

- not 100% interoperable

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Proxy-Based Solution

JVM C

JNI

DLL

GeneratedProxy

Classes(C#)

C#

PInvoke

assembly

API

.NETUser

Architectural Diagram

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Proxy-Based Solution

EJB Example

J2EE Server

EJBBean

.NET Client

Home

RuntimeLibrary

EJBBean

JVM

Home

HomeHome

Client Server

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Proxy-Based Solution

Performance Characteristics

Design and Implementation have huge impact on performance

0-25% overhead depending on application

Negligible penalty in most applications

Strings can be relatively costly

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Proxy-Based Solution

xcopy Deployment

<myapp>

bin application binaries and config files

lib application Java classes (jar,zip)

jre private Java runtime environment

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Proxy-Based Solution

Threading Model

public static void main(String[] args ){ Runnable r = new MyRunnable();

new Thread( r ).start();

…}

How does this code behave in Java and in .NET ?

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Type Mapping

The Common Language Runtime

provides access to

the .NET class library or

libraries that are based upon it

using the language bindings of your choice.

What about the Java class library?

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Type Mapping

General Issues

Both platforms have object models

Slightly incompatible specifications

Both platforms have class libraries

Typenames are duplicated

Different Naming Policies

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

class to class

interface to interface

constructor to constructor

method to method

field to property

Overall a good match

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

conflicting Array models

conflicting Exception models

cannot declare static members for interfaces (CLS)

CLS has more restrictive naming than Java

But there are problems

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

both sides use garbage collection

JNI references need to be freed explicitly

IDisposable offers what we need

Care required with callbacks!

Object Lifecycle

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Classes

Java .NET

Object

String Throwable

Exception

RuntimeException

Error

Object

String Exception

ApplicationException

SystemException

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Custom TypeCustom Type

Custom Type

CustomExceptionCustom

ExceptionCustomException

Type System Mapping

.NET with mapped Java Types

Object

Throwable

Exception

RuntimeException

Error

Object

String Exception

ApplicationException

SystemException

String

Neither Strings nor Throwablesare Java Objects anymore!

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Java proxy types should extend proxy Object type (with exceptions)

Every proxy type must be usable in all places where Java Object is legal

Object Requirements

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

.NET string literals must be usable in places where Java strings are expected

.NET string literals must be usable in places where Java strings are legal

String Requirements

Object put( Object key, Object value )

String getProperty( String name )

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

java.lang.String must map to System.String because of literals

Large impact on Object-type elements

String Mapping

Object put( Object key, Object value )

becomes

object put( object key, object value )

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

interface types must be usable in all places where Java uses the Object type

interface inheritance (multiple interfaces, directly and indirectly)

static interface elements

polymorphic use (concrete object used through interface type)

Interface Requirements

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Every Java interface maps to a .NET interface and a .NET class

.NET interface type used for declarations

.NET class type used for instantiation of proxy objects and to hold static elements

Which one gets the natural name?

Interface Mapping

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Allow subscript operator to access element

Allow built-in semantic uses

Use native arrays and proxy arrays interchangably

Array Requirements

arrInt[ 42 ] += 5;

foreach( int i in arrInt ) sum += i;

int[] arrNative = new int[ 5 ];result = MyProxyClass.sumItUp( arrNative );

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Cannot extend System.Array, so fully functional .NET arrays are not possible

Proxy array type declares index operator for 90% of desired functionality

Conversion operators provide ability to use .NET array types interchangeably

Array Mapping

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

No exception specification clause in .NET method declarations!

Need to extend System.Exception or subclass

Cannot extend java.lang.Object proxy class!

May need special serialization support

Exceptions

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Java fields map extremely well to .NET properties

Care needs to be taken with static interface fields (Impl classes)

final fields translate to read-only properties

Fields

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Fields

Java .NET

interface Context{ public static final String PROVIDER_URL = “…”;}

interface Context{}

public class ContextImpl : Context{ public static string PROVIDER_URL { get { return …; } }}

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

Anatomy of a Field Access

f.x = 5;

.NET Application Code

public int x {

set { fx.set( value ); }}

.NET Generated Code

PInvokeHelper.set( fx, value );

.NET Runtime Assembly

JNIHelper.set( obj, value );

C Runtime DLL

env->SetIntField( obj, fid, value );

C JVM

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

because we’re dealing with managed code, we can directly map all constructors

no throws clause

Special cases for methods like toString(), equals(Object), etc.

Methods and Constructors

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Object Model Mapping

All non-static Java methods are implicitly virtual

.NET methods can choose virtual is explicit, optional keyword

Which virtual resolution mechanism should we use?

Virtual Methods

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Specification Incompatibilities

Corresponding methods of same name but different specification

Corresponding methods with different names but identical specification

CLS Type restrictions

Naming rules (CLS generally more restrictive than JLS)

Different APIs, same purpose (Iterator vs. IEnumerable etc.)

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Naming Policy

Offer alternatives:

Keep Java names or

Uppercase first character or

Prefix I for interface names

What’s the right way to name .NET proxies for Java types?

Very important for usability

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Naming Policy

Take care with CLS constraints!

No identifiers that only differ in case at same scope

No elements of same name but different element type (method and field of same name, class and method of same name)

Don’t break contracts when changing names!

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

PInvoke

A way to call unmanaged code from managed code

Managed Code (in assembly)

class MyInvoker{ [DllImport(“myunmanaged.dll”)] public static extern int callMe( int val );}

Unmanaged Code (in myunmanaged.dll)

extern “C” __declspec(dllexport) int __stdcall callMe( int val );

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Using JNI (Example)

jclass cl = env->FindClass( “com.codemesh.MyClass” );

if( cl == 0 ) { jthrowable t = env->ExceptionOccurred(); env->ExceptionClear(); return;}

jmethodID mid = env->GetMethodID( cl, “<init>”,“(Ljava/lang/String;IIZ)V” );

if( mid == 0 ) { jthrowable t = env->ExceptionOccurred(); env->ExceptionClear(); env->DeleteLocalRef( cl ); return;}

jstring arg1 = env->NewStringUTF( “test” );

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Using JNI (Example) cont.

jobject temp = 0, result = 0;

temp = env->NewObject( cl, mid, arg1, 1, 2, JNI_TRUE );

if( temp == 0 ) { jthrowable t = env->ExceptionOccurred(); env->ExceptionClear(); env->DeleteLocalRef( cl ); return;}

result = env->NewGlobalRef( temp );env->DeleteLocalRef( temp );

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Demonstration

A look at the demo source code

A look at particular features of the

enabling source code

A look at a code generator

An EJB example:

C# app that works with a JRun server

Q & A

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Literature/References

The Java Native Interface, Programmer’s Guide and Specificationby Sheng Liang, Addison-Wesley, ISBN 0-201-32577-2

Essential JNIby Rob Gordon, Prentice Hall, ISBN 0-136-79895-0

.NET and COM, The Complete Interoperability Guide by Adam Nathan, SAMS, ISBN 0-672-32170-X

JNI Documentationhttp://java.sun.com/products/jdk/1.2/docs/guide/jni/

JGuruhttp://www.jguru.com

Stu Halloway’s Java Interop sitehttp://staff.develop.com/halloway

Copyright 2003, 2004 by Codemesh, Inc. All Rights Reserved

Thank you!

Codemesh, Inc.P.O.Box 620Carlisle, MA 01741

http://[email protected]

Let’s go outafter the demo!