Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, 3 February 2010

GlassFish v3 and Java EE 6 Sun-Oracle roadshow - key notes

GlassFish Roadshow 2010 - London 03-02-2010

The following is some notes I took down during the above event.

In brief summary of GlassFish v3 and Java EE 6, here are some of the key takeaways:

  • GlassFish v3 continues to be developed and supported, as the Java EE 5 & 6 RI app server
  • GlassFish v3 currently has no clustering, but offers OSGi modularization and extensibility
  • Supports and takes advantage of new Java EE 6 specifications
  • Big push on modularity and flexibility in both GlassFish and Java EE 6
  • Java EE 6 supports annotation based EJBs, RESTful web services
  • Java EE 6 greatly simplified configuration, optional web-inf.xml etc
  • Java EE 6 simplied simple class EJBs and improved JPA specification
  • Ongoing road-map for GlassFish, details TBA later this year


Java EE 6 (Roberto Chinnici):

Released Dec 10 2009

Key new features: New API, Web profiles, Pluggabiliy, dependancy injection

New technologies:
  • Jax-RS 1.1
  • Bean validation 1.0
  • DI 1.0
  • CDI 1.0
  • Managed beans 1.0
Closed down gap between EJB and POJO with unification and annotations

CDI works with POJO and EJB classes

Unification of platform types, more uniform programming model

  • EJB 3.1
  • JPA 2.0
  • Servlet 3.0
  • JSF 2.0
  • Connectors 1.6
  • Interceptors 1.1
  • JAX-WS 2.2
  • JSR-109 1.3
  • JSP 2.2
  • JSR-250 1.1
  • JACC 1.4
  • JASPIC 1.1

Key goal in Java EE 6 - flexibility, pruning, extensibility and web profiles


Profiles:

Bundles of technologies targeting specific classes of applications
Decoupled from each other and the platform
Guarantees compatibility of required technologies, individually and in combination - must satisfy all joint requirements


Web Profile:

Modern Java web application stack
First profile to be definite
Mid sized, fully functional (expected 80% web-app coverage), add additional components via extensibility (such as web services API, 3rd party frameworks)


Web profile contents:

Servlet, JSP/EL, JSTL, JSF, Bean Validation, EJB Lite, JPA, JTA, Di, CDI, Managed beans, Interceptors, JSR-250


Pruning:

Goal - to address bloat concerns

2 step process:
Declare components as "Proposed optional"
The make fully optional for the next release

Proposed optional technologies:

JAX-RPC (JAX-WS)
EJB 2.x Entity beans (JPA entity classes)
JAXR (little use)
JSR-88 (deployment, tools API - not used)

* Don't use - use replacements / alternatives


Pluggability / extensibility:

Focus on web tier
Level playing field for 3-rd party libraries and frameworks
Two major extensibility points: Servlets and CDI
Simplify packaging of web-apps
Zero-configuration!


Modular Web applications:

Libraries can contain web-fragment.xml descriptor
web.xml is now optional
Can server resources out of jars with: /META-INF/resources

e.g.
/WEB-INF/lib/catalog.jar
/META-INF/resources/catalog/books.html

e.g. Dojo jar in resources


Web fragments in servlet 3.0:

META-INF.web-fragment.xml

same structure as web.xml, can override in web.xml


Servlet container pluggability:

ServletContainerInitializer interface implements by extensions

@HandlesTypes to declare interest in on or more annotation types

ServletContext now contains method to dynamically register servlets and filters
i.e. ServletContext API has been extended

Registered using META-INF/services


onStartup method gets called with a Set of classes available

** Can only add services at startup, not dynamically once running


Asynchronous HTTP processing:

New programming model for async request processing
e.g. Comet, char, push apps
Opt-in model
Threads are managed by the container

@WebServlet(asyncSupported=true)
public class MyServlet extends HTTPServlet {

}

Goal - Decouple requests from threads

* Changes to the way filters work - thread not attached to the socket, response not written. Filters modified to make safe - option than can be turned on to identify asyncSupported=true
- do this on servlet and any filter involved in the chain

