samedi, juin 21, 2008

Javascript: The Black Beast of Aaaaarrrrgggghhhh (part 1)

I've really wanted (and still want) to have a grasp on how Javascript should be coded the Javascript way.

As a regular Java (and occasionally other languages) developer, I've sometimes used javascript with this constant sense of weirdness on the edges, and without being able to grasp the concepts in it.
In fact, the browsers' DOM and the history of the Javascript implementations in browsers contributed to this fuzziness (as we'll see later).

Basic concepts:

Javascript has very little to do with Java. In fact its name only contains java for marketting purposes of that time. Javascript is a language from the C family like java and uses a lot of the same operators and syntax.

This can be confusing, because Java and Javascript are indeed very different.

While Java is based on classes and inheritance between classes, Javascript is based on objects and inheritance between objects.
Javascript is also a prototype-based language (which is I think the hardest part to grasp...).

This may sound a bit abstract, but one cannot hope coding proper javascript without at least understanding these concepts.

A little pause

Before we start explaining the previous concepts, you must be aware that Javascript's history has been very clumsy to say the least.
Some good decisions were taken, and some very bad ones.

Most of the bad decisions were made during the browsers' war (Netscape vs Internet Explorer) with a purpose to attract developers from Java/C++ or VBScript for example.

These bad decisions leave strange reserved words in the language (like 'abstract' or 'interface' which are never used,) that should never be used or even cannot be used, and constructs that come from other worlds.

If you add to that the incompatibilities of APIs and models between browsers, it's easy to understand why Javascript is still often considered as a toy language.

So don't be surprised by the number of things that should not be used or touched in Javascript.

Javascript is not a toy language, nor a poor OO language.

In fact, in a way, Javascript is more OO than Java is ;).
In Javascript (almost) everything is object (think instances, forget about classes!).

Here's a list of the things that are NOT objects in Javascript:

  • numbers

  • strings

  • booleans

  • null

  • undefined



Everything else is objects.
Yes, everything.
Keep that in mind, and remember (again) that I said Object (instance), not Class.

One really clever thing that was done in javascript is the merging of Objects and Hashtable.
A new Object is an empty container of key/value pairs.

For example, one can create an object using:


var myObject={};


As Javascript is loosely typed, there is no class definition. You just created an Object with nothing in it.


var user={
firstname="Pierre-Antoine"
,'lastname'='Grégoire'
,age=31
};


As you can see, it's quite easy to create an object using key/values.
As you also probably noticed, keys can be String, therefore allowing access to members in two ways:

  • using the dot notation: user.firstName

  • using the subscript notation: user["firstname"]



This is it for this first short part. Next blog entry will introduce the functional nature of Javascript.

SpringOne08: RESTFUL Web Services

Late publication, didn't have the time back then ;)

A general presentation of REST:
- Everything is a resource (which has a value to the user). These are expressed by URIs and nouns
- Uniform interface (GET, HEAD, POST, PUT, DELETE, OPTIONS, and optionally TRACE)

GET:
safe operation (can be repeated) that retrieves a representation of the Resource.
GET is Cacheable (Servers return ETag or LastModified)

HEAD: identical to GET without response body, only headers.

POST: creates a new Resource (Typically as a child to another Resource)
POST /hotels/1/bookings/ for example returns a location like: /hotels/1/bookings/50/

PUT: updates a resource or creates a resource when the destination URI is known.
As opposed to POST this can be repeated affecting the same resource.

DELETE: IdemPotent, if an item is not there, it doesn't fail.

OPTIONS:
retrieves allowed HTTP methods on a resource.


Resource reprensentations => multiple representations (html, image, json... etc)

Stateless conversation:
no HTTP Session! State is maintained through transitions between links. As a result, the result is very scalable and enforces loose coupling.

Hypermedia: fancy word for links ;), XLink is a spec for that and allows seamless evolution.

SpringOne08: MDA and Spring

