Handling Exceptions in Grails

Improve error handling – Exceptions

The Error Handling in Grails has changed with the latest support from Groovy. In this case we will make use of the “Declarative Controller Exception Handling” feature of Grails.

“Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is java.lang.Exception or some subclass of java.lang.Exception, that method will be invoked any time an action in that controller throws an exception of that type. See the following example”:

class ElloController  {
    def index() {
        def message="Resource was not found"
        throw new NotFoundException(message);
    }

    def handleNotFoundExceptio(NotFoundException e) {
        response.status=404
        render ("error found")
}

In the previous example, a simple blank page will the message Error not found will be shown on the invocation of the controller
Important:

  • The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the Exception argument type is the important part.
  • The exception handler methods can do anything that a controller action can do including invoking render, redirect, returning a model, etc.

We need to avoid including redundant methods in every class. Therefore traits in Grails provide a clever way to include some methods to a class. With regard to Exceptions, we create a traits groovy file including the neccessary Exception Handlers. Example:

package com.apo4.exception

trait NotFoundExceptionHandler {
    def handleNotFoundExceptio(NotFoundException e) {
        response.status=404
        render ("error found")
    }
}

This trait can be included in any controller through an implements directive. Thus our old controller becomes:

import com.apo4.exception.NotFoundExceptionHandler
import com.apo4.exception.NotFoundException

class ElloController implements NotFoundExceptionHandler {
    def index() {
        throw new NotFoundException("Resource was not found");
    }
}

As it can be seen, the methods are no longer in the controller but are moved into the traits and included from the implements directive.

Exceptions can easily be invoked in services as well. *Controllers consuming such services should have the implementation of the traits or a method to Handle the Exceptions.

import com.apo4.exception.NotFoundException
class ElloService {
    def serviceMethod() {
        throw new NotFoundException("Resource was not found - thrown from service");
    }
}

References

Dillinger uses a number of open source projects to work properly:

ZF2 – Sharing and reusing DB connection for dummies

(Post has been updated after comment from Flamur on a unneccessary code in Module/Module.php)
While we were used to pass the DB-Connection to a Register or later this practice was improved by retrieving it from the Bootstrap in Zend Framework 1, the ZF2 has a new service layer which looks like a new commodity. I am referring to the ServiceManager, which also something like a registry for different object instances.

In ZF2, the DB credentials are usually stored in the ./config/autoload/ directory. Normally all files within this directory will be loaded by the ModuleManager (you don’t need to care much at this time). The file global.php (or db.php) should look like this:

return array(
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        'aliases' => array(
            'db' => 'Zend\Db\Adapter\Adapter',
        ),
    ),
    'db' => array(
        'driver'    => 'pdo',
        'dsn'       => 'mysql:dbname=DBNAME;host=HOSTNAME',
        'username'  => 'USERNAME',
        'password'  => 'USERPASS',
        'driver_options' => array(
                        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
         ),
    ),
);

The following can then be retrieved at any place in Controller through:

$this->db = $this->getServiceLocator()->get('db');

And if you are using 3rd party modules from different vendors, who require access to your DB-adapter, you can just add the following to their config/autoload/ directory:

<?php
return array(
    'service_manager' => array(
        'aliases' => array(
            'vendor_or_any_any_name_for_zend_db_adapter' => 'db', //Same as the alias in our main global.conf
        ),
    ),
);

Why Semantic Web in Digital Libraries

Medieval Library

Malachi (the librarian) looked at me sternly: “Perhaps you do not know, or have forgotten, that only the librarian is allowed access to the library. It is therefore right and sufficient that only librarian know how to decipher these things.”
“But in what order are the books recorded in this list?” William asked. “Not by subject, it seems to me.” He did not sugges an order by author, following the same sequence as the letters of the alphabet, for this is a system I have seen adopted only in recent years, and at the same time it was rarely used.
“The library dates back to the earliest times,” Malachi said, “and the books are registered in order of their acquisition, donation, or entrance within our walls.”
“They are difficult to find, then” William observed.
“It is enough for the librarian to know them by heart …

