Delirious Development Dialysis

December 27, 2008

Javascript mouseover effects on table rows using jQuery

Filed under: CSS, Development, JavaScript, jQuery — Lee Francis @ 10:51 am
Tags: , , ,

Introduction
Lately I’ve been getting into jQuery. On first sight the syntax can look a bit strange, but I get it now – for the most part, that is. On a related note, for a while now I’ve been “wondering” about how you do the mouseover effects you sometimes see on table rows. I’m talking about the effects where you move your mouse over a cell in table row and then the full row’s background colour changes to give the effect of highlighting the full row for selection. I really haven’t given it much thought, but I recently came across some code in a company application that got me thinking about it again so I decided time was right for to take a closer look.

Code
Originally, before the use of jQuery, your markup would look something like this:


<html>
<body>
   <table>
      <tbody>
         <tr onclick="javascript:alert('info about row 1 here')"
             onmouseover="this.style.backgroundColor='#BBA57A'"
             onmouseout="this.style.backgroundColor='#FFFFFF'"
             style="cursor:pointer;>
            <td>some table cell content here</td>
         </tr>
         <tr onclick="javascript:alert('info about row 2 here')"
             onmouseover="this.style.backgroundColor='#BBA57A'"
             onmouseout="this.style.backgroundColor='#FFFFFF'"
             style="cursor:pointer;">
            <td>some table cell content here</td>
         </tr>
         <tr ...>
            ...
            more rows and cells containing more of the same here
            ...
         </tr>
      </tbody>
   </table>
</body>
</html>

You’ll notice the obtrusive JavaScript event handling code on lines 5 to 8 and 11 to 14. This code repeats itself on every row of the table which is just annoying. The only difference between the code attached to the individual table rows is the obvious onclick event handler (here a simple alert message) which should simulate some functionality specific to a click on that unique row. As a whole this use of Javascript makes the markup somewhat more difficult to read and generally untidy. Of course it is usually the backend server code creating this kind of code in a for-loop or similar – nobody writes this stuff by hand, but that’s not the point.
So how can you use jQuery to replace this mess? The following shows a first attempt of a replacement using jQuery.


<html>
<head>
   <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript">
      $(function() {
         $('table tbody tr').mouseover(function() {
            $(this).addClass('selectedRow');
         }).mouseout(function() {
            $(this).removeClass('selectedRow');
         }).click(function() {
            alert($('td:first', this).text());
         });
      });
   </script>
   <style>
      .selectedRow {
         background-color: blue;
         cursor: pointer;
      }
   </style>
</head>
<body>
   <table border="1">
      <thead>
         <tr>
            <th>First column</th>
            <th>Second column</th>
            <th>Third column</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>This</td>
            <td>That</td>
            <td>The other</td>
         </tr>
         <tr>
            <td>Second</td>
            <td>line</td>
            <td>here</td>
         </tr>
      </tbody>
   </table>
</body>
</html>

So – I guess a brief explanation is in order. You’ll of course need the jQuery JavaScript library available in the correct location as referred to in the script tag (line 3). Apart from that, all the custom JavaScript jQuery code is happening in the script tag at the top of the page (lines 4 to 14). We are first creating a jQuery selector to select all tr tags inside a tbody tag which itself must reside within a table tag (line 6). When these tag elements are found we bind the ‘mouseover’, ‘mouseout’ and ‘click’ events to the rows (lines 6,8 and 10 respectively). The mouseover and mouseout event just add or remove a CSS class named ’selectedRow’ dynamically to or from the row which adds the effect. The CSS class itself is defined at the top of the page within the style tags just after the script. The actual mouse click functionality just returns the value of the first cell in the selected row, just as an example. This could be a unique row id or similar.
The jQuery selector makes sure the mouse click event is set to only work on tr tags that are present from within a tbody tag to avoid adding the effect to the thead header row.

So that’s all there is to it really – not too bad. It was a lot simpler than I first imagined and the jQuery code makes things nice and tidy once you get used to the chained decorator pattern syntax.

December 24, 2008

Long time, no see?

Introduction
So what gives? It’s been seven months since my last posting. Have I really been all that busy that I couldn’t find the time to create a new posting?