Late publication... didn't have the time back then ;)

Capgemini NL featured talk.
Begins with some basic concepts of MD*.

Then describes what an MDA tool is supposed to do and who's going to use it.
This is one point of view.

Pitfalls:
- Prevent "architecture-driven modeling" using markings.
- Keep applying traditional patterns of re-use, even if code generation can allow to generate a lot of boiler-plate code.
- Don't "u-em-ellify" everything.
- Don't touch your generated files (I tend to disagree... it just means that you need appropriate tools for that, though it does have problems with refactoring, and he recommends using Abstract classes).

Recommended tooling:
- MDA tools: OSS=> OAW, Acceléo Commercial=> OptimalJ
- be sure to have markings available

Advantages of MDA:
- From his experience, MDA allows to shift most of the issues in an application from the boilerplate code towards the business code. It seems obvious, but it's always nice to have additional practical feedback.
- Development and/or project speedup (I guess it depends on the side of the project and the extent of the use of MDA).
- Consistent code: enforce architectural patterns
- more flexibility

Prerequisites:
- knowledge of the models / languages
- more tools, more learning curve
- creating templates is hard: garbage in == garbage out

In the end a quite conventional talk, yet interesting.

jeudi, juin 12, 2008

SpringOne08: Spring Web Services

Read the interesting (IMNSHO) bits below.

Spring Web Services is Contract-First.

Tools for contract infering from an xml instance:
Trang, XMLSpy, Microsoft XML to Schema (and an additional: Oxygen XML does that if I remember well). Why isn't there a java library for that (for use in IDEs and scripts)?

(Of course) contract first is really a good practice, and schemas (once you get to know them) are really a very expressive language for message content description.

New in Spring Web Services 1.5:
- JMS and Mail transports (a bit of overlap with Spring Integration... though this may merge sooner or later).
- WSS4J support (including client-side)
- WS-Addressing support
- OSGI Bundles

SpringOne08: Spring Integration

Great talk, great features, though you can find everything he presented on the site and blog entries.

I'll probably blog on this subject as soon as I give it a try.

mercredi, juin 11, 2008

SpringOne08: Spring Batch

This illustrates (and answers) a question I've always asked myself: Why shouldn't we code batch jobs in java...? In fact It's a lot more portable, testable and encapsulate-able than most of the usually used languages/platform nowadays.

Spring Batch 2.0 will be Java 5 ready.

Really interesting talk, yet already partly seen last year, and...I passed out a bit.

It seems that there is an underlying convergence between Spring Batch and Spring Integration (after all Batches are only integration operations that are longer or operate on larger sets of data, with a bit more requirements in the failure handling...)

SpringOne08: Security

Not Ben Alex, but let's not judge the speaker so fast ;)

Interesting demo showing a completely unsecured Spring-based (of course) application completely secured on the fly using Acegi...uh sorry Spring Security (I actually got used to Acegi ;)). Quite classical, but enhances the improvements in the configuration.

A few interesting things to know:
- new Spring 2.x namespace for lighter configuration.
- Only one filter: DelegatingFilterProxy with a filter chain behind.
- REST Support: you can specify the method (POST, PUT, DELETE...) in the intercept-url element.
- very nice ldap-user-service configuration... worth checking!!!
- Embedded Apache DS: very nice!
- easy to mix and match multiple schemes: OpenId for authentication, and JDBC for user details or NTML for Authentication and Active Directory for User details.

He mentions an interesting possibility: only testing the securisation of methods by completely removing the call to the underlying method. Sadly he doesn't go into details.

A nice practice also: securing based on permissions and not on roles. This is much better for further evolutions. Roles change, permissions less likely.

In the end (I knew a bit from the tests I did recently) Spring Security is an improvement in terms of useability, (if not in features, it keeps the plethora of features of the original), on Acegi.

SpringOne08: Persistence Optimizations