The passage is taken from the book: “The name of the Rose” by Umberto Eco and the (fictional) episode (taking place sometime in the 14th century) is an interesting overview of the findability of information within a repository of books. Apparently, only the repositor (librarian) knew where the books were located and he was the only way to get information on the nature of the books.

It is astonishing to see how in all these centuries we have not evolved that organization of the knowledge sources which need be more accessible. We rely on social information or not-so-well organized system to find relevant knowlede or data.

Probably something that only the Semantic Web promises to solve. By annotating similar sources of knowledge through all the content within; by annotating repositories themselves as a collection of all the inner semantic information and only through a giant “web of knowledge” that can emerge in the future, related knowledge will be more accessible. (Although another problem of vast will arize, with too much information-error and little information.)

PhpCloud quick note on DSN

PhpCloud Logo Official Logo

Cloud is the new magical word of these 2 years and a lot of  solutions are moving to Clouds which basically is a set of web-apps hosted on the internet. There have been a few php-cloud solutions as well, most of them commercial and Zend (the company behind PHP), has lately launched the phpcloud.com.

I started testing a little bit the phpcloud.com with the ZendFramework 2 and immediately run in an error while configuring the MySQL Connection.

return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname={MYCONTAINER};hostname={MYCONTAINER}-db.my.phpcloud.com',
'username' => '{MYCONTAINER}',
'password' => '12345678'
),
),
);

I was getting a lot of “cannot connect to local mysql instance”.

Apparently there is an easier way of creating the DSN and username/password connection with the phpcloud:

 

$dsn = sprintf(
                'mysql:dbname=%s;host=%s',
                get_cfg_var('zend_developer_cloud.db.name'),
                get_cfg_var('zend_developer_cloud.db.host')
);

return array(
                'db' => array(
                                'driver' => 'Pdo',
                                'dsn' => $dsn,
                                'username' => get_cfg_var('zend_developer_cloud.db.username'),
                                'password' => get_cfg_var('zend_developer_cloud.db.password')
                ),
);

Google do t’u jape prioritet faqeve qe publikojne lajme origjinale

Titulli i artikullit flet vete, megjithate me fjale te tjera, faqet qe kopjojne lajme, do te penalizohen!

Ji Unik!
Ji Unik!

Ka ca kohe qe ndjehesha sikur Google po kontribuonte ne shtimin e zhurmes ne marrjen e informacionit. Zhurma nuk perbehej nga informacioni i cili buronte nga shume burime, por nga shume faqe parazitare qe mbinin si kerpurdha, pa origjinalitet dhe shpeshhere pa nje identitet te sakte pervec atij te te percjellit te sa me shume lajmeve te kopjuar per te fituar ndonje lek reklame.

Ishte folur disa here per penalizim te faqeve qe “kopjojne” informacion, por deri para ca kohesh, Google u jepte sinjal jeshil faqeve te tilla qe ne tregje te vogla si i Shqiperise shperndajne jane me te shumta proporcionalisht me faqet serioze. Njoftimin per penalizimin e faqeve te kopjuara e ka dhene Matt Cuts ne nje shkrim ne blogun e tij me titull: Algorithm change launched. Ne shkrim ai shpjegon se ka ca kohe qe po e diskutonin nje teori te tille, dhe me se fundi kane marre nje vendim. Eshte llogjike qe faqet origjinale duhet te jene te renditura me lart ne kerkim shprehet ai.

Lajmi eshte shume i mire pasi do sherbeje si nje site e faqeve parazitare, por do u jape dhe nje mesazh pune te rinjve shqiptare qe duan te ndertojne nje faqe. Qe te jesh i suksesshem ne internet, duhet te sjellesh dicka origjinale. Tani te perveshim te gjithe menget, duke filluar qe nga une i pari.

HTML 5 me logo zyrtare

HTML 5 (w3c.org) kane botuar logon zyrtare te HTML 5. Botimi i kesaj logoje nuk eshte gje tjeter vecse nje hap per te nxitur sa me pare perdorimin e kesaj gjuhe pershkrimi qe eshte shume me e fuqishme se paraardheset e saj.

Qe kur HTML 5 ka perfshire ne strukturen e saj semantiken, une jam nje nder fansat e saj dhe shume shpejt do bejme nje kalim te projekteve tona ne HTML 5.