Well, I guess it’s partly true. I have been busy, but I’m sure I could have found the time if the motivation was there. Rest assured that my guilty conscience has been forever weighing me down for not following up my ‘promising introduction’ to the bloging world. However, I think it’s fair to say that the main reason for my absence can be best described as “self inflicted censorship” – if we can call it that. I’ve been a little uncertain of what to write that would be of interest to others, and also try to avoid pissing off the people I work with. I’ve also been a little rundown at work at times so my eagerness to share my views has not been at it’s peek. Now, a few months the wiser, I guess I’ve gained a little perspective so the picture has become a clearer.

What’s been going on?
A lot has happened during the past seven months. The department I am working for at work has grown substantially from just two people (my boss and I) to around eleven and I guess I’ve been a part of that. My new boss sets targets and does her very best to reach them. Although she is a few years my junior, I’ve learned a lot from her, and for the most part I think she is great to work with. I like her positive attitude and have found it contagious at times. I also take a personal interest in management, good management that is, so I do a little reading on the subject on the side, and have been able to share my views with her on occasion. She is keen to keep everyone in the department happy and find us work that we find interesting. It’s truly great to have a boss that cares and can relate to what I’m doing. With her coming from a Java development background herself helps tremendously and means there has been a lot more focus on Java and Open source technology than earlier. As you may have guessed, that suits me fine, and I feel I have grown a lot, both on a personal and professional level. Compared to where I was a year ago, things are looking good, although the business markets have taken a turn for the worst during the last few months, so who knows what may happen in future? Fingers crossed.

Focus change
Everyone at my present workplace seems to think I live and breath for Java, but I’ve noticed that my main interest actually lies more towards web development based on open source technology than Java development. I haven’t really been following the Java scene actively for quite some time and feel I have fallen behind on the latest API’s and frameworks. At present Java just happens to be the vehicle I use to extract content for web development. My main goal is usually the end result which usually portrays itself in the form of a web application or customer website.

For most of my career I’ve been working behind the scenes on the backend systems, but for a long time I’ve had an interest in web frontend technology. However, it seems that web frontend technology still isn’t taken all that seriously. HTML, CSS and JavaScript are considered technologies that you are expected to pick up as you go along and not really use a lot of time learning. To a certain extent this is true, but I still can’t help but find it odd that this is the case in 2008 considering just how much web development goes on in the world today. Your traditional senior programmer speaks in the language of design patterns and architecture, and although I can appreciate good backend architecture, I sometimes find the frontend a bit more fulfilling and challenging. Maybe because it’s easier to explain to to family and friends what I do for a living? Easier for them to visualize, I guess. :-)

So, needless to say and according to my current interests, the last few months have been dedicated to working on web applications, creating company web sites and the like. At times it’s been great fun and I’ve learned a lot, especially about CSS which was something I always seemed to down prioritize and found “hard” to get comfortable with. I’m not sure what I really mean when I say “hard”, but for some reason I never really got in to it – mostly down to the fact that I had read a lot about it, but never really practiced it. I could never remember all the property names and their values, which is kind of half the point, I guess. This has now changed and within the last half year I have become more fluent in CSS and have grown to like it, and appreciated it’s power. I’ve also noticed just how bad it can get when more junior developers mess it all up, or don’t think in advance. The resulting CSS becomes a nightmare. I feel there is a great deal to be done on this frontier, but a lot of senior developers don’t want to touch it. Not challenging enough, I presume, which is a shame.