DBA-Developer relationship, try to improve it... ok... too bad DBAs are not there to here that ;)

Operational considerations:
- Data volumes, row sizes
- Growth estimates, update frequencies
- Availability requirements
- Testing/QA requirements

Guidelines:
- appropriate data types
- small rows
- split large tables with one-to-one table containing fewer used fields
- improve indexes
- normalize data
- partition data (if available)

Most important: application tuning:
- keep transactions short
- bulk processes => off-hours
- understand locking (on writes, on reads...escalation of row locks to table locks in case of many reads...)

ORM tuning:
- watch Criteria, no NULLS in the WHERE clause, they are not indexed
- like with % at the beginning: no index either
- pick an appropriate TransactionManager (only use XA when accessing JMS and database together)
- use READONLY, try to avoid SERIALIZABLE
- use lazy-loading
- use caching

JDBC Tuning:
- set the fetch size on connections (defaults to 10 for Oracle driver...) lessens the network roundtrips

Hibernate Tuning:
- use "select" fetch mode for relationships needed sometimes - results in 1 or 2 queries.
- use "join" fetch mode for relationships needed all the time (try to limit to one per object)
- use "batch-size" to prefetch a number of proxies and/or collections

Bulk operations:
- do it in the database to avoid network (SQL statement, stored procedure, native data load tools...)
- if you need to do it from the application: JdbcTemplate (batchUpdate), SimpleJdbcInsert (executeBatch), Spring Batch (BatchSqlUpdateItemWriter), Hibernate (set hibernate.jdbc.batch_size and flush and clear session after each batch)

SQL Tuning:
- Capture SQL
- Run EXPLAIN
- adjust: analyse, tweak optimizer, add index
- repeat until adequate performance
- ASK for help from your DBA ;)

OpenSource JDBC monitors:
- p6spy
- Elvyx
- JDBCSpy

Database specific tools:
- MySQL (slow query log with --log-slow-queries or --log-queries-not-using-indexes)
- Oracle: Enterprise Manager, Statspack
- Oracle XA: Monitor Top SQL

Interesting tips for Oracle:
- Use the call to a function setting the module name in Oracle in the validation query for the connection
- Use explain and autotrace in Oracle SQL Developer
- Use ANALYSE TABLE [table] COMPUTE STATISTICS
- Use ANALYSE INDEX [index] COMPUTE STATISTICS

Database Tuning:
- Memory (Global Area SGA, Session Area PGA)
- Disk (Block size, File placement)

Talks about a ProxyDatasource during Q&A. This seems to allow to transmit the credentials of the interactive user. Could be interesting for refactoring of legacy Oracle Forms applications.

SpringOne08: Spring 2.5 to Spring 3.0

This presentation talks about 2.5 and the future (3.0).

2.5 summary:
- 2.0 kernel so-to-say plus additional features.
- end of 1.3 support (who cares? ;););) )
- JDK 1.6 support: JDBC 4.0, JMX MXBeans (supports runtime snapshots)
- AspectJ load-time weaving (available in 2.0 but not mainstream as in 2.5) through a platform support or a generic Spring VM agent using <context:load-time-weaver />
- JEE 5.0 support (JPA support is improved, EclipseLink support) and all other JEE 5.0 APIs

A bit of details on 2.5:

JSR 250 Common Annotations:
Good: @PostConstruct, @PreDestroy
Bad: @Resource ;);) of course, this annotation is a bit limited (injects a resource from JNDI from a name in a setter or field)... yet a standard. Life is a bitch... though Spring allows using it without JNDI :).

Other annotations:
- @WebServiceRef/@EJB (should have been named @EJBRef... life is really a bitch)
- @TransactionAttribute (EJB 3 transaction demarcation... a bit limited)
- @PersistenceContext / @PersistenceUnit already supported in 2.0: JPA resource injection