Ideal when waiting for some external resource etc.
Low level API - not very elegant
Idea is that frameworks will use this - see for example Atmosphere framework which is based on annotations - under the hood this async API is used.


JSF 2.0:

Facelet as a standard view declaration language
Composite components
Ajax (declarative and programmatic) e.g. f:ajax tag
Partial state saving (track deltas and sends changes in response, previously all would have been sent even if not changed!)
System events e.g. f:event tag
Resources
Validation e.g. new f:validateBean tag (better integration, validation API. can handle multiple errors, not first one at a time!)


EJB 3.1:

@Singleton beans
@Startup beans (invoked at app startup, works well with Singleton pattern)
@Asynchronous invocations (biggest change, allows non-blocking sync EJB invocations as first class call. Method must be either void or return a Future object)
No interface view (bean impl does not need an interface anymore, now 1 class = 1 EJB!)
Define EJBs directly inside a web app, inside a war file
New API - EJBContainer API works on Java SE, can bootstrap an EJB container in a Java SE application (ideal for testing/development, could be useful in client applications)


Simplified packaging:

EJB class directly into the war file
Previously must built an EJB jar to be included


EJB 3.1 lite:

A subset of EJB 3.1
All types of session beans (stageful, stateless, singleton) - other bean types not supported (timer, entity etc)
Declarative transactions and security
Interceptors
ejb-jar.xml descriptor allows (is optional, probably not useful)

* Class loading, new visibility rules in Java EE spec

Slight differences in class loading rules - if in doubt check the specs


New JNDI Namespaces:

Until now - only java:comp
Now added:
java:module - a module (war, ejb, jar)
java:app - an application
java:global the whole server / cluster

e.g. @Resource(lookup="java:app/CustomerDB") DataSource db;

EJB components have global names now:

e.g. java:global/app1/module2/SomeBeanIcom.acme.Foo

Helps solve problem of remote EJB communication in same app server


Dependency injection (DI):

Combination of DI 1.0 / CDI 1.0
New @Inject annotation
@Inject @LoggedIn User user; (@LoggedIn = "Which one", User = "What")
Beans auto-discovered at start-up
Extensible
Injection metamodel (BeanManager API)
@Resource still available for container resources

* Identified by type and qualifiers (no longer just a string name alone)

* No bean declaration as per Spring declaration, bean discovery at startup
* Injection errors all reported at startup, rather than on use at runtime

Beans can be associated with session - i.e. loggedIn
Beans can be more ephemeral, i.e. for request
Beans can be more long lived, i.e. shopping cart conversation flows
Can add class for beans on the fly, via APIs at runtime

Example of DI annotation:

@Inject
CheckoutHandler(
@LoggedIn User user,
@Reliable @PayBy(CREDIT_CARD)
PaymentProcessor processor,
@Default Cart cart)

* Note that constructor injection is possible
* Note different scopes, PaymentProcessor is probably conversation scope, LoggedIn is session, PaymentProcessor is probably application scope singleton

* Instance and state management handled "for free" by framework/APIs

JAX-RS 1.1:
Already widely adoped
Really a high level HTTP API
Annotation-based programming model
Programmatic API when needed

* think of it as the new HTTP level API (higher level than HTTPServlets, remove low level detail and tedium)

Jax-RS resource class, example:

Identified by the @Path annotation

