Wednesday, July 11, 2018

Perform an Auto-Submit Form Post from an Angular page

Keywords:
angular angular2 form post auto submit

Problem:
You need to send the user to another application (in the current view or new window) via a form-post that includes a payload of inputs.

How do you:
  1. avoid the form being handled by the angular framework; and (for bonus points)
  2. make the form dynamically auto-submit (to avoid the user having to hit a submit button)?

Solution:
For (a) the key to ensuring the form element in the template is not handled by the angular framework - and therefore allowing it to submit to the defined action is adding the ngNoForm attribute. There's notes in a discussion How to submit form to server in Angular2 ... at the time of writing, it doesn't appear to be well documented.

<form ngNoForm 
    #myFormPost name="myFormPost" 
    action="https://httpbin.org/post" 
    method="POST"
    target="_blank" >
    ...
  </form>

For (b) the dynamic auto-submit, you can obtain the reference to the form and submit it from the component code:
@ViewChild('myFormPost') myFormPost: ElementRef;
  ...
  // in some place where the form has been set
  this.myFormPost.nativeElement.submit();

A full working example is here: angular-form-post-auto-submit (on StackBlitz)
(this includes demo handling of hidden multi-line inputs)


Tuesday, February 23, 2016

HSQLDB ignores column aliases in select statement by default

Keywords:
HSQL HSQLDB column alias ignored NullPointerException JSTL

Problem:
I can't pin point where this change happened from the HSQLDB changelogs but somewhere between HSQL 1.8.0.7 and 2.2.5, the handling of column aliases has changed. This is particularly problematic if attempting to lookup via alias name in JSTL where failed lookup of results (due to wrong column names) come back as null.

This is a standalone JSP example:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:setDataSource var="dataSource" 
    url="jdbc:hsqldb:mem:example/aliasprob"
    driver="org.hsqldb.jdbcDriver"/>
<sql:update dataSource="${dataSource}">
    create table if not exists USERS (
        fullname varchar(255), 
        telephone varchar(255)
    );
</sql:update>
<sql:update dataSource="${dataSource}">
    insert into USERS (fullname, telephone) 
    values ('Joe Bloggs', '123-5555');
</sql:update>
<sql:update dataSource="${dataSource}">
    insert into USERS (fullname, telephone) 
    values ('Fred Twitters', '456-5555');
</sql:update>
<sql:query var="users" dataSource="${dataSource}">
    select fullname as "name"
    , telephone as "phone"
    from USERS
</sql:query>

<!DOCTYPE html>
<html>
    <head>
        <title>Alias Problems</title>
    </head>
    <body>
        <p>These are the users:</p>
        <table border="1">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Phone</th>
                </tr>
            </thead>
            <tbody>
                <c:forEach var="row" items="${users.rows}">
                    <tr>
                        <td>${row['name']}</td>
                        <td>${row['phone']}</td>
                    </tr>            
                </c:forEach>
            </tbody>
        </table>        
 </body>
</html>

<sql:update dataSource="${dataSource}">
    drop table USERS;
</sql:update>

With the above test, you get two rows in the result table with empty cells for the values. If the code above was changed to ignore the aliases used in the 'AS' statements and use the underlying column names the data would be visible. If I have code that uses column aliases in this way does the select statement have to be changed to work with HSQLDB?

Solution:
HSQLDB introduced the get_column_name property which "returns the underlying column name" (despite an alias being used) and is true by default. The documentation also states this is for "compatibility with other JDBC driver implementations". I suspect there's some inconsistency with with way the JSTL SQL tags are using ResultSet.getColumnLabel(int) vs ResultSet.getColumnName(int).

When using JSTL, there's no distinction between column labels or names when using the row['column'] syntax so using get_column_name=false in the HSQL connection URL is a quick fix - making the JSTL behaviour at least, consistent with other JDBC drivers.

In the example code above, this would look like:
<sql:setDataSource var="dataSource" 
    url="jdbc:hsqldb:mem:example/aliasprob;get_column_name=false"
    driver="org.hsqldb.jdbcDriver"/>

Friday, October 30, 2015

Database schema naming for Vendor Neutrality

Keywords:
database vendor-agnostic identifier limitations Oracle SQL Server PostgreSQL HSQL MySQL table column

Problem:
It's surprisingly not a common topic of dicussion, but if you want to author database scripts in a way that is vendor-agnostic the consensus seems to be to conform to ANSI SQL. Are there any guides for how to name the schema identifiers to comply with the various vendor's (character limit) limitations?

Solution:
I couldn't find a good cross-vendor summary, so here's an attempt at looking at the important identifier limitations across some vendors.

Vendor Identifier Limit (characters) Notes
TABLE COLUMN CONSTRAINT
Oracle 30 30 30
https://docs.oracle.com/database/121/SQLRF/sql_elements008.htm#SQLRF51129
PostgreSQL 63 63 63
http://www.postgresql.org/docs/current/interactive/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
MS SQL Server 128 128 128
https://msdn.microsoft.com/en-us/library/ms175874.aspx
MySQL 64 64 64
https://dev.mysql.com/doc/refman/5.0/en/identifiers.html
HSQL 128 128 128
http://hsqldb.org/doc/2.0/guide/databaseobjects-chapt.html#dbc_table_creation
DB2 30 * 30 * 18 *
*Limit increased to 128 from v9.5

https://www-01.ibm.com/support/knowledgecenter/SSEPGG_9.5.0/com.ibm.db2.luw.wn.doc/doc/c0051391.html

If you are concerned with complying with all the above vendors, then the lowest common denominator here is Oracle at 30 characters for table/column & constraints.

Friday, November 28, 2014

Avoid using java.io.File.lastModified() for sorting Files

Keywords:
java File lastModified timestamp ext3 ext4 linux windows sort order milliseconds

Problem:
It seems like a basic use-case - order a list of files based on the order they were modified. File.lastModified() seems a reasonable choice for basing a Comparator on, based on the documentation:
A long value representing the time the file was last modified, measured in milliseconds since the epoch ...

So, assuming the files are not made any quicker than 1-per millisecond this should work fine right? No. For some reason, on linux based systems File.lastModified() is always rounded to the second. This appears to be a (legacy) limitation with 'ext3' (and earlier?) file-systems that persists to this day - even if the file-system is ext4 (with nanosecond precision). On a windows based system (with NTFS, 100ns precision) the File.lastModified() values are to the millisecond (I'm not the first person to notice the difference - File.lastModified() on windows vs linux).

Problems with sorting files on linux don't seem to be isolated to java "Order files by creation time to the millisecond in Bash" - though I suspect that thread is actually based on using an ext3 file-system, as on an ext4 file-system you can get this working with ls -latr --full-time.

Q: How do you know what type of file-system you're running?
A: df -T

Q: What precision will the file-system support?
A: See Comparison of file systems article and the 'Max Timestamp Resolution' column.

Q: If I'm still unsure, is there a test case I can try?
A: Here's a basic one:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileModified {
    public static void main(String[] args) throws IOException {
        File file = File.createTempFile("timestamp-test-", ".txt");
        FileWriter writer = new FileWriter(file);
        writer.append("updated");
        writer.close();
        
        System.out.println("via " + file.getClass().getName() 
                    + "\n\t" + file.getAbsolutePath() + "\n\t\tmodified: " + file.lastModified() + "ms");        
    }
}