@Autowired Spring annotation
- on fields, configuration methods, constructors
- nice sweet-spot between autowiring by type and autowiring by name: annotation-driven, less wild-guessing.
- @Qualifier allows to narrow the potential autowired components if multiple are available. This is also available in the xml syntax in beans. Qualifier can be a bean name or an annotation applied to a bean.

@Configurable with AspectJ
- classes can be weaved and may be created by using a simple "new" constructor call!
- using <context:load-time-weaver aspectj-weaving="on"/> and <context:spring-configured /> (and of course the appropriate class-loader/agent).

@Transactional with AspectJ
- using <context:load-time-weaver aspectj-weaving="on"/> and <tx:annotation-driven mode="aspectj" transaction-manager="......
- avoids creation of proxies by using load-time weaving.
- also works for private and protected methods, and for code from same component (common problem with proxies).

Annotated MVC:
- @Controller, @RequestMapping...etc (I already tested it, you should try it ;) )
- allows POJO Controllers for classic methods, or in portlets...

Test Context Framework:
- @ContextConfiguration, @TransactionConfiguration
- works with JUnit 4.4 (@RunWith(SpringJUnit4ClassRunner.class)) and TestNG
- no use of class hierarchies... nice and light ;) (a bit troubling though as the test almost contains anything except metadata....)

Recommandations:
- Option 1: XML-based configuration complemented with annotations.
- Option 2: more radical: Fully annotated components. (Not that much an XML hater... so it seems a bit over-strict)...
- Externalized configuration => XML
- Embedded configuration => Annotations
- Find the balance, and mix and match!!!

Spring 3.0 insights:
- Spring 2.5.5,2.5.6 up until July (OSGI refinements)
- Spring 3.0 RC1 (August)
- Spring 3.0 GA in Q4: Java 5 in the core (internal use of Generics and varargs), support of Portlet 2.0, preparation of Servlet 3.0, => REST support, EL support, conversational support...
- Backwards compatibility with removal of deprecated APIs.
Pruning and Deprecation:
-prune: Commons Attributes
-prune: Toplink (EclipseLink)
-deprecated: pre JDK 5.0 support

SpringOne08: Keynote

9h30, Keynote should start any minute.

First, the main local organizer of Spring One talks about his baby: Parleys. He shows off a very nice Flex-based UI. Flex is definitely nice, and what they've done with id also! Check for version 2 of Parleys very soon, it's great!

Rod Johnson:
A bit of commercial Blah... (sorry, but that's it... :P) though the content is quite relevant.
This quickly turns into a (little bit) more technical talk.
It also contains interesting bits that I didn't know of or have not yet tested:
- Use of qualifiers in Annotation and XML configuration
- support for Meta-Annotations (annotate annotations ;)) which allows to use your own meta-tagging for your component types and then annotate them with Spring Annotations , the org.springframework.stereotypes package also provides sensible defaults.
- Junit 4 support through specific runner (haven't had the opportunity to test it yet, but will indeed do it very soon!)

Spring Integration is mentionned there, and I think (see later in this post) that this may be very soon a very important Spring project...

Enters Keith Donald who talks about the web tier.
Interesting Javascript module... worth following...

Rod Johnson again:
Spring Powered applications: replaces more and more the JEE container.
Decoupling of business logic from deployment platform in terms of choice. (can be argued with their new server which relies a lot on Spring ;) ).
Obviously leads to Springsource Application Platform.

Christian Dupuis:
Nice presentation of STS. Should have been preceded by a SpringSource AP in-depth presentation.

Peter Cooper-Ellis, comes from BEA, and gives a little talk about his view of SpringSource and Spring.

Rod Johnson:
Predictions => most interesting: app server and ESB fusion (see Spring integration merging with Spring AP ;), it seems so obvious)

mardi, juin 10, 2008

Spring One minus One

Just to tell the few potential readers of this blog that I'll blog about Spring One the two coming days from Antwerpen, Belgium.