Wednesday, November 24, 2010

Yes, Troy McClure have read WCAG ;-)
The objective of this technique is to demonstrate how CSS can be used to replace structured HTML text with images of text in a way that makes it possible for users to view content according to their preferences. To use this technique, an author starts by creating an HTML page that uses semantic elements to mark up the structure of the page. The author then designs two or more stylesheets for that page. One stylesheet presents the HTML text as text and the second uses CSS features to replace some of the HTML text with images of text.
Where possible, authors should deliver the presentation that does not include images of text as the default presentation. In addition, the control used to switch should be located near the beginning of the page.
keep reading samples and:
The CSS for the presentation that includes images of text follows. Note that the CSS uses positioning to place the contents of the heading elements offscreen so that the text remains available to screen reader users.

P.S: Troy McClure: "He was a star in the early 1970s, but his career went downhill:..... I'm younger does not fit.
P.P.S: Sorry for quoting newer version 2. I know w3 does not like to promote it very much ;-)))

A better(????) way to author alternate text The real function of alternate text

I have read this
since it apeared in my twitter few days ago.

Pure bullshit ! Sorry folks. Image should be used for "Content"
and ALT should really represent content, so it SHOULD describe what is on the image.

For "trick" like heart image, button image etc...

we are talking about

alternate graphical representation for text
not alternate text representation of graphical image content.

So it is all wrong from the begining
from the very markup point of view.

Use any reasonable tag to encapsulate text and style it using CSS.
It can be ABBR if you text contains shortened form like heart pictogram,
or use A HREF if you want to link as well, STRONG,
or use SPAN in the worst case.


save the document by pressing <img alt="save button">


save the document by pressing <span class="img-as-text save-btn">save button</span>.

heart example would look like:

Tuesday, November 16, 2010


almost unbelievable
what someone is willing
to do for "rounded corners" ;-))

Monday, November 15, 2010

GWT real-world-projects and Validator

I tried to find out who is using GWT. Instead of writing
google dork which could show-up random lame implementors,
I have used offical chosen GWT showcase:

Lets see how they fit into w3.validaton:

Google Moderator = 11 Errors

Go Frid = 40 Errors, 18 warning(s)

Lombardi Blueprint = 28 Errors, 18 warning(s)

etc. etc...

So is it really so difficult to create GWT page passing w3 validation ? Or is it again just bad use of framework by "web ignorants" ?

P.S. No real analysis performed, sorry, no more time to waste tonight

Saturday, November 13, 2010

The Art & Science of JavaScript

The WORST book I have ordered and read this year !

Sorry for not being constructive and writing some detailed review, but I choose beer with friends instead.

Can not recomend unless you want to find what CUTTING-EDGE, INSPIRATIONAL and IMPRESSIVE and AMAZED is ment by sitepoint publisher.

Tuesday, October 19, 2010

Is eval evil ?

var tact = (eval("args.S_TACT") == undefined ? "" : "S_TACT=" + eval("args.S_TACT"));

In this case it is really evil, and dangerous !
specially if args is "somehow built" from document.URL

For those interested: code comes from big blue web site.

Friday, October 15, 2010


This computer program contains valuable, confidential and proprietary

IsUndefined = function (obj) { return (typeof obj == 'undefined'); }
IsNull = function (obj) { return (obj == null); }
IsValid = function (obj) { return (!IsNull(obj) && !IsUndefined(obj)); }

Sad but true

More "valuable" code can be found here:

Monday, October 11, 2010

VS2010 Code Snippets for Java Script

Just random notes about another "cool VS2010 feature"

"Visual Studio 2010 will include more than 200 built-in snippets
that you can immediately use when you install the product."

Excelent ;-) there are 13 "all useless" Java Script
snippets for basic lang constructs that hardly anyone needs
(if someone needs them I do not need her in my team)
including "deprecated with()" and "difficult to type alert()" ;-))

+ 5 incomplete XML Comments tags for VS2010 intellisence"
+ 3 MS Ajax snippets

Compared to easy creation of Toolbox items (drag and dropp)
the creation process of snippets
(XML file, edit, save, import etc..)
seems to be bit complicated if not unusable.

Snippet Designer
This helps with creation specially "extract snipped" context menu but still...
a lot of clicking to finish the snipped.
And if you make mistake (wrong language, wrong folder)
all gets complicated again.

After 30+ mins experimenting, I have managed to create this template
(it took me 5 minutes to press F4 and change properties ;-)))

What else we get with snippets ?

If your not convinced that saved you that many keystrokes, theres another handy feature. See how the first "i" is highlighted

and the second two are surrounded by dotted lines? That means that those variables are supposed to be the same - which mean

that if you edit the first "i" right after you insert the code snippet, the other "i"s change to the new name automatically.

That 'linkage' isn't kept around forever, as soon as you go and edit something other than the snippet, those dotted lines go

away and any changes that you make later on don't automatically get propagated. But pretty cool, eh?
Cool but quite useless for while and for cycles.. but keep reading

MSDN (Offical Docs)


a) type cnstr,TAB or cn,TAB,TAB and it will generate whole thing
b) change cnstr and p
and you have your own jQuery style construction pattern done.

After someone skilled creates template in 2-20 minutes
and ensures distribution of template to
"some sort of sharable location"
every "developer" can monkey type
and learn and memorize nothing.....

Next catch: Shortcut
This text is used as a shortcut for inserting the code snippet. The text value of a Shortcut element can only contain

alphanumeric characters, hyphens ( - ), and underscores ( _ ).

This is bug of code or bug of docs, if you name your shortcut with - or _
it will not work with TAB,TAB scenario.
It will be visisble in top level intellisence popup,
but will not expand.
So the best shortcut name to include some sort of namespacing is
hungarian notation as aitkCnstr, aitkModule, aitkSynchro etc...

So far...

I admit, this may be too quick experience but
i'm not impressed and I will love my "old memory" for obvious tasks
old fashion Toolbox + replace for more esoteric snippets.

I may write more when I learn more...

My first trial:

save somewhere to:
My Documents\Visual Studio 2010\Code Snippets\Visual Web Developer\My JScript Snippets\cnstr.snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="">
<CodeSnippet Format="1.0.0">
<Title>cnstr (jQuery style)</Title>
<Description>construction pattern ala jQuery</Description>
<Literal Editable="true">
<Literal Editable="true">
<Code Language="jscript" Kind="type decl"><![CDATA[(function (window, undef) {

function $cnstr$($p$) {
/// <param name="$p$" type="String"></param>
/// <returns type="$cnstr$" />
return new $cnstr$.prototype.$cnstr$($p$);

$cnstr$.prototype = {
$cnstr$: function ($p$) {
this.$p$ = $p$;
$cnstr$.prototype.$cnstr$.prototype = $cnstr$.prototype;

// exports
window.$cnstr$ = $cnstr$;

VS2010 Web Development (Code Only) Profile.

1. Java Script validation is turned off
2. HTML validation is turned off

I do not know what MS calls web development,
but for me it is JS, HTML, and CSS....
Also Error List and other windows must be opened manually.
I do not like this "damned default",
so if hou click CTRL+SHIFT+J as mad
and no errors (you sure have some) appear in your Error List
now you know why.

Comming soon:
detailed compare of profile settings,
and maybe exported setting for
more realistic web code only development.

Friday, October 8, 2010

Fast and correct htmlEncoding for JavaScript

Feel free to adjust two last matches in the regexp to any of your needs. I encode all > 0x07 and from allowed ascii, I encode only big 5. Using regexp is still faster (specially on MSIE) than any other impl. var _encodeHtmlRegExpImpl = (function() { // performance is 78ms on MSIE 7 (the slowest one) // on 80KB html markup from: var re = new RegExp( // surrogate pair (sp) "([\uD800-\uDBFF][\uDC00-\uDFFF])" + // html UNUSED including standalone surogates (un) "|([\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\uD800-\uDFFF])" + // out of ascii (oa) "|([^\u0000-\u007F])" + // big 5 + add others (b5) "|([\u0022\u0026\u0027\u003C\u003E])", "g" ), toCodePoint = function(high, low) { return ((high - 0xD800) << 10) + (low - 0xDC00) + 0x010000; }, enc = function(m, sp, un, oa, b5) { // extracted out from main function and ifs changed to ternary // thanx to Andrea Giammarchi return "&#" + (oa || b5 ? m.charCodeAt(0) : (un ? "xFFFD" : toCodePoint(m.charCodeAt(0), m.charCodeAt(1)))) + ";"; }; return function(s) { return s.replace(re, enc); } } ());

Monday, September 27, 2010

org/owasp/esapi/codecs/ (is it really correct ?)


After reply from jwilliams, I have almost apologized for arogancy...
but...I gues jwilliams is the same person, that coded this:
@author Jeff Williams

I have spent some more time to tune my implementation,
and to figure out what the OWASps HTMLEntityCodec does,
since the jwilliams comment did not match what I have saw in his code:

I have tested against ESAPI-2.0-rc6
the primitive code

return ESAPI.encoder().encodeForHTML(in);

This is what gets encoded (all green are "encoded somehow")

and please see HTML source code
for what is produced in markup !

So basically what you have posted as comment
is SOMETHING ELSE as YOUR code does:
Your post:
1) Encoding characters > 255 isn't useful, barring games with the character set.
2) There is no security problem with rendering named entities, although ESAPI uses hex entities to help performance.
3) Nobody is immune to charset switching
4) It's dangerous to remove characters entirely, you should replace with u+FFFD

What I think:
1) but you ARE encoding > 255, and incorrectly.
You ARE using ALSO, NAMED entities, not hex ! (and for huge ranges),
you print out standalone surrogates as hex which is error and violation of SGML def of HTML,
and correct surrage pairs are encoded as two hex codes instead of one hex int
2) esapi uses NAMED as well for wide range of chars !
3) no comment yet waiting for explanation
4) You are NOT using u+FFFD but whitespace " "

So please if I'm wrong "again", correct me but I do not want to waste ANY more time with
fixing external api,
I will stick to my fixed code,
and I warn the others to make their own versions as well (or use better code than OWASPs RI).

Please update DOCS to make things clear, if this is intended encoding and
OWASP considers this as safe, I will skip the libs just by reading docs, and
save some time on communication and testings.

Final Note ?

I hope this can open eyes a bit:

public static void main(String[] args) {
EscapeUtils2 eu=new EscapeUtils2();
String s1="<>abc123+-";
String s2=new String(new int[]{0xdc00,65823,65839,65855},0,4);

with ESAPI gou get:

extra encoded + sign
&#xdc00 entity outputed (should not apear in HTML !!! by specification)
and 3 more &#xd800 entities (should not apear in HTML !!! by specification),
which happens because SMP should be encode(codePoint) not encode(char)+encode(char).

+ with my code you get all strange data situations logged:
27.9.2010 13:35:43 EscapeUtils2 log
WARNING: UNUSED DESCSET: codePoint=56320 at index:10
27.9.2010 13:35:43 EscapeUtils2 log
WARNING: SMP: codePoint=65823 at index:11
27.9.2010 13:35:43 EscapeUtils2 log
WARNING: SMP: codePoint=65839 at index:13
27.9.2010 13:35:43 EscapeUtils2 log
WARNING: SMP: codePoint=65855 at index:15

I do not expect that my data will contain SMPs or unpaired surrogates. But at least if they do, I produce correct markup.

Thursday, September 23, 2010

OWASP has deleted How_to_perform_HTML_entity_encoding_in_Java

I have fixed this "naive article" back in spring 2009
an it contained my proposal for "HTML encoding".

Week ago I have discovered mistake in my code:
2 chars which I should exclude from output
where not excluded and outputed as encoded.

I wanted to update the alg on the web and surprise:
HTML Entity Encoding is not enough to stop XSS in web applications. Please see

XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet for more information.

So let's see what is the OWASPS update ?
Article named: XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet.

Why Can't I Just HTML Entity Encode Untrusted Data?
HTML entity encoding is okay for untrusted data that you put in the body of the HTML document, such as inside a div tag. It
even sort of works for untrusted data that goes into attributes, particularly if you're religious about using quotes around
your attributes. But HTML entity encoding doesn't work if you're putting untrusted data inside a script tag anywhere, or an
event handler attribute like onmouseover, or inside CSS, or in a URL. So even if you use an HTML entity encoding method
everywhere, you are still most likely vulnerable to XSS. You MUST use the escape syntax for the part of the HTML document
you're putting untrusted data into. That's what the rules below are all about.
Ok it covers more in one place, excelent....
introduces "terms" like "HTML Escape" or "Attribute Escape"....
and no surprise it is strong propagation of
ESAPI and ESAPI reference implementation.


Check code here:

latest version of mine "pseudo-code"
still kept inside owasps wiki history.

compare and decide .....

Mine works for "Supplementary Multilingual Plane"
uses only
Numeric character references not Character entity references.

and it's imune to client charset swithing..

Probably we will here more about ESAPI, since they "amuse and scare me" more and more every day....
BUG FIX: Two extra chars to remove are 0b 0c. (swich ifs or add extra if else line). Sorry....

string.replace with function benchmarks

function escapeRegExp(s) {
return s.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
function escapeRegExp_asFunction(s) {
return s.replace(/([-.*+?^${}()|[\]\/\\])/g, function(ch) {
return "\\" + ch;

Test case:

var loops = 10000,
s1 = "abcdefgjklmnoprstuvxyz",
s2 = "-.*+?^${}()|[]/\\",
s3 = "a-a.a*a+a?a^a$a{a}a(a)a|a[a]a/a\\a",
testStrings = [s1, s2, s3];

MSIE 7.0 results



Using function as second parameter in replace is at least:

796/125 ~= 6 times slower than the first one on MSIE a
173/48 ~= 3 times slower on FF
77/61 ~= same speed on Safari !!!

on test string with half matched chars.

Tuesday, September 14, 2010

isArray, optimized ?

isArray optimized ?

The world has almost agreed that this is
correct check for Array in JavaScript.

var toString = Object.prototype.toString,
isArray: function(obj) {
return === "[object Array]";

Similar checks are used for Date or Numbers.
For those who may not know why, read this excelent explanation by kangax:

instanceof considered harmful (or how to write a robust isArray)

I have been curios about performance:

100 000 loops !!! times in mils compare native naive checks and the correct one.

MSIE 7.0
a instanceof Array 63:true
a.constructor === Array 62:true == [object Array] 235:true

a instanceof Array 12:true
a.constructor === Array 41:true == [object Array] 51:true

a instanceof Array 2:true
a.constructor === Array 5:true == [object Array] 41:true

MSIE 7.0 is the slowest and penalty is >4 all browsers.

Again this is of course nothing in absolute numbers,
since we are talking about 100000 loops here !

Speedup for false checks

The penalty and measured times are "the same"
even if you pass null or undefined inside.

Since I use this method
often on attribute normalization
at the begining of my functions,
and many times the checked attribute is optional
(null, undefined or even "")

I propose small speed up with this code:

var toString = Object.prototype.toString,
isArray: function(obj) {
return (object!=null && === "[object Array]");

Yes the "evel twin" is intentional.
or even with

var toString = Object.prototype.toString,
isArray: function(obj) {
return (!!object && === "[object Array]");

Of course you pay some extra penalty for this (20ms/100000 loops on MSIE) in positive checks,
but it drops down false checks to almost no cost (31ms/100000 loops).
BTW do we need === to compare strings ?

arrLit == [object Array] 219:true:[object Array]
arrLit optimized 234:true:[object Array]

null == [object Array] 203:false:[object Object]
null optimized 31:false:[object Object]

You see the extra price on positive call 219 vs 234 and spped up 203 vs 31!
on null input

Of course you can still write the code outside of isArray
in each code where it makes sence
but I like it inside - optimized.

I see no sence to let null be converted to
[object Window] (on FF) and compared as string with [Object Array].

Tuesday, September 7, 2010

VS 2008, ASP.NET Development Server, .xslt vs .xsl filename extension

MS VS 2008, .xslt vs .xsl filename extension

Add New Item "Wizard" generates by default .xslt extension. The file is then served by magic cassini (ASP.NET Development Server) when testing locally.

All works fine until you try to load xslt file with XMLHttpRequest.
Cassini sends incorrect Content-Type:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/
Date: Tue, 07 Sep 2010 13:02:40 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: application/octet-stream
Content-Length: 347
Connection: Close

and of course XHR (correctly) fails to provide xhr.responseXml property.

How can you configure ASP.NET Development Server or .NET web application to serve "correct Content-Type"?
What is the "correct Content-Type" anyway ?
Will be XHR capable to read this "correct Content-Type" (XB of course)?

Thanx for one nice default
inconsistent with another one.

Because of using
twisted version of XHR
and MSIE 7.0 it was hard to spot.

Solution ?

Use .xsl instead of .xslt.
ASP.NET Development Server servres them with text/xml Content-Type which seems to work ;-)

Thursday, September 2, 2010

JSLints and evil twins == (again)

This time I have used JSLint to recheck and possibly
polish some of my older sourcecodes:

As expected JSLint gave me
several messages

Problem at line 3 character 5: Expected '===' and instead saw '=='.

I decided to turn it off with /*jslint eqeqeq: false*/
and surpise... only SOME of the messages disapeared.

Try this:

1./*jslint eqeqeq: true*/
4. if(a==b){}

result (expected):

Problem at line 2 character 5: Expected '===' and instead saw '=='.
Problem at line 3 character 5: Expected '===' and instead saw '=='.
Problem at line 4 character 5: Expected '===' and instead saw '=='.
Implied global: a 2,3,4, b 4

all 3 lines reported as error.

Now try to turn it off:

/*jslint eqeqeq: false*/

Only the last line is not reported any more, first two are still considered harmfull:

Problem at line 2 character 5: Use '===' to compare with 'undefined'.
Problem at line 3 character 5: Use '===' to compare with 'null'.
Implied global: a 2,3,4, b 4

Why do I care ?

From habit (maybe very wrong one)
I use construction:

if(arg3 == null)
if(arg3 != null)

bacause IMHO this is valid:


To simplyfy ifing for both undefined and null values
Otherwise I would have to write:

if(arg3 === null || typeof arg3 !== "undefined")
if(arg3 === null || arg3 === undefined)

with second option I use known trick,
"elimination of evil global undefined"
BTW: also used by jQuery:
(function( window, undefined ) {


Trying this

/*jslint eqeqeq: false*/
(function(undefined) {

with JSLint you get:

Problem at line 2 character 11: Expected an identifier and instead saw 'undefined' (a reserved word).
(function(undefined) {
Problem at line 3 character 9: Use '===' to compare with 'undefined'.
Implied global: a 3

Solution ?

Can anyone tell me how to turn off JSLint ==
In the way it ignores all not only some constructions ?

Can anyone tell me how to make effective and simple if
which returns true only for "null and undefined" and false for all other values ?
Suggestion by Mr.D on his page
If you only care that a value is truthy or falsy, then use the short form. Instead of
(foo != 0)
just say
is not and option because we are latking about specified or valid (0, false) and uspecified or invalid (null,undefined) here...

Or shell I rewrite all my ifs from if(a!=null) into strange looking:

/*jslint eqeqeq: false*/
(function(undef) {

Thanx in advance....

Try also my favorite blogger at:

Update: 2011/06/07

It seems that current version Edition 2011-07-01
works fine for all 3 cases and works correctly for null and undefined as well:

1./*jslint eqeqeq: true*/
4. if(a==b){}

Tuesday, August 31, 2010

org.owasp.esapi.encodeForURL (shocked again)

My quick look at OWASP ESAPI-2.0-rc6 again

java.lang.String encodeForURL(java.lang.String input) throws EncodingException
Encode for use in a URL. This method performs URL encoding on the entire string.

For the docs the "URL encoding" is defined by referencing wikipedia !
Don't we have RFCs for this ?

Being curious what it really does ? Look in the code:


What ? Read JavaDoc !
Translates a string into application/x-www-form-urlencoded format.
This is not ment for building URLs but for encoding form data !
There is another JavaDoc:
The URLEncoder and URLDecoder classes can also be used,
but only for HTML form encoding,
which is not the same as the encoding scheme defined in RFC2396.
And another one:
The recommended way to manage the encoding and decoding of URLs is to use URI

Reading URI docs you will learn about all deviations Java has from RFC2396.

The OWASP JavaScript version of "the same" is even "better"
(I bet a beer, not producing the same results as Java code):

encodeForURL: function(sInput) {
return !sInput ? null : escape(sInput);

Reading MDC docs:
escape and unescape Functions
The escape and unescape functions do not work properly for non-ASCII characters
and have been deprecated. In JavaScript 1.5

and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.

Bad naming or ignorance ?

There is just small chance that authors realy ment to code
"HTML form encoding" and not to solve URI building and encoding,
and that the method has just a bad name. I would suggest Encoder.encodeForHtmlForm
instead of misleading encodeForURL with even more confisung wiki link !

In the case OWASP really ment to solve
encoding for URI or http scheme URLs, there should be totaly
another code behind !!!!

If you really plan to encode URI components there is API needed to
encode path, path-segment, query, fragment with separate rules defined by
RFC (and I vote for the "new rfc3986" instead of buggy java implementation of old "RFC2396").

If you code or find rfc3986 compliant java uri implementation,
let me know,
until then I will not

Strong suggestion again: search for "Jena IRI".

Wednesday, August 25, 2010

request.getRequestDispatcher vs servletContext.getRequestDispatcher

ServletRequest.getRequestDispatcher(String path)

The pathname specified may be relative,
although it cannot extend outside the current servlet context.
If the path begins with a "/" it is interpreted as relative to the current context root.
If it is relative, it must be relative against the current servlet

ServletContext.getRequestDispatcher(String path)

The pathname must begin with a "/" and
is interpreted as relative to the current context root.
Use getContext to obtain a RequestDispatcher
for resources in foreign contexts.

Basic difference is that

request.getRequestDispatcher allows for relative paths.
Relative to what ?

relative path as coincidence

If the servlet (let's call him B) is accessible using only one URI (/ctx/B)
that seems to be easy answer.
Event if mapped with with url-pattern /path/B,
most containers are "trailing slash ignorant" and your servlet will be accessible with
both /ctx/path/B and /ctx/path/B/ variants.
With the same code in servlet:
request.getRequestDispatcher("../c.jspx").include(request, response);
you will get two different results of course,
/ctx/c.jsp and /ctx/path/c.jspx
one of them will end up with null pointer of course.

Usually using realtive path is coincidence and not design decision.

relative path as design

But wait "relative path" can be used as intentional design:

Imagine that the same servlet is accessible using

/f/g/h/ mappings

and based on the requested uri you want to include different view (c.jspx).
If the view exists in the relative location use it, otherwise use predefined global view.

// get view on current level

Reative Path - Double dispatch

what if b is already dispathed.
If the call goes througn A to B and the to C.
What "it must be relative against the current servlet" means ?
(test your self on several containers, reading specs is not enough for this case ;-))

My suggestion

getServletContext().getRequestDispatcher() and /contextRelativePath

request.getRequestDispatcher and relativePath

Otherwise you code may
not be movable up and down in web hierarchy withou moving views,
not work when mapped to different level URIs" without duplicating views,
and probably will suffer from container's trailing slash ignoracy.

Use realtivePaths only "as design not as coincidence",
and always document relative path dependencies in your servlet documentation.

Friday, August 20, 2010

HTTP Trace method and Query

Should the first line of trace echo the query string or not ?
Or is it up to container (web server ?)

WAS, TOMCAT, WLS all return trace without the query string
so if you browse


server responds with:

TRACE http://localhost/path HTTP/1.1

But I have seen containers returning

TRACE http://localhost/path?query HTTP/1.1

Any ideas why someone does not want to echo query ?

.href or setAttribute("href") in MSIE "sometimes" overrides the link text

Call to .href or setAttribute("href") in MSIE "sometimes" overrides the link text

If the text link contains ..@.. (hard to say exactly).
However MSIE DOES NOT override
the text if A tag contains other elements.

jQuery.attr does not solve the problem (or I use wrong API ?)

Proposed detection:

var supports = new (function() {
var a = document.createElement("a");
t = a.innerHTML = "a@a";
a.href = "http://msie";
this.aTextHrefOverride = (a.innerHTML != t);

Proposed solution:

var setAttributeHref = !supports.aTextHrefOverride ? function(that, value) { that.setAttribute("href", value); } : function(that, value) {
var t1 = getTextContent(that), t2;
that.setAttribute("href", value);
if ((t2 = getTextContent(that)) != t1) {
// asrt(has only text child no element childs);
setTextContent(that, t1);

getTextContent, setTextContent are XB helpers over .text and .textContent

TODo: lets check the dom-deviations

Wednesday, August 11, 2010

Expression Language, Conditional Operator , WebLogic Tomcat incompatibility problem

Web logic server requires extra whitespaces in this situation:


Apache Tomcat/6.0.28 - works fine
WebLogic Server fails with

weblogic.servlet.jsp.CompilationException: Failed to compile JSP /RequestUrl.jspx
RequestUrl.jspx:44:50: Syntax error in expression. Encountered ":r". Expected one of ...

WLS requires extra space after :

<td>${fn:escapeXml(r.queryString==null?'null': r.queryString)}</td>

//TODO: check grammar in specs .... please
//JSP.2.3.8 Conditional Operator - A ? B : C
//and find out who is right or wrong.

Tuesday, August 10, 2010

Raw reflection vs java.beans.Expression

I have been just curious if java.beans.Expression and java.beans.Statement
are just convenience APIs over raw reflection APIs
or if those classes really bring up some "performance" or other boost.

First testcase:

java beans API:

String s1=(String)(new Expression(b1,"method1",args)).getValue()

raw reflection:

String s2=(String)b1.getClass().getMethod("method1",new Class[]{Date.class}).invoke(b1,args);

"Cached reflected method":

Method m=b1.getClass().getMethod("method1",new Class[]{Date.class});
String s3=(String)m.invoke(b1,args);


360 [100000,loops,ms]
238 [100000,loops,ms]
105 [100000,loops,ms]

java.beans api seems to be the slowest.
Even if Expression is designed with statefull API,
which provokes "the intend to reuse same Expression object"
and change only arguments for example and keep target and method the same,
the Statement.invoke() code
seems to do all reflection work again and again
without any optimization and many extra ifs.

Just Another useless testcase for
standardized and useless convenience API ?

Here is the
list of bugs reported by to

"RowSet Wrapper List Strategy" and reality

"RowSet Wrapper List Strategy" and reality....

From Core J2EE Patterns: Best Practices and Design Strategies.

While the Transfer Object Collection strategy is one way to implement your finder methods,it might prove expensive if the query returns a large set of results and you end up creating a large collection of transfer objects, which are used sparingly by the client. Clients typically search and use the first few result items and discard the rest. When an application is executing a query that returns a large set of results, the RowSet Wrapper List strategy might be more efficient though it requires additional work and adds more complexity.

Code presented in the book is focused on RowSet wrapper and the code has 61+73 lines just as sample, and is
suitable only for RowSets. Get the book, read the samples, it is nice reading. However:

Using generics and AbstractList we can rewrite the original to 20lines long
"General Wrapper List" implementation, capable to transform any List<O> into List<E> by supplied convert method.

import java.util.AbstractList;
import java.util.List;

public abstract class WrappedList<O, E> extends AbstractList<E> {
public abstract E convert(O original);
private List<? extends O> original;
public WrappedList(List<? extends O> original) {
this.original = original;
// TODO: defensive copy ?, performance will suffer,
// and here we code for performance
// this.original=new ArrayList<O>(original);
public E get(int index) {
// TODO: caching ?
return this.convert(original.get(index));
public int size() {
return original.size();

This code has the same "quality" as the one presented in the book, and creates:
unmodifiable list (unexpected that view modifies list) which is
indirectly mutable (for sake of performance we do not make defensive copy of supplied original list),
that produce not equals (!=) instances with subsequent get(index) for the same index.

Using this to produce RowSet Wrapperfrom book, requires subclasing (anonymous inner class)
and this extra code (from book):

21 public Object get(int index) {
22 try {
23 rowSet.absolute(index);
24 } catch (SQLException anException) {
25 // handle exception
26 }
27 // create a new transfer object and return
28 return
29 TORowMapper.createCustomerTO(this);
30 }

moved to overrided convert method.

This way we have implemented optimized collection suitable to be used inside
c:forEach or jsf:table tags supporting start and end attribues.

Imagine situation where you have 1000 records from model and need to view only 10 of them.

<c:forEach items="${list}" var="l" begin="0" end="9">....

If list is constructed with the usuall "Value Object Collection" (copy and transform all)
it caouses 1000 calls to convert instances
of Value Object of type O into Value Objects of type E,
and creates 1000 of new instances of E.
In out case only 10 calls will be made and 10 new objects will be created.


<c:forEach items="${list}" var="l" begin="10" end="19">....

I would expect 10 again. But wrong it is 20 !.

<c:forEach items="${list}" var="l" begin="990" end="999">....

Will be 1000.

Thanx for clever code inside javax.servlet.jsp.jstl.core.LoopTagSupport.

Another idea of "too early full copy" arrays can be found here:


Even if you try to design with performance in mind,
even if you try to design by patterns and strategies,
choice of other libraries can eliminate
or even negate your efford.

Maybe, we will fix this soon, stay tuned.

Monday, August 9, 2010

Beware, my lovely specs

SRV.2.3.2 Initialization
After the servlet object is instantiated, the container must initialize the servlet before
it can handle requests from clients. Initialization is provided so that a servlet can
read persistent configuration data, initialize costly resources (such as JDBC API based
and perform other one-time activities.

SRV. Multithreading Issues
A servlet container may send concurrent requests through the service method of
the servlet. To handle the requests, the Servlet Developer must make adequate provisions
for concurrent processing with multiple threads in the service method.
Although it is not recommended, an alternative for the Developer is to implement
the SingleThreadModel interface

EE.4.2.3Transactions and Threads
In web components not implementing SingleThreadModel,
transactional resource objects
should not be stored in class instance fields,
and should be acquired and released within the same invocation of the service method.

I do not understand what "initialize JDBC connection means" or the first suggestion is just excelent antisample ;-))

Quote of the day

Enhancing productivity without compromising architectural principles. Without adequate
infrastructure it is tempting to cut corners by adopting quick, hacky solutions that will cause
ongoing problems. Appropriate infrastructure should encourage and facilitate the application of
sound design principles.

Credits for this one go to Rod Johnson and his work:

This sentence can be used in many of my post from now ;-) Thanx for inspiration.

Thursday, August 5, 2010

${}, fmt:message and fn:escapeXml

As expected ${exp} nor fmt:message
DO NOT PERFORM xml escaping.

99% of mine usage of both is to produce texts (text elements, or attribute values).
Only 1% of mine situations contain markup inside "exp" expression.

As EL values come from various and 99% enescaped sources (params,resources, db...)
I have to use c:out or fn:escapeXml over and over which enlarges the source code,
and creates unnecesary mess.

This is very sad, and I would like to propose new $$ operator for EL
which I would like to use as default,
(shall I implement this my self ? How ? When ? Where ?)
or I have missed some trivial trick ?

The hope for declarative tag based markup, disapears soon with my paranoid escaping of output:

<fmt:setBundle var="localizationContext" basename="tags" />
<c:set var="bundle" value="${localizationContext.resourceBundle}" />

<fmt:message bundle="${localizationContext}" key="fileTable.lastModified" var="strLastModified"/>
<c:out value="${strLastModified}"/>

the last two lines hurt my eyes,
and polute pageScope with useless variable,
so I tend to rewrite it soon into:


Apart from losing the declarative beauty, I have no clue about runtime consequences ;-) I have to read, thing and reverse engineer maybe a bit.

Please is anyone willing to educate me ?


just stupid design,
since it MUST have value attribute.

Only when value is null, the body is processed.

<c:out value="${null}">
<fmt:message bundle="${localizationContext}" key="parametrized.markup">
<fmt:param value="${bundle['namespaced.markup']}"/>
<fmt:param value="${fn:escapeXml(bundle['namespaced.markup'])}"/>
<!-- probably wrong, double escaping -->

This can save us from exporting strLastModified.

But, how do you specify null in EL ?
After reading specs again I have found
NullLiteral ::= 'null'

Look at MS ideas here:

Wednesday, August 4, 2010

Can this be any worse ?

Can this be any worse ?

if (!Array.prototype.containsKey) {
Array.prototype.containsKey = function(srch) {
for ( var key in this ) {
if ( key.toLowerCase() == srch.toLowerCase() ) {
return true;
return false;
var getNamedEntity = function(input) {
var entity = '';
while (input.hasNext()) {
var c = input.peek();
if (c.match(/[A-Za-z]/)) {
entity += c;;
if (entityToCharacterMap.containsKey('&' + entity)) {
if (input.peek(';'));
} else if (c == ';') {;
} else {

return String.fromCharCode(entityToCharacterMap.getCaseInsensitive('&' + entity));
var entityToCharacterMap = [];
entityToCharacterMap["""] = "34"; /* 34 : quotation mark */
entityToCharacterMap["&"] = "38"; /* 38 : ampersand */
entityToCharacterMap["<"] = "60"; /* 60 : less-than sign */
entityToCharacterMap[">"] = "62"; /* 62 : greater-than sign */

Let's make contest ;-)
How many "bad practices" (cannot find other polite word)
can you "spot" in this code ?

Monday, August 2, 2010

"Interesting project" - owasp-esapi-js

Just to keep in touch with some security topics, I have downloaded latest code of OWASP ESAPi for Java
and JavaScript today.
I'm bloging about the JavaScript part today.

This is the quote from original site (if you do not know OWASp and/or ESAPI:
The purpose of the ESAPI is to provide a simple interface that provides all the security functions a developer is likely to need in a clear, consistent, and easy to use way. The ESAPI architecture is very simple, just a collection of classes that encapsulate the key security operations most applications need.

Just the first look is shocking:

the esapi.js
does not use closure to hide it's internal functions,
pulutes global space,
modifies Array and String prototypes,
uses bad uncompressable techniques,
unefficient constructs,
and ...
is "unsecure" and "destructive".

Unsecure can be shown here:

if (!Array.prototype.each) {
Array.prototype.each = function(fIterator) {
if (typeof fIterator != 'function') {
throw 'Illegal Argument for Array.each';

for (var i = 0; i < this.length; i ++) {

What is the purpose of the if here ? If already defined, use the defined function
override otherwise. Defined by who ?

Browser ? As far as I hnow, none JavaScript version supports Array.prototype.each
(there si forEach in JS 1.6)
Other library ? How trusted ?
Or injected poisoned version of XSSed script ?

This method and others constructed in the same style are then used in subsequent
"security APIs".

Destructive means:

var $type = function( oVar, oType ) {
if ( !oVar instanceof oType ) {
throw new SyntaxError();

In global scope of course.

Those two are ultimately candidates for criticism, specially in "security related library".

The rest of the code which is not big (3000 lines including spaces and comments),
shows quite inconsistent coding style,
and lack of professional Java Script knowledge.

So much for now, I will have deeper look later,
but I'm not impressed.

"Shame of OWASP label"

Eclipse and JSP Validation rtexprvalue

Sometimes the ment for RAD slows you down.
Specially if not implemented by specs:

<jsp:directive.attribute name="title"/>

<l:holy-grail-no-quirks-mode title="${param.title}">

"title" does not support runtime expressions holy-grail-no-quirks-mode.jspx

Read the docs (jsp-2_0-fr-spec.pdf, Table JSP.8-3 Details of attribute directive attributes):
rtexprvalue (optional) Whether the attribute’s value may be dynamically
calculated at runtime by a scriptlet expression.Unlike the
corresponding TLD element, this attribute defaults to true.

Fix: you have to type extra chars if you want this warning to disapear:
<jsp:directive.attribute name="title" rtexprvalue="true"/>

Already registered ;-(

Pure JSP templating

Here is small proposal for templating using just basic
JSP techniques (no Struts Tiles, JSF nor Facelets needed).
It uses JSP Tag Files to implement the "template (tag)".

Layout is inspired by my favorite

And war file with all 3 files *tag, sample and css) can be downloaded from my web site:

Any comments and imrovements are welcomed.

Thursday, July 29, 2010

<c:url> DANGER !

<c:url value="/foobar.jspx#fragment">
<c:param name="p1" value="v1" />
<c:param name="p2" value="v2" />

fragment is not recognized as fragment and taken as part of path:


JSTL Specification 7.5 for c:url
reffers to old
JSP 1.2 in JSP.2.2.1 "Relative URL Specification"
which refers to old RFC
Elements may use relative URL specifications, called “URI paths” in the Servlet
2.3 specification. These paths are as described in the RFC 2396 specification.
So it becomes very unclear
if the value can contain fragments and/or query.

I vote for YES it can, even if the JSTL would want to advocate NO,
as I developer I would request it.

Tested on Suns jstl-impl-1.2.jar, Tomcat 6.0,
and after decompilation and quick look in the code,
I have strong suggestion

DO NOT USE !!!!!
it is dangerous and combined with lax EL, it can lead to
serious "security troubles" (search CWE, OWASP or others).

I will post fixed reliable version of
ainthek:url when ported from my other libraries.
And it will use IRI (I have not found anything better so far).

OEPE, Eclipse helios & NoSuchMethodError at creating new WLS server

Here are some news from my friend:

Some theory first:
In order to have Oracle WebLogic Server 11gR1 PatchSet 2 (latest) runtime environment in Eclipse helios,
you need to have server adapter in your IDE for that.
We still think the best way to do this is through “Oracle Enterprise Pack for Eclipse” where this adapter is included.

From this pack you only need this software:
Oracle WebLogic Server Tools
Oracle Common Tools (dependency)

You can do that by adding another update URL in Eclipse:
“Oracle Enterprise Pack for Eclipse -”

Oracle web site ( )
contains this note:
“Note: Be aware that Eclipse 3.6 Helios is not final and this tech preview is based on the M6 milestone release of Eclipse 3.6.”

True. When you download latest eclipse it’s M7 milestone (from April 30, 2010).
Milestone M6 was API Freeze and latest M7 is Feature Freeze, Focus on Performance and Polish.

IMHO M7 is final 3.6 milestone.

Now to the point: when you try to add awesome WLS in latest Eclipse you will get nice server error

From Error log:

at org.eclipse.wst.server.ui.internal.wizard.TaskWizard.performFinish(
at org.eclipse.jface.wizard.WizardDialog.finishPressed(
at org.eclipse.jface.wizard.WizardDialog.buttonPressed(
at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(
at org.eclipse.swt.widgets.TypedListener.handleEvent(
at org.eclipse.swt.widgets.EventTable.sendEvent(
at org.eclipse.swt.widgets.Widget.sendEvent(
at org.eclipse.swt.widgets.Display.runDeferredEvents(
at org.eclipse.swt.widgets.Display.readAndDispatch(
at org.eclipse.jface.window.Window.runEventLoop(
at org.eclipse.jface.action.Action.runWithEvent(
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(
at org.eclipse.jface.action.ActionContributionItem.access$2(
at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(
at org.eclipse.swt.widgets.EventTable.sendEvent(
at org.eclipse.swt.widgets.Widget.sendEvent(
at org.eclipse.swt.widgets.Display.runDeferredEvents(
at org.eclipse.swt.widgets.Display.readAndDispatch(
at org.eclipse.ui.internal.Workbench.runEventLoop(
at org.eclipse.ui.internal.Workbench.runUI(
at org.eclipse.ui.internal.Workbench.access$4(
at org.eclipse.ui.internal.Workbench$
at org.eclipse.core.databinding.observable.Realm.runWithDefault(
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(
at org.eclipse.ui.internal.ide.application.IDEApplication.start(
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(
at org.eclipse.equinox.launcher.Main.basicRun(
Caused by: java.lang.NoSuchMethodError: org.eclipse.wst.server.core.internal.UpdateServerJob.<init>(Lorg/eclipse/wst/server/core/IServer;)V
at org.eclipse.wst.server.core.internal.ResourceManager.fireServerEvent(
at org.eclipse.wst.server.core.internal.ResourceManager.registerServer(
at org.eclipse.wst.server.core.internal.ResourceManager.addServer(
at org.eclipse.wst.server.core.internal.Server.saveToMetadata(
at org.eclipse.wst.server.core.internal.Base.doSave(
at org.eclipse.wst.server.core.internal.Server.doSave(
at org.eclipse.wst.server.ui.internal.wizard.WizardTaskUtil.tempSaveServer(
at org.eclipse.wst.server.ui.internal.wizard.WizardTaskUtil$4.performFinish(
at org.eclipse.wst.server.ui.internal.wizard.TaskWizard.executeTask(
at org.eclipse.wst.server.ui.internal.wizard.TaskWizard$
at org.eclipse.jface.operation.ModalContext$

That is because underlying eclipse implementation had changed.
You see that signature?

It’s initialize method from UpdateServerJob class that returns void and takes IServer as an argument.

When you decompile latest M7 UpdateServerJob.class there really is no such method. It has only constructor that takes IServer array!

public UpdateServerJob(IServer servers2[])
servers = servers2;

And WlsUiPlugin$1 calls it with

public void serverAdded(IServer server)
if(WebLogicServerUtil.isWebLogicServer(server) && server.getServerState() == 0)
UpdateServerJob job = new UpdateServerJob(server);

Unfortunately that works for M6 version only. At that time UpdateServerJob constructor looked like this:
public UpdateServerJob(IServer server)
super(NLS.bind(Messages.jobUpdateServer, server.getName()), server);

Oracle developers, I think it is really a time to update your OEPE plugin because M7 is out there for 3 months now.
You have to change all calls of that constructor:
UpdateServerJob job = new UpdateServerJob(server);
UpdateServerJob job = new UpdateServerJob(new IServer[]{server});

Simple like that

This construction needs to be changed also in these files: -> package -> -> package -> WlsUiPlugin$ -> package ->

Or you can give us OEPE plugin sources and we will change it ourselves 


Decompiler info:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page:
// Decompiler options: packimports(3)

Bundled M6 (oepe-helios-all-in-one) eclipse plugin jar: org.eclipse.wst.server.core_1.1.202.v20100315.jar
Latest M7 eclipse plugin jar: org.eclipse.wst.server.core_1.1.202.v20100518.jar

OL snipped (valid HTML from your JSP components, PLEASE !)

many component authors are lazy to read HTML specification,
and lazy to write extra if in the code as well.
One of the examples is title tag absence in code generated by
myfaces components (see older posts).
Proposal for correct list rendering:

<c:if test="${!empty files}">

<c:forEach var="file" items="${files}">
<li><c:out value="${}"/></li>

The point is that OL without child LI is nonsence from HTML point of view.
Later we will talk about what element
to generate instead for empty list
and if null and empty is the same (EL does not care of course).

Wednesday, July 28, 2010

Fix For WST (Web Standard Toolkit) template

This is just sick ;-)

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="" version="2.0">
< language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />

<![CDATA[ <?xml version="1.0" encoding="UTF-8" ?> ]]>

<![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> ]]>

<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>


My proposed version is:

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="" version="2.0">
< language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
<jsp:output omit-xml-declaration="no" doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" />
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>


Do you think ther is a reason or just ignorance ?
Fist original WST code is buggy, outputed "XHTML" will have whitespaces before ?xml and whitespaces before doctype. (Authors, please read at least JSP.1.3.8 White Space) if not XML and HTML specs ;-))


somewhere from

Content-Type: text/html;charset=UTF-8
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<html xmlns:xhtml="">
<!-- *** powered by betterFORM, &copy; 2010 *** -->

Bug or feature ?

Monday, July 26, 2010

Oracle Web Tier Tools (OEPE)

Part of Oracle Enterprise Pack for Eclipse (OEPE)

I have commented on encoding issues in JDeveloper and today I have reached the same point in the Eclipse-OEPE environment.

First the good news is that OEPE let's you choose form many templates combining language (html,xhtml) of source markup, doctypes and final output doctype in
File/New/JSP Page/(Use JSP Template) and configure the templates the easy way
Window/Preferences/Web/JSP Files/Templates.

My chosen one the "New JavaServer Faces (JSF) Page (xhtml)"
will produce this:

<?xml version="1.0" encoding="${encoding}" ?>
<%@ page language="java" contentType="text/html; charset=${encoding}"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xmlns:f="" xmlns:h="">
<meta http-equiv="Content-Type" content="text/html; charset=${encoding}" />
<title>Insert title here</title>

What is the ${encoding} in this template ?

In per project scope it is
Project/Properties(ALT+Enter)/Resource/Text file encoding.
Select UTF-8 of course.

Next step is to customize the predefined templates to more resonable markup
but at least,
you have an easy chance to do so.
In jDeveloper I'm quite missing (or did not find) this EASY WAY.

not every template uses the ${encoding} param,
for example this one:
"JSP with xhtml markup, xml style syntax and default view setup"
has ISO-8859-1 (windows-1252 ?) hardcoded ;-(

Thursday, July 22, 2010

Trinidad JavaScript

Trinidad JavaScript

In short ?
Bad,obsolete,space consuming,sub-optimal .... practices,
in the order discovered.....
judged by my average JS knowledge....

  1. everything in global scope
  2. using new Array()
  3. var; var; var;
  4. Browser detection (sniffing)

  5. Useless chars eg: typeof (elem) == "string"
  6. ... this makes no sence to continue.....
TrUIUtils.createCallback = function(thisObj, func) {
 // create a function that sets up "this" and delegates all of the parameters
 // to the passed in function
 var proxyFunction = new Function(var f=arguments.callee; return f._func.apply(f._owner, arguments);");

 // attach ourselves as "this" to the created function
 proxyFunction._owner = thisObj;

 // attach function to delegate to
 proxyFunction._func = func;

 return proxyFunction;
TrUIUtils._cssToJs = function(prop) {
 var jsProp = '';
 var upperNext = false;
 for (var c = 0; c < prop.length; c++) {
  if (prop.charAt(c) == '-') {
   upperNext = true;

  if (upperNext) {
   jsProp += prop.charAt(c).toUpperCase();
  else {
   jsProp += prop.charAt(c);

  upperNext = false;
 return jsProp;
I had to stop after while... ... since this could be book of "JavaScript antisamples". I have no idea about the libs origin, they mention IE 4 versions, however Trinidad claim support to 6+, I belive a lot of code is "ported" from some other languages with little JS knowledge or care, or comes from aged libs written in the dark and deep web history. I have to quote Mr.D:
There are no good texts on JavaScript programming. Most of the people on the web who are producing JavaScript programs learned it by copying really bad examples from bad books, bad websites, and bad tools. We have an amazingly good community of JavaScript programmers here, but still we can benefit from better practice of style.

META and Content-Type and Wisdom of JDeveloper

g define:wizard (first hit)
someone who is dazzlingly skilled in any field

Ok then this already mentioned
"JDeveloper New JSF Page" wizard is not skilled in HTML .

In HTML which the wizard is claiming to produce (and twice !, by duplicated DOCTYPE ;-)
the META tag should not be closed (NET-enabling start-tag requires SHORTTAG YES).

However in .jspx (which is XML) you need to close it.

Simple workaround, that should work:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

BTW: why this meta is not part of trh:head rendering and must be specified manually in jspx markup ?

How many additional steps I have to do to produce valid HTML with these RAD tools ?

HeadRenderer (org.apache.myfaces.trinidadinternal.renderkit.core.xhtml)

This is snipped from trinidad-1.2.12 source code.

String title = getTitle(bean);

if (title != null)

rw.startElement("title", null);
rw.writeText(title, null);

// Write the META generator tag

First is very wrong from HTML validity point of view:
Validation Error: end tag for "HEAD" which is not finished
....For instance, in HTML the head element must contain a title child element...

Second which is unconditional write of

<meta name="generator" content="Apache MyFaces Trinidad">

is at least "unwanted" from "security" point of view.
However trinidad JSF style is so obvious that underlying technology
does not have to bue guessed the hard - "metadata generator way".

Of course, this can be fixed by implementing custom renderer, but...
wasn't trinidad designed to save my time in "usual situations" (at least ) ?

Please change the "if order" and make possible to turn off META generator tag.

Double DOCTYPE, jsp:output, trh:html (trinidad) and JDeveloper wizards

This the result when you click "new JSF Page" "wizard"
and use "*.jspx" and "Render in mobile device" option.

<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="" version="2.1"
<jsp:output omit-xml-declaration="true" doctype-root-element="HTML"
doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN"/>
< contentType="text/html;charset=UTF-8"/>

This however has one major problem,
produces invalid HTML markup with DOUBLED DOCTYPE.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<html dir="ltr" lang="en-US">

This is because one is produced by
and another by
thr:html + org.apache.myfaces.trinidad.core renderkit
(which is default for JDeveloper and "ADF Mobile")
It seems just like coincidence that both are the same (read more...)

As far as I hnow, the thr:html does not have "none" option for "Mode"
So the best is to remove all doctype-* from jsp:output.
Actually if reading the JSP spec for omit-xml-declaration, you can remove whole
jsp:output because:
The default value for a JSP document that has a jsp:root element is “yes”.

To bring some more info: the actual DOCTYPES rendere for MSIE 7.0 with
various swiches are:

default (damned again ?):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

strict (this should be default in 2010 !!!):

The letters are modes for specific browsers taken from:

Wednesday, July 21, 2010

JDeveloper 11g and encodings (Damned Default)

After fresh instalation JDeveloper will produce new JSPX pages that may look like this.

<?xml version='1.0' encoding='windows-1252'?>
< contentType="text/html;charset=windows-1252"/>

This 1252 seems to me like "unwanted legacy".

Use to select an encoding value. The default is CP1252.
Once you have selected a value, all new files will be created with the new encoding, and the new encoding will be used to open and save files without encoding tags.
Note that XML files and JSP 2.0 documents (XML compliant files)
must include an appropriate XML encoding declaration on a per-file basis.
For details refer to the W3C XML specification.
You can expand the encodings
in this list by appending new
encoding definitions to the encodings.xml file, found in the jdev/bin directory. This XML file contains a list of mappings from Sun JDK to IANA encoding names.
Note that files already open in JDeveloper will not be opened with the new encoding. To change the encoding used to read open files, close the files and reopen them after changing the encoding value here. Also note that files with encoding tags will always be opened and saved using the specified tags, and not JDeveloper's encoding.

This is tricky, half true, or buggy ...
I have tried to make a new page in an existing project and again the 1252.
Then I have tried new page in different project and UTF-8.

There are two more "Character Encoding" (at least) in Project Preferences.
XML.encoding and JSP.charset in JSF pages seems to be controlled by
Project Preferences/Compiler/JSP.

So If you have already created projects change those, and
manualy fix text in files and if you have non ascii markup in the text, resave all files as UTF-8 as well ;-))

Damned Defaults

Under this "Label" I will try to mark
default settings,
configurations and so called
"convenience APIs"

that I personally consider

or in best case

ADF Rich client Demo - incomplete HTML, user agent detection


Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/, application/, application/msword, application/x-ms-application, application/x-ms-xbap, application/, application/xaml+xml, */*
Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: xxxxxxxxxxxxx

Produces this incomplete markup:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""><html dir="ltr" lang="en-US"><head id="d1__xc_h"><title>ADF Faces Rich Client Demos</title><meta name="generator" content="Apache MyFaces Trinidad"><link rel="stylesheet" charset="UTF-8" type="text/css" href="/adf-richclient-demo/adf/styles/cache/blafplus-rich-desktop-bbz27h-en-ltr-hc-lf-cmp.css"><link rel="icon" type="image/png" href="/adf-richclient-demo/images/favicon.png"><link rel="apple-touch-icon" href="/adf-richclient-demo/images/touchicon.png"><script id="meta:metas1" type="text/javascript" src="/adf-richclient-demo/jsLibs/About.js"></script></head><body id="d1" onload="_checkLoadNoPPR()"><script type="text/javascript">var _AdfWindowOpenError='A popup window blocker has been detected in your browser. Popup blockers interfere with the operation of this application. Please disable your popup blocker or allow popups from this site.';</script><script type="text/javascript" src="/adf-richclient-demo/adf/jsLibs/Common1_2_12_1.js"></script><a name="top"></a><noscript>This page uses JavaScript and requires a JavaScript enabled browser.Your browser is not JavaScript enabled.</noscript><div id="tmplt"><form id="tmplt:ptf1" name="tmplt:ptf1" style="margin:0px" method="POST" onkeypress="return _submitOnEnter(event,'tmplt:ptf1');

Dig deeper, try to find docs....

ADF Rich Client Demo does not work in MSIE 7.0 with Native XHR disabled
Is this suposed to work in MSIE 7.0 ? I hope so but not with
Native HMLHttp request disabled in MSIE configuration ;-);
this.headers= new Object();
this.xmlhttp= new XMLHttpRequest();}

Any docs on this please ?

JSF, Trinidad, Oracle ADF Rich Client

I will start posting unsorted opinions about ADF in the next days
just to collect findings, subjective unproved hypothesis and mental shocks I'm ready to experience during my "late adoption".....

From JSF Specification:

Solving Practical Problems of the Web
JSF’s core architecture is designed to be independent of specific protocols and markup.
However it is also aimed directly at solving many of the common problems encountered
when writing applications for HTML clients that communicate via HTTP to a Java
application server that supports servlets and JavaServer Pages (JSP) based applications.

Or from ADF dev guide:

JavaServer Faces for Quick Learners
JSF 1.2 was chosen as the view layer of choice in Fusion web application development of Oracle
JDeveloper 11g. JSF is a Java EE standard since 2004 and in its current version 1.2 is part of the
Java EE 5 platform. JSF is designed to simplify web application development and changes the
programming model for building web pages from HTML markup development to the assembly
of reusable UI components that are declaratively linked to their data model and server-side event

But does this gives us mandate to produce

Bad html (suboptimal, not semantic at all, or event invalid ?)
Bad css (obtrusive, uneffective,....)
Bad JavaScript (obtrusive, large, old fassioned ?)
and ignore most of URI and HTTP principles ?

and i'm not commenting on backend Java code yet ;-(

Wednesday, July 14, 2010

Comparing window references

or "Evil twins" === vs. == in cross-windows communication

Comparing window references or "Evil twins" === vs. == in cross-windows communication.

As you may have read in meany sources
=== is preffered over ==
Mr.D calls the == variant The evil twin, but... MSIE (again) may surprise you:

Lets have two windows A and B

now in A lets call this wierd construction:

// in window A, "ask window B to create object"
new B.Object1();

// code inside window B looks like this
function Object1(p1,p2,p3)
//what DOES window mean:,
// a) is it wnd from "new wnd.Object1()" or
// b) is it callers window context ?
// see test case for answer ;-)
return this._ctx;

This construct will work
in all browsers
in all types of windows (iFrame,, modal, modeless dialogs)
but and WILL NOT WORK in MSIE modelessDialog and
and the call will end up with "Invalid procedure call or argument".

However in those working in explorer (iframe and tweaked modal dialog)
let's try to compare window references:

// remote window is opener or parent or self
// depending on the type of "popup" method used

var remote=new remoteWnd.Object1();
var remoteCtx=remote.getCtx();
asrt(remoteCtx===remoteWnd,"window refs broken ?");
return remoteCtx.location.href;

All browsers (Safari, FF, Opera, Chrome) pass this test for
all supported types of cross-referenced windows (iFrame,,showModalDialog)

MSIE (6,7,8) fails to compare window references with ===


// does not work
// seems to work but what is actually compared ? (TODO: see specs.)
// works but means something different right ?

Of course there is more XB magic in cross-window communication
(MSIE and Safari identified as trouble makers)
and I may return with more notes....

Monday, June 28, 2010

SCRIPT.src vs. getAttribute("src") and magic 4 for MSIE

// Lets have uri:

//1. popular (incorrect) way to find URI for current script (inside the script code)
var script_src = (scripts = head[0].getElementsByTagName("SCRIPT"))[scripts.length - 1].src;

//2. popular trick to "resolve" uri to another script in the same "directory"
// src becomes:
// http://localhost:8080/a/b/c/script.js/../script2.js
// which is then transformed by browsers in actual http request to
// http://localhost:8080/a/b/c/script2.js

however when combined together, it can turn deadly in Cross-Browser code
since .src returns "dots removed" in FF


and raw value in MSIE 7.0


So here comes the another magic constant 4 in getAttribute("src",4) for MSIE ;-), but ? it does not work ?! (now tested in MSIE 8)
so you have to use .src !

As far as I know even jQuery does not have fix for this,
even if they have for getAttribute("href",2)

Edited in 2011:
Confused ? me as well. I have to retest all this because MSIE 8 seems to somehow work with .src and not work with getAttribute("src,4").
Work means returning "expanded" and "normalized" uri.

Wednesday, June 23, 2010

isDialog(window) and window.dialogArguments

How to do detection if window was opened with
shoModalDialog or showModelessDialog vs. with the or other method.

Code was ugly because of non null opener returned in non MSIE browsers
and tricky window.dialogArguments if undefined and null values where passed to showModalDialogMethod

This is my proposal for reliable version test isDialog(window) tested in FF,MSIE 7,Chrome and Safari (originally it was 6 lines long with browser sniffing)

return "dialogArguments" in window;

Thanx inspiration.

Thursday, June 17, 2010

Link of the day ! "DOM Deviations", sorry "Normative Variations"

The following subsections detail the normative variations from MUST requirements in [DOM Level 3 - Core].

Or even better:
Internet Explorer Standards Support Documents

Wednesday, June 16, 2010

Firefox/3.5.6 window.onerror (MDC docs buggy as well)
funcRef is a reference to a function. When the function returns true, this prevents the firing of the default event handler. Function parameters:
Error message (string)
Url where error was raised (string)
Line number where error was raised (number)
Question is What the "raised" means ?
In MSIE it means "thrown" (that is the word). In FF it means where new Error() was called.

Tested on:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)

Testcase available for those interesed (mail me).

You may be interesed in this as well:
funcRef is a reference to a function. When the function returns true, this prevents the firing of the default event handler. Function parameters:
Error message (string)
Url where error was raised (string)
Line number where error was raised (number)

The problem: What the "raised" means ?

In MSIE it means "thrown" (that is the word). In FF it means where new Error() was called.

Tested on:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)

Testcase available for those interesed (mail me).

You may be interesed in this as well:

I have had a look at "solution" presented here: but this
Some people recommend just assigning it to window.onerror:

window.onerror = function() {

will not work in FF, just because of mentioned stack bug.

So all you will learn with the stacktrace.js sample is:


That your on error was called and it called printstacktrace and run.
You will not learn who called your onerror handler.

Monday, June 14, 2010

W3 Document.textContent vs. MSXML Document.text and MSDN docs

w3 says that .textContent for DOCUMENT_NODE should be null.
Closest MS implementation (MSXML .text) documented in MSDN claims:
Returns a string representing the value of the node.
This is the concatenated text of
all subnodes with entities expanded.
But what is subnodes and what is text ?
<?xml version="1.0" encoding="utf-8" ?>
<!-- Document level comment -->
<!DOCTYPE root [
    <!ENTITY ent1 "expanded ent1">
<?pi1 ?>
<root attribute="attribute.value">
Remarks section clarifies something:
When concatenated, the text represents the contents of text or CDATA nodes. All concatenated text nodes are normalized according to xml:space attributes and the value of the preserveWhiteSpace switch. Concatenated CDATA text is not normalized. (Child nodes that contain NODE_COMMENT and NODE_PROCESSING_INSTRUCTION nodes are not concatenated.) .text trims the whitespace on the edges of the result, and "normalizes" \r\n => \n, but otherwise just concatenates text.
Retrieves and sets the string representing the text contents of this node or the concatenated text representing this node and its descendants.
For more precise control over text manipulation in an XML document, use the lower-level nodeValue property, which returns the raw text associated with a NODE_TEXT node.
For this sample it returns:
element.text.1 cdata.content expanded ent1 element.text.2
Both comments skipped, OK, but I still, miss the text of my NODE_ENTITY.
If requested ditectly NODE_ENTITY.text returns:
expanded ent1
So I would expect:
expanded ent1 element.text.1 cdata.content expanded ent1 element.text.2
Why is NODE_ENTITY.text missing from NODE_DOCUMENT.text ? Maybe because it is inside NODE_DOCUMENT_TYPE which claims to return .text as "" ? Or because :text", does not mean text but nodeValue which is defined as null for both NODE_DOCUMENT_TYPE and NODE_ENTITY.

From my quick tests Document.text behaves the same as Document.documentElement.text. If anyone can show, how the may differ I would be pleased. Until then, considered as bad design, useless w3 deviation and insufficent documentation.

Wednesday, June 9, 2010

MSXML.createNode method (docs,design,standards?)
A string defining the namespace URI. If specified, the node is created in the context of
the namespaceURI parameter with the prefix specified on the node name.
If the name parameter does not have a prefix, this is treated as the default namespace.

The marked part may be a bit problematic to interpret.
In the reality it means that createNode will create unprefixed element or attribute and
produce xmlns="ns" declaration.

This is fine for elements because of xmlns scoping.
However this leads to troubles if creating
unprefixed-namespaced-attribute on unprefixed-namespaced-element with different namespace,
and also if creating
prefixed-namespaced-attribute on prefixed-namespaced-element with different namespace and same prefixes.
var root = d.createNode(1, "root", "nsRoot"),
    ch1 = d.createNode(1, "p:child", "nsChild"),
    ch2 = d.createNode(1, "child", "nsChild"),
    a1 = d.createNode(2, "p2:a1", "nsAttr"),
    a2 = d.createNode(2, "a2", "nsAttr");

The last line will fail, with "bit problematic to interpret" error,
showing authors misinterpretation of namespace and prefixe terms ;-)

There was a Namespace conflict for the '' Namespace.

Actualy there was a conflict for '' prefix between nsChild and nsAttr namespaces.

XML without last line will look like this:
<root xmlns="nsRoot">
    <p:child xmlns:p="nsChild"/>
    <child xmlns="nsChild" xmlns:p2="nsAttr" p2:a1=""/>

Try to rewrite this code with createElementNS and createAttributeNS in different browsers.
Some are able to autogenerate prefixes if already taken by another namespace, some produce funny results.

MS is lucky not to declare compliance, however the docs are confusing and
prefix colisions unsolved.

Another silly decision is that namespaceURI does not accept null.
The closes standardized method (DOM2 Level createElementNS) speaks abou null values, and all browsers implement
both null and "" as "unqualified".