@Path("widgets./{id}")
@Produces("application/widgets+xml")
public class WidgetResource {
pubic WidgetResource(@PathParam("id") String id { … }

@GET
Widget getWidget() { … }
}

Provides higher level HTTP handling, more declarative, better match with conceptual needs of developer


Bean Validation 1.0:

Integrated with JSF, JPA
Constraints represented by annotations

e.g.

@NotNull
@Size(max=40)
String address;

Fully extensible
@Email
String recipient;

Validation API's for validation directly, create a new validation object etc
Validation of trees of objects is possible (including loops)


JPA 2.0:

Supported for collections of basic types and embeddable objects
JPQL enhancements e.g. CASE WHEN, NULLIF
Pessimistic locking added (annotations added)
Criteria API for dynamic query construction

Criteria API: Uses the canonical metamodel classes

CriteriaBuilder, create criteria
CriterialQuery, typed criteria

Strongly types checking, type parasitised equals checking, compiler errors generated if query does not have the right types etc, so robust and safe query (rather than say String SQL construction directly).

Connectors 1.6 added too (not covered in any detail)


Summary overview:

Improved, more powerful, more flexible, more extensible, easier to use

http://java.sun.com/javaee


--

GlassFish V3 (Alexis Moussine-Pouchkine):

Java EE 6 Reference Implementation (RI)

Geographic download map:

http://maps.glassfish.org/server

Healthy increase in downloads and usage over time

GlassFish V1 first shipped 2006, reusing much from Tomcat

V2.1.1 Nov 2009, V3 (Java EE 6) Dec 10th 2009

GlassFish V3 Open Source CDDL, GPL (with 'classpath exception') licensing

Java EE 5 & 6, enterprise quality - full support is available.

Sub projects:
  • Jersey (JAX-RS)
  • Metro (JAX-WS)
  • Grizzly (NIO)
  • Atmosphere (Comet)
  • OpenMQ (JMS)
  • and scripting jRoR Grails and now Django (python)

Main difference from Tomcat - Grizzly core (rewritten)

Netbeans 6.8 tooling
Support available in Eclipse too

GlassFish development continues
Support contracts through to 2017+ unlimited
Remains the Java EE reference implementation
Now also sold with WebLogic and standalone

Roadmap -> expected soon for remaining year

Don't have to deliver as much standard runtime / frameworks jars as part of the application jar

Netbeans in-place edit of classes, incremental compilation, deploy on save, GF v3 preserves session across redeployments(!)

Session retention:
Deployment option to maintain statefull sessions across re-deployments!


GlassFish v3 key goals:

Modular and dynamic
Modular: Apache Felix (OSGi)
Extensible: HK2 (100k kernel)
Still very fast!

Centralized configuration, modules configured through centralised control


Key Features:

No ejbjar.xml needed, no web.xml, annotation driven, EJB's as single classes

Declarative annotations:

@Stateless annotation for class stateless bean
@Schedule annotation for timers

Eclipse - GlassFish tool bundle for eclipse (contains everything!)

Ultra fast auto-deploy of all Java EE and static artefacts

Maven support: mvn gf:run gf:start gf-deploy

Containers can be added / removed dynamically


New API for EJB testing (EJBContainer):

Example:

EJBContainer c = EJBContainer.createEJBContainer();
Context ice = c.getContext();
SimpleEjb ejb (SImpleEjb)ic.lookup("java:global/sample/SimpleEjb");
ejb.sayHello();


GlassFish "Embedded" - allows all features of GlassFish to be automated

org.glassfish.api.embedded.Server server;
Server.Build builder = new Server.Builder();
server = builder.build();
ContainerBuilder b = server.createConfig(ContainerBuilder.Type.web);
server.addContainer(b);

File archive = new File("hello.war");
server.getDeployer().deply(archive);

i.e. Ship app server inside an application!


OSGi:

GlassFish runs on top of OSGi (Felix by default)
Also runs unmodified on Knopflerfish and Equinox
GlassFish ships with 200+ bundles
Can run without OSGi (static mode based on HK2)
Can use OSGi management tools (CLI or Web)

Any OSGi bundles will run in GlassFish v3
Drop it in glassfish/modules

Servlets can get hold of OSGi bundles (using @Resource DI)


Update centre:

Graphical tool (GlassFish does not need to be started), available in web admin console
CLI version available
Was in v2.x but not from admin console


RESTful admin API:

JAX-RS/Jersey + Grizzly to provide REST interfaces to
Configure runtime (via GET, POST, DELETE)
Invoke commands (restart, stop, deploy, etc)
Monitoring (GET only)
Log rotation etc

e.g. Available from:
localhost:4848/management/domain
localhost:4848/monitoring/domain


Further advantages:

Dynamic language support via modules:
Rails, Grails, Django, Scala/Lift


Comet:
Cometd/Bayeux
Atmosphere

Full support for:
mod_jk
WebDAV, CGI, SSI

OpenMQ 4.4

Web Services Metro 1.4
.NET 3.5 interoperability


v3 Clustering:
Lower priority after Java EE 6 and modularity, so not yet...
Clustering is not built in as per v2
More similar to v1, single instance
Have to take on own clustering (load balancing, deployment)
See roadmap for details...


Doing More with GlassFish (Steve Elliott):

GlassFish v3 - Management and monitoring

Management:

User Friendly, pluggable and extensible for administration
Feature rich Admin console (GUI)
Easy to use Command Line Interface (CLI)
RESTful management and monitoring API
Fully documented AMX API (app server management API)
All management features built on AMX API

OSGi, load on demand = fast initial start up

v3 AdminConsole:
Frame-set removed, now Ajax based pages
Pluggable console (admin panes, trees etc loaded on demand)


Monitoring:

Lightweight prode architecture
Ad hoc monitoring in Production
Client-scripting (JavaScript)
DTrace integration on Solaris (similar to OS probes, uniform tracing experience with MySQL etc)
Extensibility / Pluggability

No overhead when there is no monitoring
Allows Monitoring to be turned on in a production environment with minimal impact
Generate and listen to only interested
Turn on monitoring when needed
BTrace integration
Portable and dynamic


Instrumentation:

Modules expose probes
POJO with annotations
XML

Modules register probe listeners

In code, POJO annotations can be used

@ProbeProvider(providername="glassfish", modulename="web")

ProbeProvider XML configuration also possible

ProbeListeners
JMX exposed

@ManagedAttribute(id="jspcount")


OSGi:

big move to OSGi technology
Big move to more modular development approach

Demands and enforces stronger modularity

OSGi is largely under the covers
Visible to GlassFish developers, but not to GlassFish users


Service based architecture:

Core modules loaded on app startup
Rest loaded on demand

Module Management:
add, remove, update installed modules

OSGi as a container


Web services - Metro : JAX-WS / Jersey : JAX-RS

Metro - SOAP-based web services stack
Built into GlassFish
Works with any servlet 2.5 compliant web container
WebLogic, WebSphere, JBoss, Tomcat
Also standalone
Advances interoperability with .NET 3.x/4.0

Project Tango - focused on interoperability with .NET

JAXB based XML Data Binding (XSD, XPATH)

SOAP Messaging MTOM etc

Bi-directional interoperability with .NET (Java or .NET as client or server)


Standards:

JCP: JAX-WS 2.2 & JAXB 2.2
W3C SPAP 1.1/1.2 WSDL 1.1, WS-Addressing
… etc


JAX-RS:

JAX-RS 1.1 is final and part of EE6

Not a web profile
but included with GlassFish v3 web profile
JCP 311
Spec - JSR 311

http://www.oracle.com/java
Contains links to GlassFish etc


.

Wednesday, 24 December 2008

Scala, an introduction

Scala - "Scalable Java": a new Language which combines both Object Orientated and Functional programming paradigms.

Scala is an extension of Java and runs on the JVM. Scala draws from languages such as Java, Smalltalk, Erlang and many others.

Scala site: http://www.scala-lang.org/

Downloads: http://www.scala-lang.org/downloads

Installation, using the IzPack Scala installer jar, run: java -jar scala-x-installer.jar


Scala - main features:
  • Integrates with Java (is an extension of Java), and shares libraries and primitive types
  • Compiles to Java byte code - runs on JVM (also can be run on .Net)
  • Imperative and functional support
  • Object Orientated (classes, objects)
  • Functional (functions as first class objects, referential transparency)
  • Statically typed
  • Type inference (more concise code that looks more like Dynamic/duck typed, but has the benefits of static / strong typing)
  • Supports closures and function literals
  • Concurrency model using Erlang Actors system (a 'safer' concurrency model)
Scala can be run stand alone, using the command line interpreter - using the "scala" command.

Scala also has plugin support for NetBeans, Eclipse and InteliJ


Syntax Overview:
  • Type inference means most type declarations can be omitted (but can still be explicitly declared).
  • Variables are defined as name : type rather than type name as per Java
  • Semicolons are often optional
  • Does not specify or define operators. +-*/ etc are valid method names are defined as such for appropriate types
  • var and val keywords - val declares a constant type (like Java's final, not reassignable), var declares a variable that can be reassigned. val, like var can still be mutable however, if the type is mutable.
  • Functions, declared using def keyword. e.g. def myFunction(x: Type1, y: Type2) : ReturnType
  • Pre and post increment/decrement (i++, ++i, i--, --i) are not supported, use i = i + 1 or i += 1
  • Recommended indentation is 2 spaces
  • Imperative for loops not supported, the functional equivalent, a for Expression is used instead
  • Arryays are indexed using (n) not [n]
  • Type parameters are specified using [type]. If both type and index are used, the ordering is [type](params)
  • Scala supports infix as method calls. e.g. 1 + 2 is equivalent to 1.+(2) where + is not a special operator, but a regular method
  • Applying () to an object (recipient) is equivalent to calling .apply() on it. e.g. myThing(i) is equivalent to myThing.apply(i)
  • The receiver of an = operator is equivalent to calling .update. e.g. myThing(i) = value is equivalent to myThing.update(i, value)
  • Method association is by default to the left, unless the method ends with a colon : e.g. 1 + 2 applies + to 1 giving 1.+(2) whereas x :: y applies :: (cons) to y, giving y.::(x)
  • The List type supports ::: (concat) and :: (cons, prepend), both apply the operation and return the resulting new List
  • Arrays are always mutable, lists are always immutable. Sets and maps can be either, the default is immutable (from the trait scala.collection.immutable) but the mutable equivalents can be imported from scala.collection.mutable
  • The -> method provides Implicit Conversion. e.g. x -> y is x.->y which returns a key/value tuple containing x as the key and y as the value

Some simple Functional examples:

Print all command line arguments, using foreach, passing println function:

Verbose:
args.foreach((arg: String) => println(arg))

Type inference on arg:
args.foreach(arg => pringln(arg))

Concise:
args.foreach(println)

The last example is a shorthand that can be applied when a function literal cosists of one statement that takes one argument - known as a Partially Applied Function.


For Expressions:

Replacing imperative for loops, the syntax is of the form:

for (arg <- args)
println(arg)


Note: In the above for expression example, arg is a val (final/const) not a var, and a new val variable is created for each "iteration".

or

for (i <- 1 to 30) ...


Declaring Arrays:

Very concisely:

val myArray = Array("value1", "value2")

defines a string array (type inference) of size 2

This is equivalent to:

val myArray = Array.apply("value1", "value2")

where apply is called on the Array Companion Object

More Verbosely the array could also be declared more traditionally as:

val myArray = new Array[String](2)

or even

val myArray : Array[String] = new Array[String](2)

but the former concise approach is the Scala recommended way, the later hints at the underlying Java roots.

Lists:

Defining new lists is easy with the cons method, as follows:

val myList = 3 :: 2 :: 4 :: 5 :: Nil // Nil is the Empty List, also so is List()

Note: The Nil (empty List) is needed so that working from right to left, the :: method is defined on Nil, which first gives Nil.::(5) returning List(5) which then gives 5.::(4) resulting in List(4, 5), and so on. Without the Nil there is a syntax error as :: (cons) is not defined on 5 (which is of type integer).


Examples:

Factorial ! - Simple factorial, defined in a functional way:

def factorial(value : int) : int = { if (value == 0) 1 else value * factorial(value - 1) }

scala> factorial(10)
res15: int = 3628800


Triangle Numbers:

def tri(x : Int) : Int = { if (x == 0) 0 else x + tri(x-1) }

scala> tri(4)
res14: Int = 10


Scala for scripting:

Scala scripts can be run using scala myscript.scala

Additionally, Scala can be used as a self contained scripting language by invoking the scala command line interpreter with the script, as follows:

On 'nix platforms

#!/bin/sh
exec scala "$0" "$@"
!#
println("Hello world, hello " + args(0))

Don't forget to give the script execute permissions (chmod +x myscipt)

Execute: myscript Louis

A similar thing can be achieved on Windows...


Scala with build systems:


With Ant:

http://www.scala-lang.org/node/98


With Maven:

http://scala-blogs.org/2008/01/maven-for-scala.html


Further Resources:

Books:

Artima book (excellent): http://www.artima.com/shop/programming_in_scala released 17th Nov 2008, by Martin Odersky, Lex Spoon, and Bill Venners.

Source code for book examples: http://booksites.artima.com/programming_in_scala/progInScalaExamples1EdV6.zip

Browse book examples: http://booksites.artima.com/programming_in_scala/examples

OReilly Programming Scala: http://programming-scala.labs.oreilly.com/


Blogs:

http://www.scala-blogs.org/

Blog on Monads: http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html


Articles:

Java refugees: http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-1


Build tools:

SBT: http://code.google.com/p/simple-build-tool/


Interesting Blog about Scala and Lift (using Maven and Jetty).

http://scala-blogs.org/2007/12/dynamic-web-applications-with-lift-and.html


SIDs (software improvement Documents):

http://www.scala-lang.org/sids


Monads:

http://projects.tmorris.net/public/what-does-monad-mean/artifacts/1.1/chunk-html/ar01s04s04.html

http://vimeo.com/8729673


IRC channel: #scala on irc.freenode.net


(Also (unrelated): pastie - http://pastie.org/ is handy for pasting those odd snippets of code around on the internet/IRC).


Interesting blog about Scala type-safe SQL / DB - SQuery - http://szeiger.de/blog/2008/12/21/a-type-safe-database-query-dsl-for-scala/

Updated (13-09-2009): Came across this useful presentation: http://www.slideshare.net/astubbs/scala-language-intro-inspired-by-the-love-game?src=embed


99 Scala problems - an adaption of the 99 Prolog problems into Scala:

http://aperiodic.net/phil/scala/s-99/#p10


.

Sunday, 7 December 2008

JSON, Java and JavaScript

JSON is so simple there's not a lot to say about it, but I thought it's worth putting up a few links and notes for reference.

JSON is JavaScript Object Notation. Whilst it could be called an Object Notation (a simple one), it's not tied to JavaScript, although it's early origins are from that language (ECMAScript, ECMA-262 3rd Edition). JSON is essentially language independant, like XML. JSON, like XML can represent data structures and data (self describing) but unlike XML, JSON does not support namespaces, schema and other more advanced features. JSONs key strengths are its simpicity and low overhead, terse message size.


JSON looks like this:


{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}


Where { and } contain the object, the properties are listed as "name" : "value" pairs. Objects can be embedded within objects and arrays are denoted using comma separated lists within []

So, special symbols (for escaping) are: {}[]:"

Main Site: http://www.json.org/

Simple JSON for Java: http://www.JSON.org/java/json_simple.zip http://www.json.org/java/simple.txt

Simple JSON for JavaScript: http://www.json.org/js.html

Wikipedia: http://en.wikipedia.org/wiki/JSON


JavaScript:

Basic suppport for converting JSON messages into objects (deserialisation) is to use the often best avoided eval function, as follows:

var myObject = eval('(' + myJSONtext + ')');

where the outer '(' ')' are necessary for the JavaScript language, not JSON itself.

Better (safer) still, various libaries are available, such as the Open Source version from www.json.org in json2.js

Which essentially is used like this:

var myObject = JSON.parse(myJSONtext, reviver);

var myJSONText = JSON.stringify(myObject, replacer);


Java:

Create a JSON string using org.json.simple.JSONObject:

JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
System.out.print(obj);

The toString() on the JSONObject serialises the JSON object (map of name value pairs) to a JSON string.

JSON is simple, by design, so there isn't much more to be said on it.

One of the main things to watch out for is encoding/escaping messages so they are JSON friendly, I'll add more on that soon.

The following link may be useful when working with character escaping: http://www.the-art-of-web.com/javascript/escape/

.

Sunday, 23 November 2008

Applet <-> Javascript integration

It's been a while since I've done this, but I thought I'd refresh my memory on the options available. Maybe Applets have fallen out of favour a bit and whilst Javascript is popular for Rich, Dynamic Internet Applications, sometimes you need more and one way to do it is to use Applets, or integrate Applets with Javascript.

This example shows some simple ways to achieve Applet/JavaScript integration:

I've included example HTML with JavaScript source and Java source code for an Applet, to demonstrate so ways to achieve JavaScript to Java Applet integration. The simple example code demonstrates both JavaScript calling a Java Applet and a Java Applet calling JavaScript.

The JavaScript function jsShowMsg(String) is called in two different ways from the Java Applet. A single string parameter is passed, and the JavaScript function displays this using the standard alert() function to create a dialog box.

The Applet provides a showMessage(String) public method, which similarly is called by the JavaScript code when the button on the page is pressed. The String parameter is taken from the text field and displayed in the Applet.

HTML Page:


Provides the Applet on the page. Provides the JavaScript function called by the Applet, calls the Applet public method when the button is clicked (takes the String value from the input text box.

--

<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<script type="text/javascript">

/**
* jsShowMsg - demostrates being called by an Applet, being passed a single String argument, the message
*/
function jsShowMsg(msg)
{
alert("Message from applet was: '" + msg + "'");
}

/**
* callApplet - demonstrates calling a public method on the Applet (showMessage(String))
*/
function callApplet(msg)
{
//alert("before calling Applet method with msg=" + msg);

document.testApplet.showMessage(msg);

//alert("after calling Applet method");
}
</script>

<H3><HR WIDTH="100%">Applet HTML Page - Applet <-> JavaScript integration example<HR WIDTH="100%"></H3>

<P>
<APPLET name="testApplet" codebase="classes" code="com/chillipower/TestApplet.class" width=400 height=150></APPLET>
</P>

<input type="text" id="msgTb" name="msgTb" value="A message from JS!" /><input type="button" value="button1" onclick="callApplet(getElementById('msgTb').value);" />

</BODY>
</HTML>

--


Java Applet Class:


Calls the JavaScript function in two different ways when the Applet is started. Provides a showMessage public method that the JavaScript can call.

--

package com.chillipower;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;

/**
* @author Louis B
*/
public class TestApplet extends Applet
{
String JS_MESSAGE = "Hello from Java Applet to JavaScript (using JavaScript alert)";
String JS_FUNC_NAME = "jsShowMsg";


/**
* init - applet init function
*/
@Override
public void init()
{
setBackground(new Color(0xFAFAFF));
}

/**
* start - applet start function
*/
@Override
public void start()
{
callJsByProto(JS_FUNC_NAME, JS_MESSAGE + " using showDocument :javascript protocol method");

callJsFunc(JS_FUNC_NAME, JS_MESSAGE + " using JSObject method");
}

/**
* Overide paint with simple text rendering
*
* @param g
*/
@Override
public void paint(Graphics g)
{
g.drawString("The Applet", 20, 20);
}

/**
* Simple function to show a message
*
* @param msg
*/
public void showMessage(String msg)
{
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawString("Message from JS: '" + msg + "'", 20, 40);
}

/**
* Call a named JS function, passing a single String parameter
*
* @param funcName
* @param msg
*/
private void callJsByProto(String funcName, String msg)
{
try
{
getAppletContext().showDocument
(new URL("javascript:" + funcName + "(\"" + msg +"\")"));
}
catch (MalformedURLException ex)
{
System.out.println("ex: " + ex.getMessage());
}
}

/**
* callJsFunc - call the named JavaScript function, passing the String msg argument
*
* @param funcName
* @param msg
*/
private void callJsFunc(String funcName, String msg)
{
String jscmd = funcName + "('" + msg + "')"; // Buiild the JavaScript command
String jsresult = null;
boolean success = false;

try
{
Method getw = null;
Method eval = null;
Object jswin = null;
Class c = Class.forName("netscape.javascript.JSObject"); /* works in IE too */
Method ms[] = c.getMethods();

for (int i = 0; i < ms.length; i++)
{
if (ms[i].getName().compareTo("getWindow") == 0)
{
getw = ms[i];
}
else if (ms[i].getName().compareTo("eval") == 0)
{
eval = ms[i];
}
}

Object a[] = new Object[1];
a[0] = this; /* this is the applet */
jswin = getw.invoke(c, a); /* this yields the JSObject */
a[0] = jscmd;
Object result = eval.invoke(jswin, a);

if (result instanceof String)
{
jsresult = (String)result;
}
else
{
jsresult = result.toString();
success = true;
}
}
catch (InvocationTargetException e)
{
jsresult = e.getTargetException().getMessage();
}
catch (Exception e)
{
jsresult = e.getMessage();
}

if (success)
{
System.out.println("JS eval succeeded, result is " + jsresult);
}
else
{
System.out.println("JS eval failed with error " + jsresult);
}
}
}

Debugging:

1. Using the Java ControlPanel (on 'nix, it is View Settings -> Edit the Java Runtime settings.

-agentlib:jdwp=transport=dt_socket,address=:

This makes the browser plug-in JRE open a debugging socket connection when launching the applet.

2. Open the Netneans project and attach the debugger in the SocketListen mode, using the same settings as above.



Resources:

http://windyroad.org/2006/08/14/reintroducing-javascript-and-hidden-applets-jaha/

http://java.sun.com/javase/6/docs/technotes/guides/plugin/developer_guide/java_js.html


.

Friday, 11 April 2008

SCJP 5 exam passed - woot!

It's been a busy day today, some last minute revision this morning then took the SCJP 5.0 exam this afternoon. What can I say, 3.5 hours! That's a long exam. I didn't use all the time, but still that's a quite a lot of exam for the money!

Anyway, I'm relieved and pleased to pass with 83% - not bad, could have done better but I happy with that, to be fair as a balance between time spent and other commitments.

Time to celebrate tonight I think. It's nice to get that one out of the way, will have a short break then decide which one to tackle next!

(Note to self: see if you can take a drink in next time! Got really thirsty, dehydrated and sleepy in the middle of it and no one was around so I wasn't sure if I could leave the room to get a drink, so I had to stay put - ooops!)

Notes on the exam itself:

Generally I'd say it seemed easier than I was expecting. Some questions seemed very easy, leaving me in doubt as to whether I'd missed something and then spending longer on the question than I would normally, double checking the question and answer.

The mark and review system is excellent. I also used the provided dry wipe sheets and pens to keep track of questions I wasn't sure of so I could go back. Going back to a drag and drop question does mean you lose your previous answer - but it does warn you before it happens. It seems you can only review your questions once you've gone through the whole test, so it's worth finishing with enough time left to go over the harder questions that you've marked again at the end. 3.5 hours is a long time, I suspect 3 would still be more than enough, but it's surprising how long it takes to answer 72 questions, which is a lot of questions really. If you struggled on half of them you'd be mentally exhausted by the end. The exam does concentrate quite a lot on API and syntax specifics, so you've really got to spend some time just revising and remembering those specific API classes and methods. Overall, a good experience, I'd recommend anyone in a position to do it does so, preparing for it certainly gives you a good grounding in many aspects of Java SE 5.

What to do next, that's the question. Probably one of the web developer (web components or services) ones, as they would be beneficial in my job. I guess I should do an upgrade exam from 5 to 6 (or 7!) soon too, ideally.


Resources:

I've made my personal SCJP 5.0 study guide available on my personal web site www.chillipower.com - specifically here http://www.chillipower.com/Primers/SCJP%205%20Study%20Guide%200.1.doc for anyone who might find it useful.

Although SCJP 5.0 is technically out of date already, v5.0 represents the bulk of the material needed in order to pass. I will at some point take the upgrade exam, but this is lower priority right now.