Me shume informacione: http://www.w3.org/html/logo

Cudira shqiptare ne IT – Mail Servera brenda firewallit

Te gjithe kemi mesuar avash avash, por ka gabime te medha nga IT ne pozita te vogla por ka dhe raste te tjera. Para se ta coj me tej shkrimin duhet te sqaroj qe me IT quaj nje person i cili merr persiper te garantoje strukturen teknologjike ne nje ambient. Nje IT eshte nje programues, nese i kerkohet te programoje dicka, nje system administrator, nese i kerkohet te konfiguroje nje rrjet, apo nje elektricist qe do shtroje disa kabllo per te lidhur nje rrjet. E rendesisshme eshte qe IT te kuptoje cfare po ben dhe se si sistemi qe ai po miremban integrohet me boten reale pertej dhomes se ngushte ku po punon  …

Ne IT ka shpeshhere gabime, ne fund te fundit te gjithe gabojme dhe me thene te drejten gjerat kryesore qe mesojme i mesojme duke gabuar. Megjithate ka vende ku gabimet tolerohen dhe vende te tjera ku nuk mund te tolerohen. Psh nese une ngre nje rrjet ne shtepi per te fikur dhe ndezur televizotin nga dhoma e gjumit, dhe rrjeti lejon dhe komshiun tim qe merr internet nga i njejti Wireless, atehere gabimi nuk eshte shume i madh. Nga ana tjeter ka vende ku gabimet nuk mund te tolerohen. Vende te tilla jane ambientet serioze, ambientet ku ka shume leke e me rradhe.

Para 2 javesh ndodh nje problem me nje klient te sherbimit te hostit (www.host.al) qe ankohet se dergon emaile tek nje adrese por emailet nuk arrijne! Nje nga koleget ma kalon si problem shume i shqetesuar bashke me informacionin me poshte:

Qe nga e premtja nuk mundemi te dergojme email tek *@XXXbank.com.al. Email-et nuk me kthehen mbrapsh dhe ne XXXbank nuk shkojne. Sapo fola edhe me IT e XXXbank dhe me thote qe tek log-s e domain te tyre nuk vjen asnje email nga kompania jone. Gjithashtu sot nje email eshte derguar nga XXXbank tek domainiim.al me sukses. A mund te verfikosh dot ne shell nese behet mos ka ndonje problem me dns lookup ose dicka e tille. IT i XXXbank me siguroi qe domainim.al nuk eshte ne blacklist ne domain e tyre. Te lutem me ndihmo sepse kemi korespondece te vazhdueshme me XXXbank.

Nje verifikim i shkurter dhe pashe qe IPte e Mailserverit te tyre nuk aksesoheshin nga serveri yne. Me shume mundesi nje problem routimi ne AlbTelekom ose nje bllok ne Firewall. Kontrolloj me tej dhe IPte e regjistruara nen AlbTelekom nuk marrin asnje trafik nga asnje vend ne Gjermani, as ne Amerike, e nga askund!

C:\Users\abrahaj>tracert 217.24.241.132

Routenverfolgung zu mail.unionbank.al [217.24.241.132] über maximal 30 Abschnit
e:

1     1 ms    <1 ms    <1 ms  rtog.rz.fh-offenburg.de [141.79.160.254]
2    <1 ms    <1 ms    <1 ms  193.197.62.129
3     1 ms     1 ms     1 ms  Karlsruhe1.belwue.de [129.143.1.189]
4     3 ms     2 ms     2 ms  Mannheim1.belwue.de [129.143.1.174]
5     3 ms     4 ms     3 ms  Frankfurt1.belwue.de [129.143.1.22]
6     5 ms     5 ms     5 ms  gig1-1-0-cr01.fra.oteglobe.net [80.81.192.207]
7    54 ms    53 ms    75 ms  62.75.4.137
8    45 ms    45 ms    46 ms  62.75.4.130
9     *       71 ms    70 ms  62.75.3.30
10     *       61 ms    63 ms  telecomalbania-customerside-tirana1.al [217.24.
40.2]
11     *        *        *     Zeitüberschreitung der Anforderung.
12     *        *        *     Zeitüberschreitung der Anforderung.
13     *        *        *     Zeitüberschreitung der Anforderung.

