J2ME + Keep-Alive + Chunking = Out-of-the-box + automagically :-)

Wondering about best practices on how to use HttpConnection with J2ME, I had a peek at the sources and to my surprise, I found out, that HttpConnection should offer both keep-alive and chunking without any additional application code (e.g. adding http headers).

The implementation of HttpConnection uses an internal connection cache, so your application code can happily create – Connector.open(“http://…”, …) – and close connections and still transparently re-use the underlying TCP-connections as per HTTP/1.1 Keep-Alive specs, provided the operations being performed on those connections do not preclude Keep-Alives (e.g. by using the request property “Connection Close”, forcing HTTP/1.0, encountering any errors, or just the server plainly rejecting keep-alives).

It is a common misconception, that in order to use Keep-Alive, the HttpConnection object should be kept open. Just don’t do that! Instead always tidy-up resources you’re fed up with, as is the case with HttpConnection that is best used for a single transaction (request-reply) only. HttpConnection will transparently take care of caching the underlying TCP socket connection for you.

HttpConnection appears to be far more powerful than most J2ME programmers suspect. My advice: If you are not completely sure whether a particular option, header or application code is required, just leave it out and see what happens. For instance, HttpConnection will either add a Content-Length header (provided the content does not exceed its output buffer) or enable chunking (again adding the appropriate header) on its own and in a way completely transparent to your application code.

I myself had to learn it the hard way after having set up an implementation for chunking of my own. Not before trying to find out about how to properly interface my implementation to HttpConnection (and peeking at its sources), I realized that it’s all there already – ready to be used for free without even having asked for it ๐Ÿ™‚

I was able to verify this behavior using a Nokia 6131 NFC mobile device (CLDC-1.1 + MIDP-2.0) and GlassFish v2ur2. It works like a charm!

Notes

The automatic keep-alive may not be what you want when your mobile pays for each second of online access. Keep-Alive can easily be disabled by calling conn.setRequestProperty( “Connection”, “close” );.

Your actual mileage may vary ๐Ÿ˜ฆ The behavior of the implementation on your phone might be inferior to the one I dealt with (Nokia with lots of implementation code from Sun – judgement derived just from looking at package names) . Nick reports about some of his amazing experiences in his post Using HTTP-Over-Socket and HTTP Proxy in J2ME Applications.

My test responder is implemented in Grails and it succeeds in chunking but fails the keep-alive test (i.e. multiple socket connections are being established) when being run in developer mode from Grails built-in Jetty-Container (i.e. grails run-app). Don’t know (and don’t care), whether this is due to Jetty or Grails running in development mode.

I would have liked to post this as a comment to Codepimps’ article at http://codepimpsdotorg.blogspot.com/2008/12/every-byte-counts.html, however I did not succeed in talking Blogger into accepting my WordPress.com account ๐Ÿ˜ฆ

Posted in Uncategorized | Leave a comment

Gmail Offline Access with Google Apps Premier Edition outside of the US

I encountered a tiny problem using Gmail Offline with Google Apps Premier, that might apply only to some non-US countries.

The Create Desktop Shortcuts action does not create any shortcut at all (at the time of this writing and using Google Chrome). So how do I access my mails when offline?

The URL to be used for accessing Google Mail (gmail.com) as given in the help pages does not apply to Google Apps accounts. Normally I just access my Gmail by browsing to http://mail.saddey.net, eventually being redirected to https://mail.google.com/a/saddey.net/. When offline, mail.saddey.net cannot be accessed.

The work-around is both trivial and effective: Just navigate directly to the very same URL that shows up in your browser after invoking Gmail while being online. For convenience, you can create a shortcut of your own just as easily by right-clicking your desktop and selecting New, Shortcut and entering the full URL (from Google’s domain).

Notes: As of now (31-jan-09), using Gmail Offline with Google Apps Premier requires:

  • A browser that is supported by the Google Labs feature (common but up-to-date ones will do)
  • The Google Labs feature (“new features”) to be enabled in your Google Apps domain settings (if you don’t know what this is, please call your admins).
  • The display language no longer needs to be set to English (US), your language might already be supported now.
  • The Google Labs feature to be enabled in your personal Gmail settings
  • Offline to be enabled in your personal Gmail Labs settings
Posted in Uncategorized | Leave a comment

How to send Alert Mails with GlassFish v2ur2

I’d like to demonstrate GlassFish configuration settings that will cause GlassFish v2ur2 (aka SJAS 9.1_02) to to send alert emails on logging errors or warnings.

A trivial task for an application server that implements a plethora of standards and offers such a slick user interface, I thought.

But I was very much mistaken. Even after having struggled for more than a day, I was unable to identify self management configuration settings that would produce alert mails on any severe or warning entry being logged.

Eventually I succeeded by adopting back level configuration settings from SJAS 8.1 (see Managing and Monitoring Sun Java System Application Server 8.1 – Declarative Alerts at the very bottom). Syntax errors and a package name had to be fixed to get <alert-service> going. What works for me within my domain.xml looks similar to:

      <thread-pools>
        <thread-pool .../>
      </thread-pools>
      <alert-service>
        <alert-subscription name="AlertSubscription1">
          <listener-config listener-class-name="com.sun.appserv.management.alert.MailAlert"
                           subscribe-listener-with="LogMBean, ServerStatusMonitor, HeapSizeMonitor">
            <property name="recipients" value="joe@company.com, jim@service.net"/>
            <property name="fromAddress" value="glassfish@company.com"/>
            <property name="subject" value="Alert From GlassFish Application Server"/>
            <property name="includeDiagnostics" value="true"/>
            <property name="mailSMTPHost" value="my.smarthost.company.com"/>
          </listener-config>
          <filter-config filter-class-name="com.sun.appserv.management.alert.MailFilter">
            <property name="filterWarningMessages" value="false"/>
          </filter-config>
        </alert-subscription>
      </alert-service>
      <management-rules ...>
      </management-rules>
    </config>
    <!-- config model with name "server-config" ends -->
  </configs>

I still would like to know, how to set up mail alerts using self administration settings (e.g. What is the object name to listen for? How to properly install the “default” Custom MBeans with GlassFish PE)?

Posted in Uncategorized | Leave a comment

Grails: Links from my first week with Grails

Never before in my life I had the opportunity to learn a new technology and put it into productive use within just a couple of days. Grails will change is changing has changed the Java and framework landscape. Using Grails, within less than 3 weeks, an application has been developed that accepts NFC-scans from mobile devices (i.e. Nokia 6131 NFC), sends notifications by email and by SMS, and renders a live view of scans as well. None of the staff involved had any previous experience with Grails whatsoever (I started implementing the domain classes and services, a colleague of mine then took over to implement the GUI while I was on vacation on the Canary Islands). Our work was targeted towards NetBeans, GlassFish and PostgreSQL.

Listed here are the links that helped us jump on the track to wealth, glory and wisdom ๐Ÿ™‚

1-2-3

Links

Pet stores, sort of:

The web service side:

Still more advanced:

Slightly off topic:

Tiddlers:

Deutsche Ecke (German corner, don’t hold your breath yet):

Watch out

Posted in English, Grails | Leave a comment

Yoigo y los Datos – Cutting down your mobile calling and internet access costs while staying in Spain

Update (Vodafone)

In Germany there is a saying “Don’t praise the day before dusk”.

Two days after having published my praise for Yoigo here, they may have uncovered my “excessive” service usage. The bright coach has now turned into a dull pumpkin: Gone are the the 80 MB for EUR 1.20. Instead, soon after having reached the first Megabyte (and having paid EUR 1.20), my connection is now slowed down to 8 kBit/s, making it next to impossible to use the data service at all (e.g. Google Mail complaining about broken network, downloading a 375kB PDF taking more than 5 minutes).1 MB per day at decent download speeds for EUR 1.20 no longer looks as if it were a bargain.

The main problem is, that there’s no reliable information on precise traffic amounts and conditions. This even applies to the status SMS you’ll receive after each session. It just states how much you paid for the session (0.000 Euros after having used up the first megabyte of traffic) but does not indicate your actual traffic usage. For my Nokia E90, 1 MB is next-to-nothing (e.g. opening Adobe’s home page just twice).

So I reverted to Vodafone and bought me a Vodafone prepaid SIM at a local Vodafone outlet, added an additional charge of EUR 60 and spent it on a month of “unlimited” Internet access. Of course, even with Vodafone, “unlimited” has certain – and in this case well documented – limits: Your first Gigabyte will fly in at maximum network speeds – up to several MBits/s (provided both, the mobile network station and your device support UMTSย  third genaration standards). Any excess traffic will be slowed down to 128 kBits/s. That’s still not too bad at all. Provided you’ll use up your Gigabyte, you’ll pay 6 Eurocents / Megabyte of traffic. A great value in my opinion with the added benefit of cost transparency. Vodofone as well offers other data packages, e.g. 1 GB of traffic without set time periods (but of cource nothing left, once your package has been used up).

A word of caution: Don’t even think of browsing without buying a data package first: You would end up paying 2 Euros for each Megabyte of traffic from your prepaid balance.

Original post (Yoigo)

Being a computer nerd on a tight budget and spending a vacation on the Canary Islands, I chose to get a Yoigo Prepaid Mobile Card in order to avoid excessive roaming costs.

Yoigo offers excellent coverage, using Vodafone (including Vodafone’s UMTS coverage) to fill in their network gaps. Rates are quite competitive, about 14 Euro Cents per minute for domestic calls.

There’s a hidden secret in their offering though: Yoigo won’t charge you more than 1.20 Euros per day for Internet access. If you have a state-of-the art Nokia mobile and want to browse from your notebook, tha fastest way to gain Internet access is to enter “internet” within your mobile’s packet access point settings, enable infrared on both your mobile and your XP/Vista notebook and use *99# for the dial-in number.

However, precise conditions of use are not being divulged to customers, so it took a couple of sessions to find out what you’ll get for your money: 1.20 Euros will buy you up to 80 MBytes at download speeds of 384 kBit/s (using UMTS coverage), your daily allowance being renewed at exactly midnight “Peninsula” time. Any excess traffic will be crippled down to about 16 8 kBit/s, eventually coming to a complete halt at about 100 MBytes (mobile unit forcibly removed from the network and unable to reconnect for a couple of minutes). It appears as though once you try to use anything near 80 MB/day, your daily allowance will be reset to just 1 MB (before your connection will be slowed down to 8 kBit/s). See Update above.

All in all, if you’re looking for a mobile provider in Spain who offers reasonable rates, and provided your mobile Internet traffic averages around 40 MB/day (perfect for email and browsing, but inadequate for uploading YouTubes), right now Yoigo may be your best bet. They sport several tariffs, e.g. one that has a monthly minimum of about 6 Euros and has lower call charges, and another one that has no monthly minimum, but incurrs slightly higher call charges. On the Canary Islands, you’ll find Yoigo at local Post Offices (services not offered by Correos themselves, but by privately owned enterprises that operate within the vicinities of Los Correos). If you need more (prepaid) traffic, you may want to take advantage of one of Vodafone’s offerings (e.g. 1 month of unlimited Internet access for 60 Euros – traffic beyound the first GB slowed down to 128 kBit/s).

Disclaimer: The information provided in this post is based on personal experience and given as is. No warranty of any kind regarding its fitness of correctness can be given. Stay googled to keep informed ๐Ÿ™‚

Posted in Uncategorized | Leave a comment

Grails: How to log within static methods

Grails injects a log object for each artifact, but these loggers are not accessible within static methods.

Here’s a quick-and-dirty code snippet sample that demonstrates how to log from a static method within domain class Account. The trick is to get the Logger by invoking org.apache.commons.logging.LogFactory.getLog(this):

import org.apache.commons.logging.LogFactory

static Account createOrFindByImei(String imei)
{
    Account result = Account.findByImei(imei)
    return result ? result  :
    saved(new Account(
            imei:imei,
            email:Login.getCurrentLogin().email,
            name:"* New Account ($imei) created at " + new Date()))
}

private static Account saved(Account account)
{
    if(account.save())
    {
        return account
    }
    LogFactory.getLog(this)
      .error("!saved: $account.errors", new Throwable("*STACKTRACE*"))
}
Posted in Uncategorized | 1 Comment

Google Talk Chatback

Half an hour ago I wanted to chat with a colleague of mine. I’m not that much into chatting, but into moving all and everything to Google Apps, so I’m on Google Talk (on my mobile as well), but my colleague is registered with Skype and MSN.

Bad luck, maybe hours of installation work ahead (I’m using a Thin Client which normally reverts to its clean boot settings on each power-up – keeping out stray viruses), tedious efforts to bar SuperChat applications from damaging the VOIP client built into my Nokia E90, forgotten passwords and other chores ahead ๐Ÿ˜ฆ

For immediate anonymous chats, there’s a quick solution: Just add Google Chatback to your website. Chats are anonymous, but they’re not public, i.e. I’ll receive a separate window for each user. So they’re quite safe, unless someone successfully pretends to be my daughter, inquiring about my credit card details.

This one uses iframes, but the badge comes in customizable flavors that don’t require iframes. Provided your mailer program sends html you can even include the chatback badge in your mails. Sadly enough, Google Mail does not allow html in your signature, so you’d have to cut-and-paste each time again.

๐Ÿ™‚

Posted in Uncategorized | Leave a comment