If you establish that the target environment(s) for your java application are on file-systems that do support a higher than 1 second precision how do you get access to this from java?


Solution:
The closest bug report I can find is JDK-6939260. But it appears that the bug title has been changed to propose exposing higher than millisecond precision for files - the side note made in the comments states "it's not possible to support this with java.io.File because it specifies that the last modified time is returned in milliseconds". This missed the point in the original bug description stating "The end of the number is always 000" - ie parking micro/nano second precision, shouldn't the method provide at least millisecond precision if the underlying filesystem supports this (or higher)?

It appears for new features (and bug fixes?) related to the capabilites of the file-system, this functionality is going to be implemented in java.nio.file. So if you're using java 1.8+ you may be able access more accurate timestamps via Files.getLastModifiedTime(Path,...). The updated test case becomes:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.TimeUnit;

public class FileModified {
    public static void main(String[] args) throws IOException {
        File file = File.createTempFile("timestamp-test-", ".txt");
        FileWriter writer = new FileWriter(file);
        writer.append("updated");
        writer.close();
        
        System.out.println("via " + file.getClass().getName() 
                           + "\n\t" + file.getAbsolutePath() + "\n\t\tmodified: " + file.lastModified() + "ms");
        
        Path filePath = FileSystems.getDefault().getPath(file.getAbsolutePath());
        FileTime modified = Files.getLastModifiedTime(filePath);
        System.out.println("via " + modified.getClass().getName() + "\n\t" + filePath 
                           + "\n\t\tmodified: " + modified.toMillis() + "ms (" + modified.to(TimeUnit.NANOSECONDS) + "ns)");
    }
}

Note that although java.nio.file.attribute.FileTime exists in java 1.7, JDK-6939260 claims that it's only going to be fixed in 8 onwards (I can't tell which update - I tried the latest available and it still fails).

If you need to support java 1.7 or below on linux there is no staightforward option (short of parsing ls --full-time command output). If your system is in control of the files being written, my suggestion would be to maintain a separate record of creation/modified time - assuming order by time is important and you need higher than per-second precision.

Friday, June 20, 2014

Using JCR-SQL2 for querying ACLs in a Jackrabbit repository

Keywords:
jcr-sql2 query jackrabbit ACL ACE access controls nt:hierarchyNode rep:policy

Problem:
The ultimate problem was actually how do you handle 'gracefully' removing Principals from the (default) jackrabbit security workspace when there's the potential they are being referenced by either: (a) groups; or (b) access controls (ACLs). This may be a topic for another (much more detailed) post, but for now the focus is on (b) detecting if there are any ACLs in the repository that reference the Principal.