Projects
Just before the summer I got assigned to a project as a backend programmer. We were given the task of creating a company web site for a larger Norwegian gas company. The customer’s technology of choice was IBM’s Web Content Management (WCM). WCM, if you are unfamiliar, is a Java portlet based product that sits on top of WebSphere Portal Server. Although I had worked with both WebSphere Portal Server and WebSphere Application Server in the past, this was a different ball game.
We were two developers assigned to the project and luckily for me the other developer was fluent in CSS and other frontend technologies. He was a couple of years my junior, but I learned a lot from him. We both struggled with WCM at first and had to overcome a relatively high learning curve trying to find a good structure and extract our content before styling, but the end result was very good. The site looks beautiful today and the customer is happy. This was a relatively new experience for me in many ways. I don’t mean to offend anyone, but this was one of the first projects I was a part of where I actually felt I learned something of interest from someone else. Looking back, it was a great experience to follow a project from beginning to end and be part of the entire process. I’m not saying everything went smooth and we had our problems along the way, but in retrospect we did a good job. It’s just a shame the the technology, WCM in this case, is not much in use in my neck of the woods. However, HTML, CSS and jQuery parts, on the other hand, are. I also learned a bit about a few other web related things, like browser compatibility and became somewhat bemused that the tools for frontend technology development are still relatively poor. Was there really life before Firefox and Firebug?

The second project I was part of was to help refactor and expand a Java web application that is part of a company service desk for employee support. Although the technology in question was once again something odd, SAP EP using Java and SAP HTMLB in this case, I was happy to be able to introduce jQuery as a frontend alternative to help create some good looking stuff on the frontend. I was also happy to refactor some of the code, which was in dire need of some attention. Parts of it still is, I’m afraid. Old style JSP code with scriptlets etc. really do suck.

The third and final project I’ve been working on this autumn (and now nearly completed) is based on the open source Java portal, Liferay. Liferay has been a kind of baby of mine for the last 12 to 15 months. A colleague introduced me to it and ever since it seems I have been associated with the product, or at least that’s what everyone thinks at the company. In this project we created a web site for a customer to help their end users recycle materials and goods. We created a great deal of Java portlets in the process using Java, JSP and JSTL. We had to use a few of the new features of JSR-286 to get things working. In this project I also introduced jQuery into my frontend code which most certainly made some code a lot easier to both read and maintain. My CSS skills came in handy as well.

Conclusion
So there you have it and that’s it for now. A brief summary of what I’ve been up to for the past few months. Hopefully, I’ll have more for you soon, but don’t be surprised if it has more to with web development than backend programming, since that’s where my interests are at present. I’ve been reading a lot lately so expect a few book reviews soon. :-)

Take care!

May 25, 2008

Creating tables in MediaWiki

Filed under: MediaWiki — Lee Francis @ 9:14 pm
Tags:

Introduction

Tables are another useful feature of MediaWiki and have a simpler, if not a bit more clumsy, syntax than their html equivalent. Personally I think this syntax is a bit strange and think it could have been made easier to use.

Creating tables

You define a table in MediaWiki by using a combination of the curly brace and a pipe character, so that is the combination “{|” to start the table and “|}” to end it. The tables contents lie between these two “tags” similar to the html <table> and </table> tags familiar from html. However, it is important to note that both the starting and ending brace/pipe combination must reside on their own separate line and no other tags apart from any table attributes may exist on those two lines.

Creating columns

You start a new column by simply using a single pipe character at the beginning of a new line. You must also remember to do this for the first row after the table definition. You can also define many columns on a single line, but then you will have to use a double pipe character sequence for that. The example later will clear things up.

Creating rows

You start a new table row using a combination of the pipe and dash characters “|-” at the beginning of a new line. As in html, each row must have the same amount of columns as the last and any empty column cells must be populated with a html space entity tag.

So all of this may sound a bit technical. So lets look at a simple table example using a few of the things we’ve just mentioned:

{|
| 1A
| 1B
| 1C
|-
| 2A
| & nbsp;
| 2C
|-
| 3A || 3B || 3C
|}

would give the following output:

Simple wiki table

Pretty basic stuff, but the syntax can get a bit untidy. Unfortunately it actually gets worse.

Adding a column header

By replacing the pipe character with an exclamation you define a table column header, so:

{|
! col1
! col2
! col3
|-
| 1A
| 1B
| 1C
|-
| 2A
| & nbsp;
| 2C
|-
| 3A || 3B || 3C
|}

gives something that should like:

Wiki table with simple column header

Notice the bold header at the top of each column.

Adding a row header

You can also do something similar for rows, so

{|
! —
! col1
! col2
! col3
|-
! row1
| 1A
| 1B
| 1C
|-
! row2
| 2A
| & nbsp;
| 2C
|-
! row3
| 3A
| 3B
| 3C
|}