Marr ne telefon ne AlbTelekom dhe sqaroj problemin. Nga ana tjeter nje teknik qe e kam degjuar me emer qe eshte shume i afte, por i mbytur me 100 pune si te gjithe njerezit e afte ne Shqiperi. I shpjegoj problemin, i them se i kam nisur dhe nje email me logs dhe qe po pres te bejne dicka.

Pas ca ditesh marr serish ne telefon te njejtin teknik, i shpjegoj serish problemin dhe i them qe eshte ne dem te AlbTelekom nese ka probleme te tilla. Me kerkon t’i rinis emailin dhe premton se do merret!

Pas nje jave asnje ndryshim dhe filloj te kontrolloj me tej. IPja eshte me verte e regjistruar nen AlbTelekom, por mesa duket nje tjeter operator perdorka IPte e AlbTelekom (pa vendosur informacion publik mbi IPte). Operatori i ri eshte nje kompani e specializuar per te ofruar sherbim per Bastore, Banka e te tjera aktivitete. Per t’i rene shkurt, nje kompani teper serioze qe sigurine e ka ne plan te pare.

Mesa duket IT tek operatori ka bllokuar IPte e Bankes XXX dhe mailserveri i tyre nuk eshte i aksesueshem nga asnje vend. Nderkohe IT tek Banka thote qe nuk ka logs tek serveri per emaile te ardhura nga jashte, dhe pa dyshim nuk ka asnje email te ardhur fare nga jashte. Persa kohe emailet ju punojne brenda rrjetit tuaj jeni ne rregull, per te kontaktuar me boten, mund te perdorni yahoo, gmail ose dhe @facebook se shpejti.

BIOS Password RESET

Reset BIOS Password

Just a quick note to myself and to all those that have “outdated” information on “how to remove the BIOS password”. Most of the computers today have a Jumper (sometimes in Green or blue color) that can be used to reset your bios password. Near that jumper should be a text (on the mainboard) which reads PSWD or PASSWD. Remove the jumper, power on, set a new password.

Removing the CMOS battery does not neccerily mean that the old password will go away. Not sure where those transistors store some energy, but even when you leave the PC without any power cable (USB, Monitor or anything) the password would not go away. The quickest method seems to be that nice Jumper 🙂

SQL vs noSQL

There is an interesting discussion around on wether we should stick by the old Relational Databases or go with the new hype of noSQL. noSQL looks very interesting in the fact that it does not use as much resources as RDBMS, but on the other side it lacks many functionalities.
I found the video above somewhere and it is a fun and informative video about this topic.

This version of the ClamAV engine is outdated on debian

Quick how to solve the problem with “This version of the ClamAV engine is outdated” on Debian

If you get:
[code]/etc/init.d/clamav-daemon start
* Starting ClamAV daemon clamd
LibClamAV Warning:
***********************************************************
LibClamAV Warning: *** This version of the ClamAV engine is outdated. ***
LibClamAV Warning: *** DON’T PANIC! Read http://www.clamav.net/support/faq ***
LibClamAV Warning: ***********************************************************
LibClamAV Error: cli_hex2str(): Malformed hexstring: This ClamAV version has reached End of Life! Please upgrade to version 0.95 or later. For more information see www.clamav.net/eol-clamav-094 and www.clamav.net/download (length: 169) LibClamAV Error: Problem parsing database at line 742 LibClamAV Error: Can’t load daily.ndb: Malformed database LibClamAV Error: cli_tgzload: Can’t load daily.ndb LibClamAV Error: Can’t load /var/lib/clamav/daily.cld: Malformed database
ERROR: Malformed database[/code]

The solution can be to update the clam engine from the Volatile project at Debian:
[code]echo “deb http://volatile.debian.org/debian-volatile lenny/volatile main contrib non-free” >> /etc/apt/sources.list[/code]

After that
[code]
apt-get update
apt-get install clamav
apt-get -u upgrade
[/code]

Add the repository to the sources list