Wednesday, November 24, 2010

Yes, Troy McClure have read WCAG ;-)

http://www.w3.org/TR/2010/NOTE-WCAG20-TECHS-20101014/C30
...............
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
http://xstandard.com/en/articles/better-alt/
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.


Antisable:

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

Better:

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


heart example would look like:

Tuesday, November 16, 2010

ShadedBorder

http://www.ruzee.com/blog/shadedborder

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

Monday, November 15, 2010

GWT real-world-projects and w3.org 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:
"real-world-projects.

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


http://www.sitepoint.com/books/jsdesign1/


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

ssajax.js

This computer program contains valuable, confidential and proprietary
information.

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:
http://www........com/ocom/resources/sitestudio/ssajax/ssajax.js

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

http://snippetdesigner.codeplex.com/
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 ?

http://www.switchonthecode.com/tutorials/csharp-tutorial-visual-studio-code-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)


http://msdn.microsoft.com/en-us/library/ms165392(VS.80).aspx

Shortcut

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 ( _ ).
from http://msdn.microsoft.com/en-us/library/ms171440(v=VS.80).aspx

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
or
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="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Keywords>
<Keyword>construction</Keyword>
</Keywords>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>cnstr (jQuery style)</Title>
<Author>a.in.the.k</Author>
<Description>construction pattern ala jQuery</Description>
<HelpUrl>
</HelpUrl>
<Shortcut>aitkCnstr</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal Editable="true">
<ID>cnstr</ID>
<ToolTip>cnstr</ToolTip>
<Default>cnstr</Default>
<Function>
</Function>
</Literal>
<Literal Editable="true">
<ID>p</ID>
<ToolTip>p</ToolTip>
<Default>p</Default>
<Function>
</Function>
</Literal>
</Declarations>
<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$;
})(window);]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

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: http://www.w3.org/TR/html4/ 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/HTMLEntityCodec.java (is it really correct ?)

org/owasp/esapi/codecs/HTMLEntityCodec.java

After reply from jwilliams, I have almost apologized for arogancy...
but...I gues jwilliams is the same person, that coded this:
org/owasp/esapi/codecs/HTMLEntityCodec.java
@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);
out.println(eu.escapeHtmlFull(s1+s2));
out.println(ESAPI.encoder().encodeForHTML(s1+s2));
}

a.in.the.k:
&#60;&#62;abc123+-&#xFFFD;&#65823;&#65839;&#65855;

with ESAPI gou get:
&lt;&gt;abc123&#x2b;-&#xdc00;&#xd800;&#xdd1f;&#xd800;&#xdd2f;&#xd800;&#xdd3f;

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

http://www.owasp.org/index.php?title=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.

BEWARE

Check code here:
http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java

and
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

escapeRegExp
78:abcdefgjklmnoprstuvxyz
110:\-\.\*\+\?\^\$\{\}\(\)\|\[\]\/\\
125:a\-a\.a\*a\+a\?a\^a\$a\{a\}a\(a\)a\|a\[a\]a\/a\\a

escapeRegExp_asFunction
110:abcdefgjklmnoprstuvxyz
797:\-\.\*\+\?\^\$\{\}\(\)\|\[\]\/\\
797:a\-a\.a\*a\+a\?a\^a\$a\{a\}a\(a\)a\|a\[a\]a\/a\\a


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 toString.call(obj) === "[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
toString.call(a) == [object Array] 235:true

Firefox/3.5.12
a instanceof Array 12:true
a.constructor === Array 41:true
toString.call(a) == [object Array] 51:true

Safari/533.18.5
a instanceof Array 2:true
a.constructor === Array 5:true
toString.call(a) == [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 && toString.call(obj) === "[object Array]");
};

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

var toString = Object.prototype.toString,
isArray: function(obj) {
return (!!object && toString.call(obj) === "[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 ?
Benchmarks:

arrLit toString.call(a) == [object Array] 219:true:[object Array]
arrLit optimized toString.call(a) 234:true:[object Array]

null toString.call(a) == [object Array] 203:false:[object Object]
null optimized toString.call(a) 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/9.0.0.0
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.

Questions:
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*/
2.if(a==undefined){}
3.if(a==null){}
4. if(a==b){}


result (expected):

Error:
Problem at line 2 character 5: Expected '===' and instead saw '=='.
if(a==undefined){}
Problem at line 3 character 5: Expected '===' and instead saw '=='.
if(a==null){}
Problem at line 4 character 5: Expected '===' and instead saw '=='.
if(a==b){}
Implied global: a 2,3,4, b 4

all 3 lines reported as error.

Now try to turn it off:

/*jslint eqeqeq: false*/
if(a==undefined){}
if(a==null){}
if(a==b){}

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

Error:
Problem at line 2 character 5: Use '===' to compare with 'undefined'.
if(a==undefined){}
Problem at line 3 character 5: Use '===' to compare with 'null'.
if(a==null){}
Implied global: a 2,3,4, b 4


Why do I care ?

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

function(arg1,arg2,arg3)
if(arg3 == null)
or
if(arg3 != null)

bacause IMHO this is valid:

null==null
true
undefined==null
true
null!=null
false
undefined!=null
false

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

if(arg3 === null || typeof arg3 !== "undefined")
or
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 ) {

})(window);