gives a row header on each row, like

Wiki table with simple column and row header

Adding table attributes

The table syntax supports most table parameters familiar from html tables using a style tag. However, this is a bit of a mess as we will see in the next example. I am not a fan of mixing CSS styles with wiki syntax, but if you want them to look good then that’s what you have to do. Since these are not html tags then you can’t use a general stylesheet, but must style each element using the style attribute.

{| style=”background:red;color:black;width:50%;” border=”1″ cellpadding=”5″ cellspacing=”0″ |
! —
! col1
! col2
! col3
|- style=”background:white; color:blue”
! row1
| 1A
| 1B
| 1C
|- style=”background:white; color: blue”
! row2
| 2A
| & nbsp;
| 2C
|- style=”background:white; color:blue”
! row3
| 3A
| 3B
| 3C
|}

Gives the following output:

Wiki table with styling

March 30, 2008

My meeting with a celebrity

Last week, a colleage and myself were fortunate to participate at a one day GSE Nordic WebSphere User Group conference held at Bouvet’s offices in Oslo. One of the conference speakers was Stefan Hepper from IBM Germany. Stefan works as the WebSphere Portal Programming Model Architect and leads the programming model part of IBM’s flagship portal product, IBM WebSphere Portal Server. However, more importantly (at least to me), he had the honorable task of working as specification lead for the JSR-168 Portlet version 1.0 specification, and is currently working as specification lead on the new JSR-286 Portlet version 2.0 specification. Naturally, Stefan spoke primarily of the new features in the upcoming WebSphere Portal Server version 6.1 product in the context of JSR-286, but the two aforementioned portlet specifications influence every serious Java based portal server like IBM’s WebSphere Portal Server, SAP Enterprise Portal, Oracle Portal Server, Liferay and JBoss Portal Server, just to name but a few.

Stefan Hepper and the site authorHowever, although Stefan answered a lot of question during his talks, oddly enough, for me the highlight was sharing a taxi and a 20 minute train ride from the conference back to Gardermoen airport (main Oslo airport) where we loosely discussed portlets and portals in depth, and Stefan willingly shared his knowledge with us indiscriminately. It goes without saying that this guy really knows his “stuff”, but it was also quite fascinating to hear how a Java Community Process expert group works in practice. I admit that I knew little of how the JCP works behind the scenes before our conversation, but I got the impression that Stefan is responsible for a whole lot of the final specification work and seems to carry a “heavy burden” by leading the group. However, you won’t find a nicer guy willing to help you with anything related to Java portlet/portal development should you need to call upon him for help.

As you may know, the JSR-168 specification is implemented and supported on almost every Java based portal server. The JSR-286 specification is expected to be finished in april 2008 and introduces quite a lot of new features. If memory serves me correctly, Stefan mentioned that the specifcation API has grown by over 100% since version 1.0. IBM WebSphere Portal Server 6.1 is scheduled for release sometime in the second quarter of 2008 and will support portlets complying with either of the portlet standards. It is also possible to communicate between portlets developed on either standard something that was not possible before between the proprietary IBM Portal API and the JSR-168 implementation.

I also mentioned to Stefan that I thought it was odd that there were so few JSR-168 or porlet related books available on the market. It just so happens that he has co-written and almost finalized a Manning book that was never published. It happens to be available for free download from the Manning web site, but requires registration (free). The book is titled “Portlets and Apache Portals” and it looks good. It also seems to cover WSRP (Web Services for Remote Portlets, version 1.0) and also portlet development using JSR-127 (Java Server Faces).

March 12, 2008

Adding lists in MediaWiki

Filed under: MediaWiki — Lee Francis @ 6:18 pm
Tags: , , ,

Introduction

This is a follow up article to the ongoing postings regarding adding content in MediaWiki. The plan is to add more short posting about adding content to MediaWiki. This posting talks about lists.

You can create 3 types of lists in MediaWiki:

  • Unordered lists
  • Ordered lists
  • Definition lists

Unordered lists