Aside: why is it a concern? Removing the Principal won't effect enforcement of the access controls, but anything attempting to process the ACL definition will hit an error for the missing Principal:
javax.jcr.InvalidItemStateException: Item does not exist anymore: 6e332039-2956-323c-8e82-212de8f88ff0`

The AccesControl documentation on the jackrabbit wiki states:
How Resource-based ACLs are stored
Resource-based ACLs are stored per resource/node in a special child node rep:policy. This one will have a list of rep:GrantACE child nodes (usually named allow, allow0,...) for grant access control entries and rep:DenyACE child nodes (usually named deny, deny0,...) for deny access control entries.

Each ACE node has a rep:principalName STRING property pointing to the user or group this ACE belongs to, and a rep:privileges NAME multi-value property, containing all the privileges of this ACE.

Note that you can read/browse these nodes using the JCR API, but cannot modify them. This must always happen through the JCR access control API.

How do you target these rep:policy items in a JCR-SQL2 query ... and more importantly has anyone done this before - to save me the time?


Solution:
I couldn't find an example, but by careful reading of the builtin_nodetypes.cnd (and some trial and error) the following query will list all access control entities (ACEs) that reference a given Principal (i.e a User or Group) with-in a given access control list (ACL) set on a resource (file or folder).
select resource.*, ace.*
    from [nt:hierarchyNode] as resource
    inner join [rep:ACL] as acl
       ON ISCHILDNODE(acl, resource)
    inner join [rep:ACE] as ace
       ON ISCHILDNODE(ace, acl)
    where ace.[rep:principalName] = "kevin"

The results will look like (in table form):
Result Node-pathresource.jcr:createdByresource.jcr:createdresource.jcr:primaryTypeace.rep:globace.rep:nodePathace.rep:principalNameace.jcr:primaryType
/files/examplejack-admin2014-05-06T07:08:09.100+11:00nt:folderkevinrep:GrantACE

Note that 'Result Node-path' - full path to the resource - won't (and can't) be a a "column" Value in the result javax.jcr.query.Row items but can be obtained via a javax.jcr.Node item referenced by the javax.jcr.query.Row. Also note that the Principal reference here is via the 'name' as stored in the protected rep:principalName field - even if using the default security workspace, this won't be the full 'principal path' (path to the org.apache.jackrabbit.api.security.principal.ItemBasedPrincipal).

Notes:
The stackoverflow [jcr-sql2] info page includes a pretty neat summary of what JCR-SQL2 is with links to the reference specs and implementations (note the above is specific to jackrabbit). The JCR 2.0 SQL-2 Grammar diagrams are particularly useful.

Thursday, October 31, 2013

Quick Start to tracing JDBC SQL operations using log4jdbc

Keywords:
database logging show SQL log4jdbc tomcat JNDI log4j trace performance timing

Problem:
Given a complex web application (with many moving parts), there's performance issues that first impressions seem to point at environment-specific database latency. Is there any way to trace/profile/monitor all the SQL statements being made to the database (preferably with timings)?

Solution:
log4jdbc seamlessly lets you configure a logger between your application and the JDBC connection. Documentation on the log4jdbc site is very good and has just about all you need to know, below is a "quick start" for the impatient.

Step 1: Jar File(s)

Drop the log4jdbc4-[version].jar file into [webapp]/WEB-INF/lib.
You'll also need:
  • a supported logging framework (log4j: log4j-[version].jar)
  • the SLF4J API (slf4j-api-[version].jar - already had it)
  • the SLF4J jar to use this logging framework (slf4j-log4j12-[version].jar - already had it)

Step 2: Driver Class and URL

  1. Change the database resource definition to use the driver class net.sf.log4jdbc.DriverSpy ('spy' as it will work out the correct 'real' driver class to use).
  2. Simply prepend jdbc:log4 to the existing URL.

For a PostgreSQL database connection configured as a JNDI/JDBC Resource in Tomcat, this will look like:
    <Resource
            name="jdbc/example"
            type="javax.sql.DataSource"
            factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
            driverClassName="net.sf.log4jdbc.DriverSpy"
            url="jdbc:log4jdbc:postgresql://localhost:5432/example"
            username="postgres" password="***" 
            maxActive="20" maxIdle="10" maxWait="-1" 
            removeAbandoned="true" removeAbandonedTimeout="120" logAbandoned="true"
            auth="Container"
            charset="UTF-8" />

Step 3: Logging Config

There's detailed notes on the five key loggers and an example log4j.properties is available. But if you just want to see SQL + timings, the following will log this all to console:
log4j.logger.jdbc.audit=FATAL,Log4JDBC
log4j.additivity.jdbc.audit=false

log4j.logger.jdbc.resultset=FATAL,Log4JDBC
log4j.additivity.jdbc.resultset=false

log4j.logger.jdbc.sqlonly=FATAL,Log4JDBC
log4j.additivity.jdbc.sqlonly=false

log4j.logger.jdbc.sqltiming=INFO,Log4JDBC
log4j.additivity.jdbc.sqltiming=false

log4j.logger.jdbc.connection=FATAL,Log4JDBC
log4j.additivity.jdbc.connection=false

log4j.appender.Log4JDBC=org.apache.log4j.ConsoleAppender
log4j.appender.Log4JDBC.layout=org.apache.log4j.PatternLayout
log4j.appender.Log4JDBC.layout.ConversionPattern=%-5p [%d{DATE} %c]: %m%n


That's it. Start up the application and it should function exactly as it did before, but all SQL operations (made via the JNDI connection pool resource in my example) will be logged in the form:
INFO  [01 Nov 2013 12:00:00,000 jdbc.sqltiming]: SELECT NAME FROM PERSON WHERE ID=54321
{executed in 1 msec}


Notes:

Bonus Step: Trace back to the Application Code

If your issue is working what part of the application code triggered the execution of a given SQL statement, a neat feature of the log4jdbc loggers is including the class & method-name of the code that invoked the JDBC driver. As there may be a few layers between your code and the JDBC driver (hibernate > application server connection pool, etc) you can tell it what level you what to capture from.
  1. change log level to DEBUG
    log4j.logger.jdbc.sqltiming=DEBUG,Log4JDBC
  2. set the system property log4jdbc.debug.stack.prefix
    -Dlog4jdbc.debug.stack.prefix=com.example
Log statements will then be in the form:
DEBUG [01 Nov 2013 12:30:00,000 jdbc.sqltiming]:  com.example.PersonDAO.findPerson(PersonDAO.java:111)
2. SELECT NAME FROM PERSON WHERE ID=54321
{executed in 53 msec}

NB: this extra logging adds a noticeable overhead to the database usage (and timings).



Friday, August 02, 2013

Tomcat IIS Connector "request entity is too large"

Keywords:
tomcat IIS IIS7 jk connector max_packet_size packetSize "The page was not displayed because the request entity is too large"

Problem:
With IIS successfully configured with tomcat using the Apache Tomcat Connector (aside: if you haven't got that far the IIS Admin Blog - How To Configure IIS 7.0 and Tomcat is a good reference - with screenshots) you find that some users can access the web-apps ok, others cannot. They get a plain error page saying:
The page was not displayed because the request entity is too large
How do you fix it?

Solution:
The issue is with attributes in the request exceeding the AJP 8kb default (for me, the ISAPI redirector was logging the error was with the 'Authorization' attribute). You can increase this to maximum of 65Kb.

This needs to be done in the tomcat-connector and tomcat itself.

Step 1: Set max_packet_size in the worker definition

In the workers.properties file referenced by the tomcat-connection definition, set the packet size to the maximum:
worker.<worker name>.max_packet_size=65536
for example:
worker.ajp13w.max_packet_size=65536
Check the workers documentation for more information.

Step 2: Set packetSize in the AJP Connector definition

In the server.xml configuration file for tomcat, set the packet size to the maximum:
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" packetSize="65536"
        tomcatAuthentication="false" />
Check the AJP Connector documentation for more information.


You'll then need to restart tomcat and IIS Site for the changes to take effect (then hope for the best).

Monday, July 01, 2013

Querying JSON using JSONPath

Keywords:
JSON query filter evaluate JSONPath expression

Problem:
Dealing with code that's doing a fair bit of JSON processing (traversing object structures and collating the values) it leads to the question - is there a standard way to lookup or filter data from the JSON structure using a query or expression?

The same question has been already been asked on StackOverflow: Is there a query language for JSON? and the answer is essentially that there are many approaches. There's another list of approaches with examples in 8 ways to query json structures.

So if there's no 'standard' approach (for example, backed by an RFC as is the case with JSON), which approach should I pick?


Solution:
JSONPath proposed by Stefan Goessner allows for XPath-like expressions to be evaluated against JSON. What's possible with the expression syntax seems to cover most of the traversal and collating scenarios I was interested in and the JavaScript implementation is remarkably lightweight (implemented as just one function jsonPath(<object>, <expression>, <optional arguments object>)).

Here some extra expression examples (beyond those shown in the JSONPath articles and jsonpath on Google Code):

Expression Result
$ The root element (the same JSON back out - i.e. an identity transform).
$.* All child elements of the root.
$.store.book All book elements.
$.store.book[1] The second book element.
$..price The price of every element - result will be Numbers.
$.store.book[?(@.isbn=='0-553-21311-3')] The book element where isbn is '0-553-21311-3'.
$.store.book[?(@.category=='fiction' && @.price > 10)] The book element where category is 'fiction' and price is more than 10.

It seems like there's still some discussion around what's to be supported and there isn't exactly high activity on the project. So if using it, treat is as beta and evaluate if it does what you need. It's likely to be one of those things that once it gets past v0 there will be less (if any) changes to expect.

Some things to look out for:
  • Where's the latest version?
    Although the downloads page says the latest version is 0.8.0, this few years old (2007). You can access later versions (of the JavaScript source) either via the SVN path to the trunk or via the Google Code Browser. The javascript implementation lists the version as 0.8.5 - I'm not sure what the cycle is for getting this to 'release'.
  • No results returned as false
    I'd expect this to be simply an empty array [].
  • Results as Arrays of Arrays
    If querying a nested JSON structure of objects and the matching results match different parts of the tree, what you get back is a nested array structure indicating the relative location of the matches. I'd prefer to get this back as a flattened array. I guess the logic is that have the context of where the items were found and if you want, you can post-process (and flatten) the Arrays of Arrays - some useful approaches discussed on StackOverflow:Merge/flatten an Array of Arrays in JavaScript?.
  • the Object and it's properties in the results?
    In using the latest code mentioned above, it seems that - in some scenarios - where an object matches the expression the result includes the object as well as the properties as additional items in the result. For example:
    Instead of: You get:
    [
        {
            "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
        }
    ]
    
    [
        {
            "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
        },
        "fiction",
        "Herman Melville",
        "Moby Dick",
        "0-553-21311-3",
        8.99
    ]
    
    This wasn't the case with 0.8.0 and may change in future releases?


Tuesday, June 04, 2013

Stop Chrome from Prerending URLs

Keywords:
Google Chrome prefetch POST prerender random timeout speculative sockets preconnections browser learning predict network actions

Problem:
Chrome has become my browser of choice - it seems faster and is less reliant on the disk which is critical if you're on machine that's continually doing disk-intensive work (such as builds).

That speed can come at a cost. Perhaps it was an update or perhaps because of the repetition of certain actions in a web-wizard style application in development but all of a sudden using Chrome was giving random unexpected results that weren't reproducible in other browsers.

Tracing the server-side, it seems that URLs are being called - with GET requests - independently of my actions in the browser. These phantom requests include my credentials (HTTP BASIC auth) and session information (as cookies), but on the client-side (tracking Network in Developer Mode) there's no explanation for how/why/when these URLs are being hit.

Is my browser possessed?

Solution:
Short answer? YES, yes it is (kind of) possessed! What I'm seeing is Chrome predicting my next action in the web-application and hitting those URLs (on my behalf) in the interests of speed. It was initially hard to find good references for this because it seems to be referenced with various terms. Officially, it's "Prerender" and the Google Whitepaper "Web Developer's Guide to Prerendering in Chrome" describes it as:

Prerendering extends the concept of prefetching. Instead of just downloading the top-level resource, it does all of the work necessary to show the page to the user—without actually showing it until the user clicks. Prerendering behaves similarly to if a user middle-clicked on a link on a page (opening it in a background tab) and then later switched to that tab. However, in prerendering, that "background tab" is totally hidden from the user, and when the user clicks, its contents are seamlessly swapped into the same tab the user was viewing. From the user’s perspective, the page simply loads much faster than before.

As mentioned in the quote, it's separate to "Prefetching" - which is the mechanism where a page can explicitly flag a URL as safe/recommended to begin fetching.

If this was a chess program, it's like the browser is thinking a few moves ahead but instead of just anticipating moves, it's actually making them.

As raised (and debated) in Chromium Issue 85229 - this time under the term "speculative sockets" - there's no way for the server/application to opt-out or ask it not to do this.

You can view diagnostics for what URLs are being Prerendered by opening the following in a tab (if you're experiencing erroneous/random behaviour it can make for interesting reading):
chrome://net-internals/#prerender

Shouldn't GET requests be safe? As discussed in On Chrome and URL Pre-fetching, yes but surely not always 100% safe. If you have an app that has URLs that only ever get POST requests there's nothing stopping Chrome from hitting these with Prerender GETs - and if the URLs (for convenience) handle the GET requests you could be trouble. Which leads to some inconsistencies in the above mentioned whitepaper for "Situations in which prerendering is aborted" ("...Chrome may run into a situation that could potentially lead to user-visible behavior that is incorrect"):
  • POST, PUT, and DELETE XMLHTTPRequests
    False: although in your usage of an application/site a URL may only ever be invoked via POST, you can't stop it attempting the same URL with a GET, just minus the parameters.
  • Developer Tools is open
    False: In my usage anyway, using the Developer tools (trying to track Network requests) will not stop the Prerender requests being made.

Which (finally) leads to the solution - turn off Prerending. The whitepaper has a section titled "Ensuring you have prerender turned on" (despite it being enabled by default). So disabling it involves following the reverse:
  1. Click the 'three bars' icon in the top right of Chrome.
  2. Click 'Settings'
  3. Click 'Show advanced settings...'
  4. Under 'Privacy'
    • un-check the option 'Predict network actions to improve page load performance'
    • un-check 'Use a prediction service to help complete searches and URLs typed in the address bar'
      (this specifically relates to prefetch/prerender of URLs typed into the 'Omnibox' address bar - Chrome will actually be calling up the suggested sites in the background if they happen to be URLs you commonly select)
  5. Open a new tab and paste in "chrome://net-internals/#prerender"
    Confirm that it lists:
    • Prerender Enabled: false
    • Prerender Omnibox Enabled: false


Notes:
There is some confusion about the requests being made for Prerender and reports of Chrome making multiple (and unnecessary) background requests for the favicon - e.g. Issue 39402. At the server-side it will be clear that Prerender requests are for URLs that you tend to access, before you actually access them rather than URLs ending in /favicon.ico. There doesn't seem to be a way to disable favicon 'polling' but the above mentioned issue seems to indicate improvements were being considered to reduce the server load.


Sunday, April 07, 2013

Capture console output in ant - for any command or task - using Record

Keywords:
ant capture task console output stdout stderr javac jspc "Problems opening file using a recorder entry" absolute path

Problem:
Many tasks include options to capture output. Each of them different, such as exec - with the redirector option; java - with the @output attribute. What if you want to capture the output (stderr and stdout) from a task that doesn't support output capture (such as javac) or you'd like more control - start|stop|start appending output from many commands to shared file(s)?

Solution:
Record is the solution. Just BEWARE the @name attribute is treated as plain file path rather than a File attribute as in many other ant tasks. This means if supplied with a relative path it will be relative to where you're running ant from - a problem if you have ant scripts invoking other ant scripts. When path issues occur, you'll get this error:
Problems opening file using a recorder entry

Run ant with the -v option to get the full stack trace of the IOException. You'll see what path it's attempted - and failed - to use.

ALWAYS use absolute paths and you'll (hopefully) be fine.

To start recording:
<!-- (1) guarantee that you have an absolute path to the log file by setting a property with @location as the relative reference -->
<property name="build.logpath" location="${a.build.location}/sub_folder/log_file.log"/>
<!-- (2) start recording -->
<record action="start" name="${build.logpath}" loglevel="verbose"/>

All tasks that follow will have the console output (and logging if you set the loglevel attribute) go to the capture file:
<jasper2 ... />
<javac ... />
etc.

Then to stop:
<record action="stop" name="${build.logpath}"/>

Easy as that.


Friday, March 29, 2013

Use javascript to set text (with newlines) into a textarea - for IE and Firefox

Keywords:
javascript jquery textarea DOM innerHTML newlines carriage return whitespace IE firefox chrome

Problem:
Setting text with newlines into a textarea using the innerHTML attribute:
<textarea id="source" rows="4" cols="50">
A
B
C
</textarea>
<button onclick="copyText();return false;">copy -></button>
<textarea id="target" rows="4" cols="50">
</textarea>


<script type="text/javascript">
    function copyText() {
        var sourceField = document.getElementById('source');
        var targetField = document.getElementById('target');
        targetField.innerHTML = sourceField.value;
    }
</script>

Works in "most" browsers but in IE the text put into the textarea has the newline characters stripped out (replaced with a single space character). Is there a way to make this work in IE? ... and most other browsers?

Solution:
To make it work in IE, setting the text via inputField.setAttribute("value", [your text]); will preserve the newlines (i.e. the "\n" character in javascript)
var sourceField = document.getElementById('source');
var targetField = document.getElementById('target');
targetField.setAttribute("value",sourceField.value);

Only problem is that setting the attribute alone is not enough for Firefox (& Chrome - all WebKit?). For the above example, the target field will not appear to have the value from the source (though the DOM will have the value). To get them all to work? Contrive the order in which you set things:
var sourceField = document.getElementById('source');
var targetField = document.getElementById('target');
var text = sourceField.value;
targetField.innerHTML = text; // now Firefox (& Chrome) are happy - but IE has the text as one line
targetField.setAttribute("value", text); // now IE has the text as multiple lines - the change should be imperceptible 

The same code using jQuery (note that jQuery's html() function will still use innerHTML ultimately so is subject to same IE issue with newlines being stripped):
jQuery(document).ready(function($){
    var text = $(sourceField).val();
    $(targetField).html(text);
    $(targetField).val(text);
}); 

Notes:
Use of innerHTML for managing textarea content - and keeping it in-synch with the DOM - was discussed in the previous post: Firefox does not reflect input form field values via innerHTML. I'll update that post accordingly ...

Friday, November 30, 2012

Using CXF in Containers with JAX-WS handling - WebSphere/WebLogic

Keywords:
cxf jax-ws websphere weblogic annotation DisableIBMJAXWSEngine Ignore-Scanning-Packages Ignore-Scanning-Archives prefer-web-inf-classes prefer-application-packages prefer-application-resources

Problem:
So CXF is your chosen JAX-WS framework for your application - perhaps because you want your appplication to work the same way in every servlet container - tomcat included - or because you can't avoid the need to reference the implementation rather than just the pure JAX-WS spec (access to the http-session for example). While these reasons seem valid they seem to have been considered as an afterthought in containers with built in JAX-WS handling - such as WebSphere and WebLogic.

So you follow the CXF notes and perhaps blog/mail-list posts and either are in the state where: (a) the application is not working or (b) is working but you're not sure how or why. What steps can you perform to guarantee successful deployment, and (if possible) can you understand the context for them - so you can decide if they're needed for example.

Solution:
The following are useful references:
Normally for these container/class-loader issues you can get the desired behaviour by simply getting the container to load the application's libraries first (parent last). The complication in this case is the annotation processing, which seems (in my testing at least) can happen independently of the annotation processing implementation - particularly for the association of @Resource references.

To get past this, there's essentially three areas to cover:
  1. Supply JAX-WS annotation processing libraries (geronimo) that will override the container defaults - this includes all libraries that the CXF framework and annotation processing require - because nothing can be used from the container (parent)
  2. Tell the container you're handling annotations - explicitly
  3. Setup Parent-Last Class-loading - get the container to use your applications libraries before its own

Step 1: Supply JAX-WS annotation processing libraries and dependencies

There's a longer list of libraries in the CXF Notes but many of these are not specifically essential to the JAX-WS issue (the latest JAXB libraries for example will be required by CXF in a tomcat deployment). These are the libraries that appear to be need in addition to those that would have otherwise been included with the application:
  • geronimo-annotation_1.0_spec-1.1.1.jar - Annotation Processing
  • geronimo-jaxws_2.2_spec-1.1.jar - Runtime Override
  • geronimo-stax-api_1.0_spec-1.0.1.jar - Runtime Override
  • geronimo-ws-metadata_2.0_spec-1.1.3.jar - Annotation Processing
  • stax2-api-3.1.1.jar - Runtime Override
  • woodstox-core-asl-4.1.1.jar - Library Requirement
geronimo and woodstox/stax2 are the same Apache license as CXF and these libraries are supplied as part of the CXF distribution. In WebSphere you'll know it's taken effect as in deployment you'll see:
[19/10/12 8:34:46:641 EST] 00000044 AbstractInjec W   CWNEN0070W: The javax.annotation.Resource annotation class will not be recognized because it was loaded from the 
    file:/E:/IBM/WebSphere/AppServer/profiles/AppSrv01/installedApps/SERVERNode01Cell/example-app.ear/lib/geronimo-annotation_1.0_spec-1.1.1.jar location rather than from a product class loader.
[19/10/12 8:34:46:645 EST] 00000044 AbstractInjec W   CWNEN0070W: The javax.xml.ws.WebServiceRef annotation class will not be recognized because it was loaded from the 
    file:/E:/IBM/WebSphere/AppServer/profiles/AppSrv01/installedApps/SERVERNode01Cell/example-app.ear/lib/geronimo-jaxws_2.2_spec-1.1.jar location rather than from a product class loader.
The "Runtime Override" libraries listed above are essential as the overridden annotation processing code can not load certain classes from the parent - this may include classes from javax.xml.*. These 'parent prevention' issues are most likely going to be reported as java.lang.VerifyError. In WebSphere for example you'll encounter 'parent prevention' issues as:
Caused by: java.lang.VerifyError: JVMVRFY013 class loading constraint violated; 
    class=org/apache/cxf/jaxws/context/WebServiceContextImpl,
    method=getEndpointReference([Lorg/w3c/dom/Element;)Ljavax/xml/ws/EndpointReference;,
    pc=0
    at java.lang.J9VMInternals.verifyImpl(Native Method)
    at java.lang.J9VMInternals.verify(J9VMInternals.java:85)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:162)
    at org.apache.cxf.jaxws.context.WebServiceContextResourceResolver.resolve(WebServiceContextResourceResolver.java:61)

Step 2: Tell the container you're handling annotations

This seems the strangest part but both WebSphere and WebLogic will continue to report errors - in particular about the @Resource annotation. For example, on WebSphere:
[19/10/12 17:11:03:261 EST] 00000053 webapp        E com.ibm.ws.webcontainer.webapp.WebAppImpl populateJavaNameSpace SRVE8084E: An unexpected internal server error occurred while populating the namespace.
    com.ibm.wsspi.injectionengine.InjectionException: CWNEN0044E: A resource reference binding could not be found for the following resource references [org.example.hello.HelloSoapService/context], defined for the example-app component.
    at com.ibm.wsspi.injectionengine.InjectionProcessor.resolveInjectionBindings(InjectionProcessor.java:1208)
For example, on WebLogic:
<24/10/2012 2:17:27 PM EST> <Error> <J2EE> <BEA-160223> 
    <The resource-env-ref 'org.example.hello.HelloSoapService/context' declared in the standard descriptor or annotation has no JNDI name mapped to it. 
    The resource-env-ref must be mapped to a JNDI name using the resource-env-description element of the weblogic proprietary descriptor or corresponding annotation.>

For WebSphere - Disable and Ignore Annotation Scanning

There are ways to configure this globally - in the application server settings and configuration. I'll only note here the application-specific approach. This involves setting attributes in the META-INF/MANIFEST.MF of the war file.
  1. DisableIBMJAXWSEngine: true
  2. Ignore-Scanning-Packages: comma-separated list of packages where there are service implementations - and use of the @Resource and @WebService annotations
  3. Ignore-Scanning-Archives: comma-separated list of jar-file libraries where there are service implementations - and use of the @Resource and @WebService annotations
You don't necessarily have to do both 2 & 3 - use 2 if implementations are in (war-app)/WEB-INF/classes for example. It does seem setting the Ignore-Scanning-Archives setting can significantly speed application deployment - and is harmless if there is no annotation processing required. Hand-coding MANIFEST files is risky - I'd recommend using an ant task (and define all three attributes):
<target name="dist" description="make the war and ear">
        <!-- list of packages with WS implementations - which should be ignored by container annotation processing -->
        <property name="service.packages">
            org.example.hello,
            org.example.goodbye
        </property>
        <loadresource property="service.packages.delim">
            <propertyresource name="service.packages"/>
            <filterchain>
                <tabstospaces/>
                <deletecharacters chars=" "/>
                <striplinebreaks/>
            </filterchain>
        </loadresource>    
        <path id="webapp.archives">
            <fileset dir="./example-app/WEB-INF/lib">
                <include name="**/*.jar"/>
            </fileset>
        </path>
        <pathconvert property="webapp.archives.delim" refid="webapp.archives" pathsep="," dirsep="/">
            <map from="${basedir}/example-app/WEB-INF/lib/" to=''/>
        </pathconvert>
        
     <!-- Define META-INF attributes -->  
        <manifest file="./example-app/META-INF/MANIFEST.MF" mode="update" flattenAttributes="true">
            <attribute name="DisableIBMJAXWSEngine" value="true"/>
            <attribute name="Ignore-Scanning-Packages" value="${service.packages.delim}"/>
            <attribute name="Ignore-Scanning-Archives" value="${webapp.archives.delim}"/>
        </manifest>
        <copy todir="./example-app/WEB-INF/lib">
            <fileset dir="./runtime">
                <include name="**/*.*"/>
            </fileset>
        </copy>
            
        <jar destfile="example-app.war" basedir="./example-app/"
            manifest="./example-app/META-INF/MANIFEST.MF"/>       
        <ear destfile="example-app.ear" appxml="metadata/application.xml">
            <fileset dir="." includes="example-app.war"/>
            <metainf dir="metadata" includes="*.*" excludes="application.xml"/>
        </ear>
    </target>

For WebLogic - Prefer Packages and Resources

In the (ear-app)/META-INF/weblogic-application.xml you must explicitly preference the packages supplied as part of the CXF solution and the service resources these libraries include:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-application xmlns="http://www.bea.com/ns/weblogic/90">
    <xml>
        <parser-factory>
            <saxparser-factory>org.apache.xerces.jaxp.SAXParserFactoryImpl</saxparser-factory>
            <document-builder-factory>org.apache.xerces.jaxp.DocumentBuilderFactoryImpl</document-builder-factory>
            <transformer-factory>org.apache.xalan.processor.TransformerFactoryImpl</transformer-factory>
        </parser-factory>
    </xml>
    <application-param>
        <param-name>webapp.encoding.default</param-name>
        <param-value>UTF-8</param-value>
    </application-param>
    <prefer-application-packages>
        <!-- // for logging  --> 
        <package-name>org.apache.log4j.*</package-name> 
        <!-- // for jaxb  --> 
        <package-name>com.sun.xml.*</package-name> 
        <!-- // for apache commons lang/io  --> 
        <package-name>org.apache.commons.*</package-name> 
  <!-- // for spring/hibernate --> 
        <package-name>antlr.*</package-name> 
        <package-name>org.springframework.*</package-name>
        <!-- // for jstl -->
        <package-name>javax.servlet.jsp.jstl.*</package-name>
        <!-- // for jax-ws -->
        <package-name>javax.jws.*</package-name>
        <package-name>javax.ws.*</package-name>
  <!-- // xml processing -->
        <package-name>javax.xml.*</package-name>
        <package-name>javax.xml.stream.*</package-name>
        <package-name>org.xml.sax.*</package-name>
        <package-name>org.w3c.*</package-name>
        <package-name>org.apache.xmlcommons.*</package-name>
        <package-name>org.apache.xml.serializer.*</package-name>
        <package-name>org.apache.xerces.*</package-name>
        <package-name>org.apache.xalan.*</package-name>
        <package-name>com.ctc.wstx.*</package-name>
        <package-name>org.codehaus.*</package-name>        
    </prefer-application-packages>
    <prefer-application-resources> 
        <resource-name>META-INF/services/javax.ws.rs.ext.RuntimeDelegate</resource-name> 
        <resource-name>META-INF/services/javax.xml.bind.JAXBContext</resource-name> 
        <resource-name>META-INF/services/javax.xml.datatype.DatatypeFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.parsers.DocumentBuilderFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.parsers.SAXParserFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.stream.XMLEventFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.stream.XMLInputFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.stream.XMLOutputFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.transform.TransformerFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.validation.SchemaFactory</resource-name> 
        <resource-name>META-INF/services/javax.xml.ws.spi.Provider</resource-name> 
        <resource-name>META-INF/services/javax.xml.xpath.XPathFactory</resource-name> 
        <resource-name>META-INF/services/org.apache.cxf.bus.factory</resource-name> 
        <resource-name>META-INF/services/org.apache.xalan.extensions.bsf.BSFManager</resource-name> 
        <resource-name>META-INF/services/org.apache.xml.dtm.DTMManager</resource-name>
        <resource-name>META-INF/services/org.codehaus.stax2.validation.XMLValidationSchemaFactory.dtd</resource-name>
        <resource-name>META-INF/services/org.codehaus.stax2.validation.XMLValidationSchemaFactory.relaxng</resource-name>
        <resource-name>META-INF/services/org.codehaus.stax2.validation.XMLValidationSchemaFactory.w3c</resource-name>
        <resource-name>META-INF/services/org.osgi.framework.launch.FrameworkFactory</resource-name> 
        <resource-name>META-INF/services/org.relaxng.datatype.DatatypeLibraryFactory</resource-name> 
        <resource-name>META-INF/services/org.w3c.dom.DOMImplementationSourceList</resource-name> 
        <resource-name>META-INF/services/org.xml.sax.driver</resource-name> 
        <!-- // geronimo (at present) has no service such declaration (glassfish and others do) - include for future reference -->
        <resource-name>META-INF/services/com.sun.xml.ws.spi.db.BindingContextFactory</resource-name>
    </prefer-application-resources>    
</weblogic-application>

Step 3: Setup Parent-Last Class-loading

This is probably the easiest step.

For WebSphere - set flags during deployment

Note that this should be set at the ear and war (web module) level.

For WebLogic - set prefer-web-inf-classes

This doesn't seem to be a comprehensive setting based on what is required in the weblogic-application.xml file, but in the (war-app)/WEB-INF/weblogic.xml file, ensure prefer-web-inf-classes is set to true:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app 
 xmlns="http://www.bea.com/ns/weblogic/90" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-web-app.xsd"> 
    <jsp-descriptor>
        <keepgenerated>false</keepgenerated>
        <page-check-seconds>-1</page-check-seconds>
        <precompile>true</precompile>
        <precompile-continue>true</precompile-continue>
        <verbose>false</verbose>
    </jsp-descriptor>
    <container-descriptor>
        <servlet-reload-check-secs>-1</servlet-reload-check-secs>
        <prefer-web-inf-classes>true</prefer-web-inf-classes>
    </container-descriptor>
</weblogic-web-app>

Happy CXF servicing.

Tuesday, October 23, 2012

Stop Hibernate info level logging to Console in WebSphere

Keywords:
websphere hibernate logging info commons logging log4j info SystemOut.log Console stdout WAS7 WAS8.5

Problem:
The application is packaged with hibernate and configured with log4j logging (to a rolling, application-specific file - hibernate set to WARN level logging) and deployed to WebSphere with parent last class loading.

Despite all this info-level messages are being output to the WebSphere system-out/console log (in WAS_HOME\profiles\[profile_name]\logs\[server_name]\SystemOut.log).

Why is the application log4j configuration (in log4j.properties) being ignored and how can the application's hibernate logging be diverted away from the console?

Solution:
Various resources on the web describe configuring WebSphere logging or hibernate logging but the bottom of this post on Hibernate and Logging specifically describes this 'leaking' of log configuration/output and how to resolve it.

Create a commons-logging.properties with the content:
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
... and put this file in the application's classpath (WEB-INF/classes for example).



Notes:
By default, WebSphere Application Server is installed to use info level tracing (for all loggers that it knowns about). In WAS 8.5 you'll see this in the SystemOut.log:
[22/10/12 12:00:00:000 EST] 00000001 ManagerAdmin  I   TRAS0017I: The startup trace state is *=info.

You can edit this by going to (in WAS 8.5) Application Servers > [server_name] > Troubleshooting | Change log detail levels. You can specify the logging definition in plain text. For example, turning default logging to audit-level and disabling logging for the verbose com.ibm.ws.webcontainer.annotation module (this is a ':' delimited list):
*=audit: com.ibm.ws.webcontainer.annotation=off

Alternatively, use the "Components and Groups" section of the interface to expand items of the "tree" and right-click to select custom logging levels for a given "node" (NB for log4j users, the log levels may not match log4j - eg "audit" and "warning" instead of "warn").

Also interesting to note is that without the commons-logging.properties file defined in your web-app you will see every package from your application(s) and their libraries (where classes include logging definitions) included in this "Components and Groups" interface. Therefore if you see org.hibernate.* disappear from this interface you can be certain the configuration has worked.



Wednesday, July 25, 2012

Managing Oracle JDBC Memory Usage - Executive Summary

Keywords:
Oracle JDBC memory leak usage java.lang.OutOfMemoryError fetchSize white paper summary 10g 11.2

Problem:
So there appears to be memory issues with your system. Oracle JDBC drivers seem like the prime candidate (based on the heap dumps). The Oracle JDBC Memory Management white paper says as much:
The Oracle JDBC drivers can use large amounts of memory. This is a conscious design choice, to trade off large memory use for improved performance. For the most part and for most users this has proved to be a good choice. Some users have experienced problems with the amount of memory the JDBC drivers use.

The white paper is only a dozen or so pages, but it seems each JDBC version introduces new connection properties or changes the meaning of previously used properties. Is there an executive-summary/cheat-sheet/quick-reference that would essentially say what you can do for a given version?

Solution:
There doesn't seem to be, but I'll have a go ...

First, some summary points:
  • From 9i to 10g performance of the JDBC drivers has been improved "... on average about 30% faster".
  • This was achieved by a greater use a caches. The justification being "memory is relatively cheap".
  • In large scale applications with complex (and batch) data usage, there seem to be two key caches that may cause memory usage issues - the "Implicit Statement Cache" and the "Internal Buffer Cache".
  • Tuning the caches can be done via connection properties (all of which can also be defined as system "-D" properties).
    Tuning should be done in consideration of:
    • the table design (column types and sizes)
    • the query design (columns needed / batches)
    • the fetch size. Setting this incorrectly will definitely cause OutOfMemoryErrors - as seen in JCR-2892.

Now, for the connection properties:

Property

Default

Notes

Applicable for Version

10.0.2.4

11.1.0.6.0

11.1.0.7.0

11.2

oracle.jdbc.freeMemoryOnEnterImplicitCache

false

When true row-data buffers are cleared when a PreparedStatement is cached (in the "Implicit Statement Cache").

Yes (new)

Ignored
(from 11.1.0.6.0 onwards, buffers are put in a new "Internal Buffer Cache")

oracle.jdbc.maxCachedBufferSize

Integer.MAX_VALUE
(2,147,483,647 ~ 2Gb)


Sets an upper limit on the "Internal Buffer Cache".
Look out for the change in meaning from 11.1.0.7 to 11.2 - though if you use a value >30 in 11.2 it will revert to treating it as an integer. Oracle recommends: "... start with 18. If you have to set the value to less than 16, you probably need more memory."
Each connection will (may?) have its own buffer cache. So in a connection pool setup multiply the pool-size by the maxCachedBufferSize.

N/A (no "Internal Buffer Cache")

No (no way to set the size)

Yes
Set as an integer value.
102400 ~ 100Kb

Yes
Set as a log2 value.
18 = 2^18 = 262,144 ~ 256Kb

oracle.jdbc.useThreadLocalBufferCache

false

By storing the buffer cache as a TreadLocal instead of on the Connection you'll save memory if (and only if) there are less Threads than Connections. Avoid if using code that uses Connections across Threads.

N/A

N/A

Yes (new)

Yes

oracle.jdbc.implicitStatementCacheSize

0

An initial size for the "Implicit Statement Cache". But it doesn't seem that setting it to 0 or -1 will disable it, so it can perhaps be ignored for memory management issues - it may improve performance.

N/A

N/A

N/A

Yes (new)

Friday, April 20, 2012

Running Native SQL deletes or updates via Hibernate

Keywords:
hibernate manual native SQL update delete bulkUpdate child table spring

Problem:
Probably not the best idea but for performance, limitations in hibernate mappings or errors in the objects you find it'd be much easier to just run some manual SQL. Can you do this via hibernate?

Solution:
Yes you can, hibernate call this "Native SQL". This is fairly well document, but I noticed its missing an example of doing a manual update/delete - where the result is not going to give you a list() of anything.

For Query you make via createSQLQuery(...), use executeUpdate() which returns the number of rows effected.

Here an example (using the CATS/DOGS table names from the hibernate document):
Query deleteQuery = session.createSQLQuery(
    "delete from CATS "
    + "where DOG_ID in ( "
        + "select d.ID from DOGS d "
        + "where d.STATUS = ?)");
deleteQuery.setString(0, "VICIOUS");
int updated = deleteQuery.executeUpdate();

If you're integrating with hibernate via spring, the same can be done via the template-callback mechanism (where your DAO extends org.springframework.orm.hibernate3.support.HibernateDaoSupport):
Integer deletedData = (Integer)getHibernateTemplate().execute(new HibernateCallback () {
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
        // delete the data
        Query deleteQuery = session.createSQLQuery(
            "delete from CATS "
            + "where DOG_ID in ( "
                + "select d.ID from DOGS d "
                + "where d.STATUS = ?)");
        deleteQuery.setString(0, "VICIOUS");
        int updated = deleteQuery.executeUpdate();
    }
});
if (log.isDebugEnabled()) {
    log.debug("rows deleted from CATS: " + deletedData);
}

Notes:
If you're wondering if you can avoid hard coding the table references by asking hibernate for the table-name mapping, this does seem possible - Get the table name from the model in Hibernate - but this approach doesn't seem to be "public" so may disappear.


Friday, March 30, 2012

javascript object keys being sorted in some browsers

Keywords:
javascript object associative array map keys sorted ordered chrome safari webkit

Problem:
Is it the case that some browsers - WebKit, and possibly IE9 - are sorting the keys javascript objects (aka "associative-arrays", aka "maps")?

Trying the following code (note the integer keys as strings is intentional):
    var x = new Object;
    x["3"]="C";
    x["2"]="B";
    x["1"]="A";
    JSON.stringify(x);

Or as a 1-line snippet you can paste in a (modern) browser address bar:
    javascript:var x = new Object;x["3"]="C";x["2"]="B";x["1"]="A";JSON.stringify(x);

You'll get the following in Firefox:
{"3":"C","2":"B","1":"A"}

In Chrome you'll get:
{"1":"A","2":"B","3":"C"}

Is this a bug? Can you not expect the order the keys are added to be preserved?

Solution:
The short answer is no (though more appropriately but rude would be "why would you!?").

A translation in terms that a Java programmer may understand is think of the javascript object as a java.util.HashMap despite the fact it behaves a bit like a java.util.LinkedHashMap in Firefox and like a java.util.TreeMap in WebKit.

Don't code based on any expectation of the key order - which may need some thought if dealing with JSON representations of objects where there is an implicit order in the objects in "stringify-ied" form.

Some thoughts on how to maintain an order are here - How to keep an Javascript object/array ordered.

Wednesday, October 19, 2011

Can not remote desktop - no Terminal Server License Servers available

Keywords:
remote desktop console disconnected terminal server license "no Terminal Server License Servers available"

Problem:
On trying to remote desktop to a machine get the popup message:
The remote session was disconnected because there are no Terminal Server License Servers available to provide a license.
Please contact the server administrator.

A quick search suggests:
  1. Restarting the "Terminal Server" can help
    but lets say (hypothetically) that we don't know where this is and/or how to do it.
  2. Installing a Microsoft 'Hotfix'
    but after accepting the terms; filling in the hotfix request form; getting the email with the link to the hotfix executable - we (at the moment anyway) get a 500 Internal Server Error on the MS hotfix download site.

If you just need to access the machine is there another option?

Solution:
You can remote desktop to the "console" - this is effectively like 'physically' logging into the machine rather than a remote session.
mstsc /console

or on Vista / Windows Server 2008:
mstsc /admin

mstsc allows specifying the machine on the command line itself to avoid the computer selection popup (use /help option for other options):
mstsc /v:remote-server /admin

Be aware that - if someone else had a console session on this machine they'd be kicked off. If you're logged on in console/admin mode anyone with access to the terminal - if it's plugged into a monitor for example - will see what you're doing.

Wednesday, September 21, 2011

Get the generated source code for JSPs in WebLogic

Keywords:
generated JSP java class source Oracle WebLogic line numbers

Problem:
Given a stack trace such as the following:
java.lang.NullPointerException
 at jsp_servlet._web_45_inf._jsp._demo.__example._jspService(__example.java:117)
 at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
 at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
 at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
 at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
 at weblogic.servlet.internal.ServletStubImpl.onAddToMapException(ServletStubImpl.java:416)
 at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:326)
 at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:183)
 at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:526)
 at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:253)

It won't always be obvious what the issue in example.jsp corresponds to in the generated __example.java. How do you get at the generated source code for the JSPs?

Solution:
The solution involves configuring a [app_name]/WEB-INF/weblogic.xml file in your web-app. The documentation is in the WebLogic 10.3 docs - see weblogic.xml Deployment Descriptor Elements but keep in mind the file will be validated against the schema so the elements must be in the correct spot.

Below is an example - defining the jsp-descriptor with keepgenerated and working-dir elements:
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app
    xmlns="http://www.bea.com/ns/weblogic/90"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-web-app.xsd">
    <jsp-descriptor>
        <keepgenerated>true</keepgenerated>
        <working-dir>c:/my_folder/temp</working-dir>
    </jsp-descriptor>
    <container-descriptor>
        <prefer-web-inf-classes>true</prefer-web-inf-classes>
    </container-descriptor>
</weblogic-web-app>

Thursday, August 25, 2011

Beware: an empty string in Oracle is NULL

Keywords:
empty string '' CLOB varchar varchar2 text null isnull nvl NullPointerException JDBC

Problem:
There's code that is (seemingly) working with writing strings to CLOB columns and with the code from a previous post (Convert Oracle CLOBs to String) the reading of strings from the CLOB columns is working ok too ... until we get to empty strings - could it be that something is converting '' to NULL?

Here's a test case:
create table test_clobtext(

id number
, text clob
);
insert into test_clobtext values (1, 'some clob text');
insert into test_clobtext values (2, '');
select id, text from test_clobtext;

You get:
        ID TEXT

---------- ----------------
1 some clob text
2

What's the value in the 2nd row? You can use the NVL() (which is just like ISNULL()):

select id, NVL(text,'IT IS A NULL') as text from test_clobtext;

Shock, horror, this is the result:
        ID TEXT

---------- ----------------
1 some clob text
2 IT IS A NULL

... and because I'm still in disbelief:

select id, NVL(text,'IT IS A NULL') as text from test_clobtext
where text IS NULL;

This is definitely the result:
        ID TEXT

---------- ----------------
2 IT IS A NULL


So it's something to do with CLOBs? No, changing the text column to a varchar or varchar2 and you will get the same result! Is this right?

Solution:
This is apparently a well known issue (that I've only just stumbled across). A discussion is on stackoverflow: Why does Oracle treat empty string as NULL which links to more details information on ask-tom: Strings of Zero Length Not Equivalent To NULL.

It would seem that there are some scenarios where it won't be NULL but I can't reproduce this - changing the test case to have text as a char(1) still gives me NULL for the column.

The bottom line is if you're working with strings/text in a Oracle database you must expect and handle NULL values coming back - there will be no way to distinguish between whether what was originally stored was actually a NULL or an empty string ('').

Notes:
If you're dealing with CLOB columns you do have the option of storing (vendor specific) empty_clob() where you do want to distinguish between the cell being set to empty from it not being set at all (ie NULL). This post "An Empty Clob is not NULL" is a good discussion.



Monday, June 20, 2011

Convert Oracle CLOBs to String in JSTL and tag file

Keywords:
java.lang.ClassCastException oracle.sql.CLOB cast java.lang.String CLOB jstl tag requestScope requestContext pageContext jspContext

Problem:
It's annoying when SQL that works for other vendors fails for a specific one ... in this case a "text" column in a schema is defined as "clob" in the corresponding oracle schema. Problem is that this is not necessarily equivalent - especially when querying the data. This is even more complex when the SQL is in JSTL. So with the JSTL code (where textValue is a CLOB):

<sql:query var="data" >
select id,
textValue
from example
where id=?
<sql:param value="${param['id']}"/>
</sql:query>
<c:forEach items="${data.rows}" var="row">
<c:out value="${row.textValue}"/><br/>
</c:forEach>


You get the result:

oracle.sql.CLOB@e645e0
oracle.sql.CLOB@1f58913
oracle.sql.CLOB@fa6b82
...


Or if you try to use the textValue in something expecting a string, you'll get:
java.lang.ClassCastException: oracle.sql.CLOB cannot be cast to java.lang.String


How do you turn a Clob to a String without filling the JSP with vendor-specific code (leaving out the argument for not having SQL in the JSP for now)?

Solution:
Great discussion of this very issue is on the OTN Forum: JSP and CLOB. It essentially involves putting the Clob to String code in a scriptlet. To keep this vendor-neutral and take some of the "ugliness" out of the JSP I'd opt for putting this code in a tag file and stick to referencing just the java.sql.* interfaces.

Step 1: create a /WEB-INF/tags/to-string.tag tag file


(Or in a subfolder - the path must start with /WEB-INF/tags/.. if using the tagdir approach).

This takes the CLOB (or other) column value and sets it back in the request context as a String.

<%--
Can turn a CLOB to String for Oracle schema
--%>
<%@ tag body-content="empty" %>
<%@ attribute name="var" required="true" type="java.lang.String" %>
<%@ attribute name="value" required="true" type="java.lang.Object" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ tag import="java.sql.*" %>
<%@ tag import="javax.servlet.jsp.*" %>
<%
String strValue = null;
if (value == null) {
strValue = ""; // NB: oracle empty string is null
} else if (value instanceof Clob) {
Clob clob = (Clob)value;
long size = clob.length();
strValue = clob.getSubString(1, (int)size);
} else {
strValue = value.toString();
}
jspContext.setAttribute(var, strValue, PageContext.REQUEST_SCOPE);
%>


In this tag file, var is the name of the variable to define in the requestScope. Note how this is done by referencing the jspContext variable.

Step 2: Use the to-string tag for your text, clob or Other columns


This involves first defining the new taglib (putting all .tag files in tagdir in the JSP scope using the "eg" prefix in this example) and then simply using the eg:to-string tag to put the string-value of the column in a "local" requestScope variable.

<%@ taglib prefix="eg" tagdir="/WEB-INF/tags" %>
<sql:query var="data" >
select id,
textValue
from example
where id=?
<sql:param value="${param['id']}"/>
</sql:query>
<c:forEach items="${data.rows}" var="row">
<eg:to-string var="textValue" value="${row.textValue}"/>
<c:out value="${textValue}"/><br/>
</c:forEach>