Trying this

/*jslint eqeqeq: false*/
(function(undefined) {
if(a==undefined){}
}());

with JSLint you get:

Error:
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'.
if(a==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
(foo)
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) {
if(a!=undef){}
}());



Thanx in advance....

Try also my favorite blogger at:
http://webreflection.blogspot.com/search?q=JSLint

Update: 2011/06/07

It seems that current version Edition 2011-07-01
http://www.jslint.com/
works fine for all 3 cases and works correctly for null and undefined as well:

1./*jslint eqeqeq: true*/
2.if(a==undefined){}
3.if(a==null){}
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 !
http://en.wikipedia.org/wiki/Percent-encoding
Don't we have RFCs for this ?

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

return java.net.URLEncoder.encode(input,
ESAPI.securityConfiguration().getCharacterEncoding());


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.
javase/6/docs/api/java/net/URI.html

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
replace my code for UNRELIABLE OWASP REFERENCE IMPLEMENTATION.


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

/a/a/a
/a/b
/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
d=request.getRequestDispatcher("./c.jspx");
if(d==null)
{
d=request.getRequestDispatcher("/c.jspx");
}
d.include();


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


PREFERE:
getServletContext().getRequestDispatcher() and /contextRelativePath

OVER:
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

http://localhost/path?query

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
properties.


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:

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


Apache Tomcat/6.0.28 - works fine
WebLogic Server 10.3.3.0 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});
for(..)
String s3=(String)m.invoke(b1,args);


Results:

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 ?

bugs.eclipse.org

Here is the
list of bugs reported by a.in.the.k to bugs.eclipse.org

"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.

Surprise:

<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:
org/apache/taglibs/standard/tag/common/core/ForEachSupport.

Conclusions:

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
connections),
and perform other one-time activities.

SRV.2.3.3.1 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:

${fn:escapeXml(bundle['fileTable.lastModified'])}

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 ?
Thanx.

Update:

c:out CAN HAVE BODY,
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 -->
</fmt:message>
</c:out>

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:

http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx

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;
input.next();
if (entityToCharacterMap.containsKey('&' + entity)) {
if (input.peek(';')) input.next();
break;
}
} else if (c == ';') {
input.next();
} else {
break;
}
}

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:
http://code.google.com/p/owasp-esapi-js/
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 ++) {
fIterator(this[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:

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

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

Result:
"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 ;-(

https://bugs.eclipse.org/bugs/show_bug.cgi?id=302060

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

http://matthewjamestaylor.com/blog/holy-grail-no-quirks-mode.htm

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

http://www.aitk.info/download/Layouts.1.0.war


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" />
</c:url>

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

/BasicConcepts/foobar.jspx#fragment?p1=v1&p2=v2


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).
http://jena.sourceforge.net/iri/

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 1.5.0.201003261013
Oracle Common Tools 1.5.0.201003261013 (dependency)

You can do that by adding another update URL in Eclipse:
“Oracle Enterprise Pack for Eclipse - http://download.oracle.com/otn_software/oepe/helios”

Oracle web site (http://www.oracle.com/technetwork/developer-tools/eclipse/downloads/oepe-11115-089873.html )
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.
http://www.eclipse.org/eclipse/platform-text/3.6/plan.php


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

From Error log:

java.lang.reflect.InvocationTargetException
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:421)
at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:1008)
at org.eclipse.wst.server.ui.internal.wizard.TaskWizard.performFinish(TaskWizard.java:221)
at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:811)
at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:430)
at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:624)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:234)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4066)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3657)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
at org.eclipse.jface.window.Window.open(Window.java:801)
at org.eclipse.wst.server.ui.internal.actions.LaunchWizardAction.run(LaunchWizardAction.java:57)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:498)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4066)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3657)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2629)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2593)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2427)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:670)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:663)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
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(Main.java:619)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
at org.eclipse.equinox.launcher.Main.run(Main.java:1407)
Caused by: java.lang.NoSuchMethodError: org.eclipse.wst.server.core.internal.UpdateServerJob.<init>(Lorg/eclipse/wst/server/core/IServer;)V
at oracle.eclipse.tools.weblogic.ui.internal.WlsUiPlugin$1.serverAdded(WlsUiPlugin.java:242)
at org.eclipse.wst.server.core.internal.ResourceManager.fireServerEvent(ResourceManager.java:493)
at org.eclipse.wst.server.core.internal.ResourceManager.registerServer(ResourceManager.java:1114)
at org.eclipse.wst.server.core.internal.ResourceManager.addServer(ResourceManager.java:630)
at org.eclipse.wst.server.core.internal.Server.saveToMetadata(Server.java:459)
at org.eclipse.wst.server.core.internal.Base.doSave(Base.java:264)
at org.eclipse.wst.server.core.internal.Server.doSave(Server.java:448)
at org.eclipse.wst.server.core.internal.ServerWorkingCopy.save(ServerWorkingCopy.java:426)
at org.eclipse.wst.server.ui.internal.wizard.WizardTaskUtil.tempSaveServer(WizardTaskUtil.java:149)
at org.eclipse.wst.server.ui.internal.wizard.WizardTaskUtil$4.performFinish(WizardTaskUtil.java:65)
at org.eclipse.wst.server.ui.internal.wizard.TaskWizard.executeTask(TaskWizard.java:256)
at org.eclipse.wst.server.ui.internal.wizard.TaskWizard$2.run(TaskWizard.java:213)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1975)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1957)
at org.eclipse.wst.server.ui.internal.wizard.page.WorkspaceRunnableAdapter.run(WorkspaceRunnableAdapter.java:35)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)


That is because underlying eclipse implementation had changed.
You see that signature?
UpdateServerJob.<init>(Lorg/eclipse/wst/server/core/IServer;)V

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[])
{
super(Messages.jobUpdatingServers);
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);
job.schedule();
}
}

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);
}


Conclusion:
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:
From
UpdateServerJob job = new UpdateServerJob(server);
To
UpdateServerJob job = new UpdateServerJob(new IServer[]{server});

Simple like that

This construction needs to be changed also in these files:

oracle.eclipse.tools.weblogic.ui_3.0.0.201003261013.jar -> package oracle.eclipse.tools.weblogic.ui.internal -> WlsUiPlugin.java
oracle.eclipse.tools.weblogic.ui_3.0.0.201003261013.jar -> package oracle.eclipse.tools.weblogic.ui.internal -> WlsUiPlugin$1.java
oracle.eclipse.tools.weblogic_3.0.0.201003261013.jar -> package oracle.eclipse.tools.weblogic.server.internal.util -> ServerLaunchUtils.java

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

Versions:

Decompiler info:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// 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}">
<ol>

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

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="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />

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

<jsp:text>
<![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ]]>
</jsp:text>


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>

</body>
</html>
</jsp:root>


My proposed version is:

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page language="java"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
<jsp:output omit-xml-declaration="no" doctype-root-element="html"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>

</body>
</html>
</jsp:root>

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 ;-))

HTML or XHTML ?

somewhere from http://www.betterform.de/demo.xhtml

HTTP:
Content-Type: text/html;charset=UTF-8
.........................
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:xhtml="http://www.w3.org/1999/xhtml">
<!-- *** powered by betterFORM, &copy; 2010 *** -->
<head>


Bug or feature ?

Monday, July 26, 2010

Oracle Web Tier Tools (OEPE)

or
Part of Oracle Enterprise Pack for Eclipse 11.1.1.5.0 (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}"
pageEncoding="${encoding}"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=${encoding}" />
<title>Insert title here</title>
</head>
<body>
<f:view>
${cursor}
</f:view>
</body>
</html>


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.


Beware:
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.....
Shocking:
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;
   continue;
  }

  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: http://javascript.crockford.com/style1.html
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:

<![CDATA[
<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);
rw.endElement("title");
}

// Write the META generator tag
_writeGeneratorTag(context);


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="http://java.sun.com/JSP/Page" version="2.1"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:trh="http://myfaces.apache.org/trinidad/html"
xmlns:tr="http://myfaces.apache.org/trinidad"
xmlns:dvtt="http://xmlns.oracle.com/dss/trinidad/faces">
<jsp:output omit-xml-declaration="true" doctype-root-element="HTML"
doctype-system="http://www.w3.org/TR/html4/loose.dtd"
doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN"/>
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<f:view>
<trh:html>
....


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


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html dir="ltr" lang="en-US">
....


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