Unordered lists are just the normal bullet lists probably familiar from word processing software or plain HTML. You create a new list element by using an asterisk (*) at the beginning of each line. It is important that the asterisk is at the beginning of the line for it to work. You can have no whitespace between the line start and the asterisk. The number of asterisk characters indicates the list element level, so for example:

* First element
** First subelelement
*** First sub-subelement
** Second subelement
* Second element
etc.

Will create an unordered list that gives the following output:

Unordered list example in MediaWiki

Ordered lists

Ordered lists are pretty much more of the same. However, you use the hash character (#) instead of the asterisk. To restart the automatic numbering you must insert a blank line within the list, so

# First element
## First subelement
### First sub-subelement
## Second subelement
# Second element

Gives the following output

An example of an ordered list

Combining unordered and ordered lists

It is also possible to combine the two list types to make any kind of crazy combination. Check out the following example:

# element 1
# element 2
#* element 3
#* element 4
#** element 5
#** element 6
## element 7
##* element 8
##** element 9
# element 10

Which gives this result:

Combining unordered and ordered list elements in a crazy partnership

Definition list

A definition list is a list type you expect to find in a dictionary or a glossary. The syntax is a bit different from it’s list siblings:

;First definition : definition text
;Second definition : definition text

So here we have two definition keys with their matching text definition. The output looks like this:

Example of definition list output

The definition text itself can expand over multiple lines and can also contain semicolon (;) characters as part of the text as long as the semicolon is not at the beginning of a new line. Like the other list types it is very important not to type any whitespace between the semicolon and the beginning of the new line. The colon character, however, defining the definition list, can be placed just about anywhere you like.

March 11, 2008

March 10, 2008

A few good reasons why I prefer open source software

Filed under: General rant — Lee Francis @ 10:33 pm
Tags: ,
[Ed note: I changed the title of this article from 'Why I prefer open source software' to 'A few good reasons why I prefer open source software'. My boss read my posting and correctly pointed out that there are many other good reasons why someone would prefer an open source model other than just the choice/freedom point I make. In hind site I happen agree with her. Please keep that in mind when reading.]

Introduction

Apparently I’m seen as a bit of an open source software advocate within my company. I admit that I can’t say I’m displeased with that description, but I caught myself asking why that is? And why am I happy as being seen as such?

Sure, I have purchased a “few” T-shirts from the Mozilla foundation and CafePress that help reinforce an indisputable image of my beliefs among colleagues, but still. Why do I prefer open source software over proprietary alternatives?

Choice and freedom

Open source software means different things to different people and there any many other good aspects of adopting an open source software strategy. However, I think one of the main reasons I like it boils down to promoting choice and freedom. In general, I don’t like being forced to do anything I don’t want to do. I like to make my own choices.

Choice is good

When developing software the goal is usually to create components that have high cohesion and low coupling. Well designed software enables you to react easily to change, and the lower the correlation between components, the easier it is to alter behavior. Choice is good, so when picking the software I want to use in my everyday life, or within the systems I want to build, I want to experience the same kind of freedom. I want the freedom to use a set of software components that match my specific needs, and not ones forced upon me because they coincidently just happen to be the ones my operating system supports. I want the freedom to replace any of these components at a later date, with better alternatives should I wish to do so, for whatever reason. And should the person, project or company, behind a particular software component on which I depend, decide to abandon support or further production then I have the freedom to carry on development on my own merit since I have the source code available. That is my prerogative. The choice is mine.

You can use the same analogy in other parts of life. If you are a car owner you wouldn’t accept having to fill petrol at only one brand of petrol station because your car happens to be incompatible with other pumps. Such a car just wouldn’t hit the market because nobody would buy it. The reason is apparent. No, you want the choice to shop for the best petrol price or just buy the first thing that comes along. You have the freedom to make that choice.

Paying for software

    It’s not about price. Yes, free sounds great and it’s beneficial to have the option to try something for free instead of paying for a trial license, but in general I don’t mind paying for software and have done so many times in the past. However, I’m finished paying for things I no longer need. For example, I have followed Microsoft Windows since 1991 and have purchased licenses for Windows 3.0, Windows 95, Windows 98 and Windows XP among other things. However, I can state with a high degree of certainty that Microsoft Windows XP will be the last Windows license I will ever buy. My company PC happens to use Microsoft Vista and there is absolutely nothing there that I feel I really need. 98% of my everyday needs are covered by using Kubuntu at home. Now, if only Adobe would consider open sourcing some of their products or at least offer their full portfolio on Linux…

    M$ basher

    So I guess this means I hate Microsoft? I don’t really. I dislike some of their business methods and the FUD they spread, but Microsoft is a corporation that exists to make money. That is it’s purpose – it is not a charity. Many people are unaware that when I left college my idea was to work for a company that developed Microsoft Win32 applications using C. I saw that as a great challenge and something I really wanted to do. I read many books on the subject. However, that never happened for me and I can’t say I lose sleep over it. I think I have gone on to better things, but I think it’s fair to say that I can see the view from both sides of the fence.
    I don’t really dislike the Microsoft software portfolio, but I think some of the people using and promoting the software need to take a good, long look at some of the great open source alternatives available out there and assess if the proprietary software they are recommending is really worth the price. Just what is the total cost of ownership for the paying customer?

    One thing that does annoy me is when people can’t distinguish between a PC, the Microsoft Windows operating system and the Microsoft Office suite. Of course, this is more down to their own ignorance than anything Microsoft has done [can be disputed]. It’s a shame, but the market for good software alternatives has been so bad for the last 10 years or so that people have become accustomed to seeing these components packaged together that they just see them as one and the same. That’s a tough nut to crack.

    Moving along

    The open source world is not what it once used to be. It’s still a movement, a rebellion in a way, but it is definitely growing. Open source software recently reached the boardrooms and more and more companies are reaping the benefits of developing products under an open source license. But let’s not beat about the bush. There is a lot more money involved in open source development today than ever before. Large corporations like Sun and IBM aren’t giving away software to be nice. It is clear that the mindset has changed and so have the business models.

    As I said earlier, there are many other good reasons why open software is preferable. However, I can only cover so much in one posting. However, I think the steady rise of open source software is good news for developers, corporations and consumers alike. For the first time in many years they now have the freedom to choose between several viable alternatives and more and more of them seem to be breaking free of their shackles.

    March 9, 2008

    Sending SMTP mail with Java

    Filed under: Development, Java — Lee Francis @ 7:15 pm
    Tags: , , ,

    Introduction

    So your Java application needs to send a notification mail? Not an uncommon scenario, but how to do it? Luckily this turns out to be pretty easy in it’s simplest form, but SMTP configuration can be the killer. You are of course dependent on being able to access a SMTP mail server and also possessing a little knowledge of the SMTP protocol.

    What you need

    Some years ago, Sun released the Java Mail API. It doesn’t ship along with the standard Java distribution (yet!) so you will need to download it manually. It can be found here and at the time of writing is at version 1.4.1. The Mail API depends on code from the JavaBeans Activation Framework (JAF) so you’ll need to download that package also. It can be found at this link and at the time of writing is at version 1.1.1. Make sure you add the activation.jar file from the JAF distribution to your Java classpath and you will also need both the mail.jar and smtp.jar files from the Mail API distribution to enable you to send SMTP mail.

    The code

    The code itself is straightforward enough, but as I said earlier, it’s the SMTP mail server configuration that can turn out to be the problem. Specially if the server is configured to not let you use it indiscriminately to avoid SPAM etc. This will depend on the company policy configuration settings of the SMTP server you are trying to connect to.

    OK, here’s a simple example of how it can be done…

    
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class Main {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("mail.smtp.host", "your SMTP mail server here");
            props.put("mail.debug", "true");
    
            Session session = Session.getInstance(props);
    
            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("from@here.com"));
                InternetAddress[] address = {new InternetAddress("to@somewhere.com")};
                msg.setRecipients(Message.RecipientType.TO, address);
                msg.setSubject("Mail subject title");
                msg.setSentDate(new Date());
                msg.setText("Message body string");
    
                Transport.send(msg);
            }
            catch (MessagingException e) {}
        }
    }
    

    So, to summarize, start you of by creating a Java Properties object and populating it with relevant configuration information. You need to specify the SMTP host name or IP address for the key “mail.smtp.host”. The “mail.debug” property is useful for development and will give you a hint what’s going wrong should you get into trouble. Proceed on by creating a javax.mail.Session object and passing it your properties object. To create the actual mail message use a javax.mail.internet.MimeMessage object passing along the session instance you just created. Populate the javax.mail.Message object with a valid sender address and receiver address array (mail has only one sender, but can have multiple receivers). Add a mail subject, the timestamp and of course the mail message body. Then all that remains is to actually post the message to the SMTP server. That where the hard part usually begins.
    So, not that difficult all in all, but remember to encapsulate the code in a try/catch block and catch the javax.mail.MessagingException exception type for it to compile. Handle errors appropriately, there is a lot that could possibly go wrong here.

    SMTP server authentication

    As I mentioned earlier, configuration can be the killer. These days most SMTP servers don’t let any old message pass through the system without some kind of policy checking switched on. It is likely that you will need to authenticate your application to the SMTP server when creating the session object. It is also possible that the server will attempt to validate the sender e-mail address your application is using so you need to choose it wisely since it will need to be valid in the mail domain.

    To create an authenticated session object you will need to make a few minor adjustments to the code. Create a javax.mail.Authenticator subclass and override the protected method getPasswordAuthentication. By default this method returns null, so you will have to make it return an initialized javax.mail.PasswordAuthentication object containing your username and password.

    You also need to tell the session object to use your new authentication class so add the property “mail.smtp.auth” to your Properties object and set its to “true”. Also change the code that creates the session object by using an overloaded version passing both your Properties object and an instance of your new Authenticator subclass. The new code should look something like this:

    
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class Main {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("mail.smtp.host", "your SMTP mail server here");
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true");
    
            Session session = Session.getInstance(props, new MyAuth());
    
            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("from@here.com"));
                InternetAddress[] address = {new InternetAddress("to@somewhere.com")};
                msg.setRecipients(Message.RecipientType.TO, address);
                msg.setSubject("");
                msg.setSentDate(new Date());
    
                msg.setText("Message body string");
    
                Transport.send(msg);
            }
            catch (MessagingException e) {}
        }
    }
    
    class MyAuth extends Authenticator {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("your username","your password");
        }
    }
    

    And that ought to do it! This code worked fine for me when testing with two separately configured Microsoft Exchange servers (ESMTP , version 6.0.3790.1830 and 6.0.3790.3959) in different mail domains as my SMTP server host, but only if clear text authentication (BASIC) was enabled on the Exchange server.

    In both cases the Exchange server checked my sender address and also insisted that my application authenticate itself before allowing it to post.

    March 7, 2008

    Achieving readable output with MySQL

    Filed under: Development, MySQL — Lee Francis @ 1:58 am
    Tags: ,

    Introduction

    Although I like using GUI tools for a lot of things, there are some things I feel you should be able to do without being dependent on a graphical user interface. Using the MySQL console to administer a database is one of them. More than often your only channel of access to a MySQL database server is using a SSL connection to the server host. This is often the case if the database server is configured to disallow connections from any other host than the localhost.

    A useful feature

    Most users associated with MySQL are familiar with a SQL statement of the form “SELECT * FROM table;” to retrieve table information. It’s one of the first things you learn. However, if the table in question has a lot of columns and contains a lot of records, then you are going to find the MySQL console a bit of a pain when reading the data. Check out the familiar SQL output result in the figure below.

    Default output for “SELECT * FROM table;”

    The alternative

    Of course you can limit the output listing by using a SQL WHERE clause and specifying the exact names of the columns of interest, but that is not the point of this posting and in some cases you may not be aware of column names you need to use (yes, I am aware of the ‘DESCRIBE table;’ command). As you know, you terminate each SQL statement with the default semicolon ‘;’ character. Without this character the database server console just waits for you to finish your SQL statement indefinitely, but there is an alternative. By replacing ‘;’ with ‘\g’ gives the exact same console output as before. OK, I know what you are thinking. Why is that any better? It’s not, however, replacing ‘;’ with the uppercase variant ‘\G’ is, and gives an output listing in a different, and often more readable, format listing each table record by it’s columns:

    SELECT * FROM table \G

    See the figure below showing the end of row number 2, the full row number 3, and the beginning of row number 4 from the same table as earlier:
    The alternative to using the default SQL statement terminator

    It was only recently that I stumbled across this feature, but I have found it useful on many occasions already.

    Summary

    I’m sure you can see the benefit of using this alternative statement termination character on occasion. As you can see, records with many columns are a lot easier to read without being forced to limit the record column output using a WHERE clause. I’m pretty sure that using the ‘\G’ termination character isn’t standard SQL, and not something you would want to use when terminating embedded SQL in your application, but a useful feature all the same. It definitely makes reading records easier even if the output may appear to be more verbose at first. You can of course use a WHERE clause or similar as before to narrow down your output further, but using ‘\G’ makes the output easier to read in many situations:

    SELECT * FROM table WHERE id = ’something’ \G

    March 5, 2008

    Removing default search limitations in MediaWiki and MySQL

    Filed under: Development, MediaWiki, MySQL — Lee Francis @ 1:15 am
    Tags: , , ,

    Introduction

    So let’s assume you have created a page in your Mediawiki site, named it with an appropriate page title consisting of only 3 characters, say SSL or SQL, only to find that it never shows up when searching for it in the MediaWiki site search. You have tried both uppercase and lowercase search query words, you haven’t misspelled the search query (only 3 characters, after all), and you are certain you are searching through the correct MediaWiki namespace. You are also certain that you saved the page, not only previewed it and then made the mistake of closing your browser.

    Come to think of it, that page you are 110% certain you read yesterday, referring to the exact same search query word, say ‘SSL’, doesn’t show up either when searching for either of ’ssl’ or ‘SSL’. How can that be? You didn’t delete the page by mistake, did you? This is getting annoying, but are you starting to see a pattern?

    As we will see this has nothing to do with searching the wrong MediaWiki namespace (although easy enough to do), misspelling the search query word, distinguishing between uppercase or lowercase search query words, failing to save a page edit or deleting a page by mistake. The cause is simple: by default, the MySQL database server does not fulltext index words of 3 characters or below. To make this possible, you will have to change the configuration of both MediaWiki and MySQL to enable it to search for useful words and abbreviations of character length 3, such as apt, ssh, nfs and the like.

    Editing the MediaWiki configuration

    It is simple to correct this problem, but you need access to both the web server file system and administrator privileges to the MySQL database server. Locate the LocalSettings.php file in your MediaWiki installation directory, usually a subdirectory of your web server’s document root, say /htdocs on Apache. Edit the file and add the variable wgDBminWordLen to it. Set it’s value to 3, so:

    $wgDBminWordLen = 3;

    Editing the MySQL configuration

    You must also tell the MySQL database server to index 3-letter words in fulltext indexes. This is the core of the problem and this configuration change will also apply to any application using the MySQL database server, not just MediaWiki. Add or edit the [mysqld] heading in your my.conf file with the following configuration line:

    [mysqld]
    ft_min_word_len=3

    And that’s really all there is to it!

    Recreate the MySQL table index

    So just one more step to go before you can use it. You now need to restart your MySQL database server to load the new configuration setting, and then recreate the search index. So restart your server process, open a console and proceed to enter the MySQL database you use for your MediaWiki installation. Recreate the necessary search index by typing:

    REPAIR TABLE searchindex QUICK;

    If you prefixed your MediaWiki database tables with a prefix when installing the wiki then the name of your ’searchindex’ table may be wk_searchindex or similar. A simple ‘show tables;’ query will give you a hint of the correct table name.

    Summary

    This particular fix took me a little while to find. Not that it was hidden, but I was unsure which component was limiting the search. As you have seen it turns out both MediaWiki and MySQL needed to be tweaked to correct the problem. Remember there is a reason why MySQL sets the index limitation to 3 characters by default. By changing it you will increase your index sizes leading to a performance hit. The default setting is 4 characters and I’m sure there is a statistical reason for this. Take a closer look at this page for more information on tuning the fulltext search in MySQL if you are unsure of the impact it might have.

    Next Page »

    Blog at WordPress.com.