Pages

03 March, 2012

Simple Session Management for Jetty Websockets

For tracking my clients websockets on the server, I need to store the session id for each HTTP connection. Otherwise I can't  distinguish the clients, as soon as they open more than one websocket.

My current websocket backend is a very simple Jetty-based Java application. When trying to get the HTTP session id in my websocket handler, I got a No SessionManager found error. Browsing the web provided several complex solutions [1] [2] that I could reduce this very simple session handling setup, using jetty's reasonable defaults.
Server server     = new Server(8001);

SessionHandler sh = new SessionHandler(); // org.eclipse.jetty.server.session.SessionHandler
sh.setHandler(websocketHandler);          // wrap websocket handler in session handler

server.setHandler(sh);                    // set session handler as jettys default handler
server.start();
Adding just two lines of code and changing the server's default handler I got basic session handling in my jetty app. Very nice.

Ciao,
Juve

26 February, 2012

CSS 3D Text-Shadow Magic with Less.js

I just found Mark Ottos CSS-based 3D-Text. His CSS class is fixed to a certain font-size, and I decided to create a Less-class for this. Here it is:
.shadow-3d (@color#fff, @size: 20px) {
    @o: @size/80;
    @c: @color - 48;
    color: @color;
    font-size: @size;
    text-shadow:
        0 @o    0 @c - 8,
        0 @o*2  0 @c - 16,
        0 @o*3  0 @c - 24,
        0 @o*4  0 @c - 32,
        0 @o*5  0 @c - 48,
        0 @o*6  @o    rgba(0,0,0,.1),
        0 0     @o*5  rgba(0,0,0,.1),
        0 @o*1  @o*3  rgba(0,0,0,.3),
        0 @o*3  @o*5  rgba(0,0,0,.2),
        0 @o*5  @o*10 rgba(0,0,0,.25),
        0 @o*10 @o*10 rgba(0,0,0,.2),
        0 @o*20 @o*20 rgba(0,0,0,.15);
}

And here you can see it in action (via Less-compiled CSS-classes):

Big Text

Small Text


Now isn't that fancy?
Stay tuned for more magic with modern web-technologies!

-- Juve

23 February, 2012

I just can't remember bash/batch Syntax - CoffeeScript to the rescue!

I regularly need some scripts for copying files to folders or remote servers, for creating folders, checking file existence, etc. The scripts should also be able to accept parameters. Often I try to write a bash script for these tasks, but it always takes much longer than expected. Similarly, on Windows, I do the same with batch/cmd-files, whose syntax is not much better to remember than bash.

I will not do this anymore, it is too cumbersome for me!

From now on, I will use a language I know very well: JavaScript!. Might sound strange but it is actually quite easy. I use node.js as "interpreter" and call the OS functions via the child_process or fs modules.  Esp. error checking is much more versatile now!
Combine that with CoffeeScript, and take shell/batch-scripting tasks to the next level, including easy async. task execution with callbacks! Thanks to CoffeeScript, I get rid of the bad parts of JavaScript. Here is a simple copy script as example (replace the echo cmd with a copy command of your choice)
fs     = require("fs")
exec   = require("child_process").exec
files  = process.argv.slice 2
target = files.pop()     #last arg is target dir/name

stop_onerror = true
error_count  = 0

copy_next = ->
    if files.length == 0 then stop()
    else
        file = files.pop()
        exec "echo copying #{file} to #{target}", (error, out) ->
            console.log out.trim()
            if error?
                console.error "ERROR(#{error_count++})! copy of #{file} failed"
            if error? && stop_onerror then stop() else copy_next()

stop = ->
    if error_count > 0
        console.log "Files copied (with #{error_count} errors)."
    else
        console.log "All files copied successfully."

usage = -> console.log '''
    Usage (with node)
        node   script.js     file1 file2 file3 ... target

    Usage (with coffee)
        coffee script.coffee file1 file2 file3 ... target
    '''

if files.length > 0 && target? then fs.stat target, (error, fstat) ->
    if error? then console.log "#{target} not found!"
    else console.log "copying #{files} to #{target}"; copy_next()
else usage()
This basic script just mimics a normal copy command and is therefore rather useless. But it shows that you can easily combine node.js' file-system functions with operating system calls via exec, and that it is really easy to add more features, such as automatic target-dir creation, file-renames, error logging, etc. Esp. such error checking and other conditional stuff is really cumbersome in plain bash/batch scripting.

Ciao, Juve

19 February, 2012

To prototype or not to prototype?

I am using jsperf a lot lately. Here is another interesting result:

Prototype-based object creation is lightning fast, compared to returning plain objects from simple functions. (see my test on jsperf)



But using prototype-based stuff usually forces you to access properties via this
which is an additional lookup in the prototype chain, that will add some overhead when accessing these object a lot. (see my other test on jsperf)



For you as a JavaScript developer, this means you have to consider the following.

  • Is my code creating a lot of (similar) objects? Then you should setup some reusable types by using prototypes.
  • Is my code accessing properties of some of my objects a lot? Then you should get rid of the access via this and add some for form of property caching in local variables.
Ciao,
Juve

07 November, 2011

Freemind to Mediawiki via CoffeeScript

Check out my new project at Github. I wrote a little Freemind to Mediawiki converter using CoffeeScript.

https://github.com/ubunatic/mm2wiki

CoffeeScript does really a good job for writing such software. Parsers, writers, and other data processing stuff can be easily done, thanks to CoffeeScript comprehensions and other smart language features.
Together with running all code running smoothly via node.js... Really nice!

-- written on an iPad, typing long text, and copying links is horrible ;)

11 October, 2011

Whitening SumatraPDF

I am using SumatraPDF as OSS alternative for the heavyweight Adobe Reader.
Sumatra is lightning fast and I like it more than Evince, which I used before.

One thing that bugged me was the ugly yellow background. It makes the tool and unfortunately also it's website look unprofessional. Here is how you can change that - at least the tool, not the web site ;)

  1. Start SumatraPDF.exe at least once. You may have to "open with..." it with a pdf file first.
  2. Fire up regedit and find (Strg+F) "SumatraPDF.exe". You need to find a key named: HKEY_USERS\...\Software\Classes\Applications\SumatraPDF.exe\shell\open\command
  3. There you should find a value named: (Default) that points to your Sumatra executable (see my screenshot)
  4. Double-click the (Default) value and add:  -bg-color 0xffffff between the "...SumatraPDF.exe" and the "%1" (as in my screenshot)
  5. Done! 
More Sumatra command line parameters can be found here: http://blog.kowalczyk.info/software/sumatrapdf/manual.html


17 July, 2011

Making command line JavaScript ready for node.js AND rhino


I have several command line scripts for doing repetitive chores. As seen in a previous post, I used rhino to run the scripts. But since node.js has been arising, I guess many developer will use that one as JavaScript interpreter. It also starts a bit faster that rhino.

The problem is that the two are not very compatible since the hooks to the operating system are named differently. This will lead to errors when one engine executes scripts designed for the other.

Here is a workaround that can make basic scripts, not using too many internals, compatible with each other. It works well for my string conversion scripts.
var args = arguments;

//initalize for node.js/rhino compatibility
if(typeof print === 'undefined') print = console.log;
if(typeof console === 'undefined') console = { log: print };
if(typeof process !== 'undefined') args = process.argv.splice(2); 
This script does two things:
  1. It maps the command line arguments to args. Node.js stores them in process.argv and rhino in the default arguments array.
  2. It will merge the basic logging functionality of rhino and node.js, mapping node.js' console.log to rhino's print function and vice versa.
That's it! I hope you can make use of this little hint.

Ciao,
Juve