Solution:
As far as I hnow, the thr:html does not have "none" option for "Mode"
see http://myfaces.apache.org/trinidad/trinidad-api/tagdoc/trh_html.html
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:
omit-xml-declaration....
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" "http://www.w3.org/TR/html4/loose.dtd">
S S A A A A A A Q

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

strict (this should be default in 2010 !!!):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
S S S S S A A A A


The letters are modes for specific browsers taken from:
http://hsivonen.iki.fi/doctype/

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'?>
.....
<jsp:directive.page contentType="text/html;charset=windows-1252"/>



This 1252 seems to me like "unwanted legacy".

Tools/Preferences/Environment/encoding:
Encoding
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.

Beware:
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.

WorstCase:
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

WRONG,
DANGEROUS
or in best case
NOT HELPING.

ADF Rich client Demo - incomplete HTML, user agent detection

Request

GET http://jdevadf.oracle.com/adf-richclient-demo/faces/index.jspx?gallery=true&_afrLoop=22766204435448480&_afrWindowMode=0&_afrWindowId=null HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, 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" "http://www.w3.org/TR/html4/loose.dtd"><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

http://jdevadf.oracle.com/adf-richclient-demo/faces/index.jspx
Is this suposed to work in MSIE 7.0 ? I hope so but not with
Native HMLHttp request disabled in MSIE configuration ;-)



AdfXMLRequest.superclass.Init.call(this);
this.isSynchronous=false;
this.callback=null;
this._state=AdfXMLRequest.UNINITIALIZED;
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
handlers.

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)
{
this.p1=p1;
this.p2=p2;
this.p3=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 ;-)
this._ctx=window;
}
Object1.prototype.getCtx=function()
{
return this._ctx;
}


This construct will work
in all browsers
in all types of windows (iFrame, window.open, modal, modeless dialogs)
but and WILL NOT WORK in MSIE modelessDialog and window.open.
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, window.open,showModalDialog)
but

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

summary:

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


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:
http://localhost:8080/a/b/c/script.js

//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

http://localhost:8080/a/b/c/script2.js

and raw value in MSIE 7.0

http://localhost:8080/a/b/c/script.js/../script2.js


So here comes the another magic constant 4 in getAttribute("src",4) for MSIE ;-), but ? it does not work ?! (now tested in MSIE 8)
http://msdn.microsoft.com/en-us/library/ms536429(v=VS.85).aspx
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 window.open 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 http://perfectionkills.com/for 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].

http://msdn.microsoft.com/en-us/library/ff460357(v=VS.85).aspx


Or even better:
Internet Explorer Standards Support Documents

http://msdn.microsoft.com/en-us/library/ff405926(v=VS.85).aspx

Wednesday, June 16, 2010

Firefox/3.5.6 window.onerror (MDC docs buggy as well)

https://developer.mozilla.org/en/DOM/window.onerror#Parameters
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:1.9.1.6) 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:
https://bugzilla.mozilla.org/show_bug.cgi?id=355430


https://developer.mozilla.org/en/DOM/window.onerror#Parameters
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:1.9.1.6) 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:
https://bugzilla.mozilla.org/show_bug.cgi?id=355430

I have had a look at "solution" presented here:
http://github.com/emwendelin/javascript-tacktrace#readme but this
Some people recommend just assigning it to window.onerror:

window.onerror = function() {
alert(printStackTrace().join('\n\n'));
}

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

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

run(null)
printStackTrace
onerror

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:
NODE_DOCUMENT
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 -->
<!-- TODO: NOTATION -->
<!DOCTYPE root [
    <!ENTITY ent1 "expanded ent1">
]>
<?pi1 ?>
<root attribute="attribute.value">
    element.text.1
    <e1><![CDATA[cdata.content]]></e1>
    <e2><!--comment.content--></e2>
    <e3>&ent1;</e3>
    element.text.2
</root> 
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.

Results:
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?)

http://msdn.microsoft.com/en-us/library/ms757901(VS.85).aspx
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");

root.appendChild(ch1);
root.appendChild(ch2);
ch2.setAttributeNode(a1);
ch2.setAttributeNode(a2);
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=""/>
</root>

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 http://www.w3.org/TR/DOM-Level-2-Core/ 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".