Monday, November 4, 2013

How To show Eclipse menu in Ubuntu 13.10 Saucy Salamander

Note: The following solution also applies to Aptana Studio.

The almost new Eclipse Kepler IDE has been released with a new exciting bug for those who use Ubuntu 13.10 (Saucy Salamander).

If you're among those lucky developers, when you'll open your IDE you'll find that Eclipse upper menu is pretty useless, since clicking on menu entries nothing will happen: no submenus will show up as you expected.

So, what to do if Eclipse menu doesn't show up in Ubuntu 13.10? The best solution at the moment (until someone decides to fix this bug) is the following.




N.B.: This method takes for granted that you already created your eclipse.desktop file. If you didn't create it and you don't want to do that at the moment, you can simply run eclipse by console with this command:

$ UBUNTU_MENUPROXY= eclipse
where "eclipse" is the path to your eclipse executable. But this is just the fast way to run eclipse once. If you don't want to remember this command and use it every time you have to run Eclipse, follow the rest of this guide.

Steps!
  1. Open your eclipse.desktop file:
    sudo gedit /usr/share/applications/eclipse.desktop
    or
    sudo gedit ~/.local/share/applications/eclipse.desktop
    (Depending on your configuration.)
  2. Copy these lines in it:
    [Desktop Entry]
    Type=Application
    Name=Eclipse
    Icon=eclipse
    Exec=env UBUNTU_MENUPROXY= eclipse
    Terminal=false
    Categories=Development;IDE;Java;
    
  3. Save the file.

Yes, that's it. Did you expect something harder? Comment complaining is welcome.

If you found this post useful, please share it!

References

Monday, August 26, 2013

How To create a global InitBinder in Spring with @ControllerAdvice

Date formatting could be an annoying problem when dealing with your views. I wrote an article about it when I was facing Json problems (see How To format dates in Json within Spring 3) but, as you may know, even if you don't need to use Json in your views, you'll probably have to face some troubles with date formats.

Sometimes you can avoid all your problems simply using the specific JSTL fmt in your jsp (see references). But what to do if you can't use JSTL in your jsp, or if a simple JSTL won't solve your problems?

Someone suggests to inject an InitBinder in your controller. What an InitBinder does is to grab your data from web request parameters and bind it to your JavaBean objects. So this could be a good solution if you have to deal with different kinds of data inputs in different controllers. But what if you have to always deal, for example, with dates? You could write a specific InitBinder for each of your controllers, but this is not a good procedure if you want to maximize your code efficiency by an accurate modularization (and this should be your aim, since you're using MVC paradigm).

What I suggest you to do is to create something like a single global InitBinder, which will be activated everytime your application needs it, without any controller restriction. There's a really simple way to do so, using Spring @ControllerAdvice annotation. A class annotated with @ControllerAdvice is a class that assists every controller, and it's easily autodetected through Spring classpath scanning.

If this is your case, and you want to create an InitBinder which manages your dates parsing them in (for example) dd/MM/yyyy format, here's what you can do.

The steps!
  1. Create a DateEditor class like this:
    public class DateEditor extends PropertyEditorSupport {
     
     public void setAsText(String value) {
            try {
                setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value));
            } catch(ParseException e) {
                setValue(null);
            }
        }
    
        public String getAsText() {
         String s = "";
         if (getValue() != null) {
       s = new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
      }
         return s;
        }
    
  2. Create a class annotated with @ControllerAdvice (I called it GlobalBindingInitializer):
    @ControllerAdvice
    public class GlobalBindingInitializer {
     
     /* Initialize a global InitBinder for dates instead of cloning its code in every Controller */
     
     @InitBinder
     public void binder(WebDataBinder binder) {
      binder.registerCustomEditor(Date.class, new DateEditor());
     }
    }
    
  3. In your Spring MVC configuration file (for example webmvc-config.xml) add the lines that allow Spring to scan the package in which you created your GlobalBindingInitializer class. For example, if you created GlobalBindingInitializer in the org.example.common package:
    <context:component-scan base-package="org.example.common" />
    

There's nothing else to do for your InitBinder date formatter to work. Remember that @ControllerAdvice is an extremely helpful annotation even when you have to handle exceptions, or if you want to create a global accessible @ModelAttribute for your application.

References

Monday, August 19, 2013

How To display trailing zeros in Json within Spring 3 and Jackson

This post could be simply read as a revisitation of the one in which I explained How To format dates in Json within Spring 3. But since the problem to solve is different, I think it could be useful to write a new guide about it, even if the mechanics are quite the same.

I recently discovered that managing prices with floats is a bad idea, so I decided to change all of my "float price" variables to a more efficient BigDecimal type. I know, the use of BigDecimals is controversial too, but it presently fits my needs, so I decided to use them in my web application.

Anyway, prices types are not what I'm going to talk about now. What I discovered when I tried to put my values in a table obtained via Json, is that Json automatically trims out trailing zeros after the decimal mark. This means that if you have to display a price like 1.20 dollars, you'll probably display 1.2 instead.

So, what I needed was something that would have been able to pick up my BigDecimal from the model, format it in a string including trailing zeros, and pass it to my jsp as Json. All of this, using Spring and Jackson, a Java library for processing JSON.

I assume you've got a jsp (i.e. itemslist.jsp), a controller class (i.e. ItemController.java) and a simple java class for the objects you want to manage in your Json call (e.g. Item.java). Plus, you should have enabled Spring annotation based configuration (see the reference links at the bottom of this post).

The steps!
  1. Create a PriceJsonSerializer class (you can change the name depending on your needs) that extends JsonSerializer. Like this:
    public class PriceJsonSerializer extends JsonSerializer<BigDecimal> {
    
      @Override
      public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) 
        throws IOException, JsonProcessingException {
          jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
      }
    }
    

    As you can see, the serialize method writes in a String format the BigDecimal, ensuring that it's scaled in order to display two digits after the decimal mark (you can customize this behaviour changing the setScale parameter "2" to a higher or lower number).

    As you can see, the serialize method sets up the format you want to use for your BigDecimal, writing it in a String format.

    Important: this means that your object will reach the jsp in a String format. So if you want to perform client-side arithmetics calculations on your values (e.g., in javascript) you'll have to parse them back to a number format. For example, if you have two values a = 2 and b = 3 in your jsp, writing a + b will perform an append procedure between strings, not a sum, giving you 32 instead of 5!

  2. In Item.java class, insert the @JsonSerialize annotation above the date getters:
    @JsonSerialize(using=PriceJsonSerializer.class)
    public BigDecimal getPrice() {
     return price;
    }
    
    @JsonSerialize(using=PriceJsonSerializer.class)
    public void setPrice(BigDecimal price) {
     this.price = price;
    }
    

I hope this works for you as it does for me. If not, comment and we'll try to figure out a proper solution. Well, your comments are welcome in any way :)

References

Monday, August 12, 2013

How To Solve JSON infinite recursion Stackoverflow
(with Spring and Jackson annotations)

Infinite recursion picture

Coding in Spring 3 with JPA and Jackson is supposed to semplify your life, sparing you from writing thousand lines of code. Sometimes, though, you'll notice that all these annotations hide the real core of your application, preventing you to really understand what your code is doing (and what it is supposed to do).
This means that if you want to develop a good java application or website, you need to carefully read the docs or (more realistically) you need to understand how to read your error logs and combine them with a well-written search engine query.

This is what I had to do when I first met the problem I'm about to write about.



The problem.

I was getting a wrong JSON response while using a many-to-many relationship, that caused my application to enter in an infinite loop giving as output an infinite recursion Stackoverflow error.

Here is part of what I found in my Eclipse console:

Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain: [here is the loop]) with root cause
java.lang.StackOverflowError
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:567)
 at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:143)
 at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:118)
 at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:24)
 at com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:180)
 at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:544)
 at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:551)
 ...

and so on.

Since I was using Datatables jQuery plugin, I also had this output in my browser window:

DataTables warning (table id = 'products'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.

What I noticed is that the same database query, without JSON, was working well. So the problem (as the console in fact said) was with Jackson and Json serialization. As the docs state (see references), bi-directional references for ORM-managed beans (iBatis, Hibernate) would cause serialization to failure since they are cyclic dependencies. Since Jackson 1.6, this problem has been solved by the introduction of two new annotations: @JsonManagedReference and @JsonBackReference (and see the end of this post to give a look at the @JsonIdentityInfo annotation).

How does serialization work? (The solution in theory)
In computer science, in the context of data storage and transmission, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and resurrected later in the same or another computer environment.

For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the annoying infinite recursive loop that causes our stackoverflow error.

So, Jackson takes the forward part of the reference, for example an attribute of a java class (i.e. List<Role> roles in User class), and converts it in a json-like storage format; this is the so-called marshalling process.
Then, Jackson looks for the back part of the reference (i.e. List<User> users in Role class) and leaves it as it is, not serializing it. This part of the relationship will be re-constructed during the deserialization (unmarshalling) of the forward reference.

The solution in practice.

It's very simple. Assuming that your database query already works without JSON, all you have to do is this:

  1. Add the @JsonManagedReference In the forward part of the relationship (i.e. User.java class):
    @Entity
    public class User implements java.io.Serializable{
     
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private long id;
     
     @Column(name="name")
     private String name;
    
     @ManyToMany
     @JoinTable(name="users_roles",joinColumns=@JoinColumn(name = "user_fk"),
     inverseJoinColumns=@JoinColumn(name = "role_fk"))
     @JsonManagedReference
     private Set<Role> roles = new HashSet<Role>();
    
    ...
    
  2. Add the @JsonBackReference In the back part of the relationship (i.e. Role.java class):
    @Entity
    public class Role implements java.io.Serializable {
    
     @Id 
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;
    
     @ManyToMany(mappedBy="roles")
     @JsonBackReference
     private Set<User> users = new HashSet<User>();
    
    ...
    

The work is done. If you take a look at your firebug logs, you'll notice that the infinite recursive loop has disappeared.


Edit (02/09/2013)

Another useful annotation you could check is @JsonIdentityInfo: using it, everytime Jackson serializes your object, it will add an ID (or another attribute of your choose) to it, so that it won't entirely "scan" it again everytime. This can be useful when you've got a chain loop between more interrelated objects (for example: Order -> OrderLine -> User -> Order and over again).

In this case you've got to be careful, since you could need to read your object's attributes more than once (for example in a products list with more products that share the same seller), and this annotation prevents you to do so. I suggest to always take a look at firebug logs to check the Json response and see what's going on in your code.


References

Monday, August 5, 2013

How To format dates in Json within Spring 3


After I managed to fix the Datatables jQuery plugin, finally squeezing my "Movie" class into the awesome table I prepared in my jsp, I found out that the dates in the columns were absolutely unintelligible: they were not properly formatted, and so they were showing up as a Long useless number.
My DataTables implementation uses Json to call the informations with which I'll fill the table's columns and rows. So, what I needed was something like a "real-time date formatter" for Json, something that would have been able to pick up my Date object from the model, format it in a comprehensible string format, and pass it to my DataTables plugin as Json.
If this is your situation at the moment, you'll probabily find this guide useful, since it's not very long and not very complicated. Well, it's not complicated at all, actually.

I assume you've got a jsp (i.e. movielist.jsp), a controller class (i.e. MovieController.java) and a simple java class for the objects you want to manage in your Json call (e.g. Movie.java). Oh, you should also have enabled Spring annotation based configuration (see the reference links at the bottom of this post). So...

The steps!


1. Create a DateJsonSerializer class that extends JsonSerializer. Like this:
public class DateJsonSerializer extends JsonSerializer<date> {
 
 @Override
 public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) 
   throws IOException, JsonProcessingException {
     DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
     jgen.writeString(formatter.format(value));
 }
}

As you can see, the serialize method sets up the format you want to use for your date strings.

2. In Movie.java class, insert the @JsonSerialize annotation above the date getters:

@JsonSerialize(using=DateJsonSerializer.class)
public Date getDate_in() {
 return date_in;
}
public void setDate_in(Date date_in) {
 this.date_in = date_in;
}

That's it. Yes, your work should already be done.
If you find something not working, please comment and I'll try to figure out a proper solution.

REFERENCE LINKS:
Spring docs - Annotation type JsonSerialize
Sakae Nakajima - Spring 3 Enable Annotation based Configuration

Tuesday, July 30, 2013

How To create a customized "Access Denied" landing page
with Spring 3 and Tiles 3

https://apps.cs50.net/img/error403.gif
Your new site finally needs the last thouch.
You're wasting your time walking back and forth in your room trying to think about what to do to improve it: suddenly, you remember that time when you first saw a customized landing page for that (otherwise) annoying 403 error.
Now the question is: how the hell can I do that?

And here's the answer!


(Yes, that was an absolutely boring post introduction, but I'm not a writer. Not yet, at least.)



The steps!

1) In security-config.xml

<security:access-denied-handler error-page="/accessdenied">

2) In webmvc-config.xml

<mvc:view-controller path="/accessdenied" view-name="common.accessdenied">
</mvc:view-controller>

3) In tiles-defs.xml (your tiles definitions file) define the tile for your landing page

    <definition extends="template" name="errors.denied">
        <put-attribute name="content" value="/WEB-INF/views/denied.jsp">
    </put-attribute></definition>

Obviously, change the paths consequently to your denied.jsp location.
You're done!

Now, you just have to customize the jsp in order to show the contents you want.
I suggest you to take a look at the 404 github pages: they're awesome.

Saturday, June 15, 2013

How to solve Dell laptops fan issues in Ubuntu

When I finally bought my new Dell Inspiron laptop, I decided to take a look at the brand new Windows 8 OEM installation which I (forcedly) paid for. About 20 seconds later, I was installing the latest Ubuntu distribution. I didn't knew what I would have found, but I was happy as well.
How to solve Dell laptops fan issues in Ubuntu
Sarah Klockars-Clauser for openphoto.net


One of the main problems I faced has been that of the incredibly loud fan noise which came from my new laptop, so I began my online quest until I found i8kutils, a (partial) solution to my problem. I'm saying "partial" because we shouldn't confuse the cause and the effect: i8kutils won't solve your overheating issues, but it will help you to configure your fans in order to overwrite their exasperated and irritating default behaviour. But be warned: if your fans are running it's probably because they're trying to manage your overheating problems for you, so don't set i8kutils just to make your fans definitively shut up (unless you know what you're doing).


The steps!

1) First of all, let's download and install i8kutils. Open your terminal and write:
sudo apt-get install i8kutils
2) Now you've got to add i8k to your modules. Open the modules file:
sudo gedit /etc/modules
and add the string "i8k" (without quotes) to the file. Save and exit.

3) Create an i8k.conf file
sudo vim /etc/modprobe.d/i8k.conf
and fill it with this code:
options i8k force=1

Note: Some older guides will tell you to create a /modprobe.d/options file. The "options" file isn't used anymore on Ubuntu. What does matter is that you create a file with a .conf extension (the filename isn't important, but I decided to name it i8k.conf for clarity). So beware of older i8kmon configuration guides.

4) Now restart your computer, or run this code to make i8k run:
sudo modprobe i8k force=1
5) We will now create a i8kmon.conf file which will tell the i8kmon utility how to behave.
sudo gedit /etc/i8kmon.conf
Paste the following code in it:
# Run as daemon, override with --daemon option
set config(daemon)      0

# Automatic fan control, override with --auto option
set config(auto)        1

# Report status on stdout, override with --verbose option
set config(verbose) 1

# Status check timeout (seconds), override with --timeout option
set config(timeout) 20

# Temperature thresholds: {fan_speeds low_ac high_ac low_batt high_batt}
set config(0)   {{-1 0}  -1  40  -1  40}
set config(1)   {{-1 1}  30  60  30  60}
set config(2)   {{-1 2}  53  128  53  128}

# For computer with 2 fans, use a variant of this instead:
# Temperature thresholds: {fan_speeds low_ac high_ac low_batt high_batt}
# set config(0) {{-1 0}  -1  52  -1  65}
# set config(1) {{-1 1}  41  66  55  75}
# set config(2) {{-1 1}  55  80  65  85}
# set config(3) {{-1 2}  70 128  75 128}

# end of file

This has been edited to match my Dell Inspiron 15r 5521 fan configuration (and I hope I did it well). If you want more informations take a look at the documentation on Ubuntu Manuals: http://manpages.ubuntu.com/manpages/gutsy/man1/i8kmon.1.html

6) Now you should be able to run i8kmon from your terminal and see if (and how) it's working. Simply run:
i8kmon

Finished!

But wait...what if you want i8kmon to automatically start at boot? I'll simply copy-paste what's been written in the official documentation:
Under Debian GNU/Linux it is possible to start the daemon automatically by creating an /etc/default/i8kmon configfile containing the line "set config(daemon) 1". Note the the /etc/default/i8kmon configfile is not installed by the i8kutils package because the program is designed to be run by normal users. If you want to use it as daemon you must create the config file yourself. In this case, the --nouserconfig option can sometimes also help by limiting it to sourcing /etc/i8kmon (and not ~/.i8kmon).
Doubts: I wonder why I don't have the ~/.i8kmon file on my system, while the docs refer to it.
If you take a look in your /usr/bin/i8k you'll find that ~/.i8kmon is considered as a user configuration, while /etc/i8kmon.conf (the file we edited before) is treated as a system configuration.
If something in your configuration goes wrong (e.g. if you can't make your temperature limits work) it would be worthwhile checking if you've got this ~/.i8kmon file on your system and try to edit it, because it could be perfidiously overwriting your system configuration. If you discover something about it, please let me know.

I hope this article has been useful to you. If so, please click here and there on social buttons to make it more visible. If not, I'm waiting for your constructive comments ;)

Monday, May 27, 2013

How To build your TeX file using LaTeX on Sublime Text


How To build your TeX file using LaTeX on Sublime Text
LaTeX and Sublime Text
Sublime Text 2 (the 3rd release is about to come) is one of the smarter and most elegant editors on the scene nowadays. It comes with a lot of interesting functions, and it can easily be enriched with plugins using its awesome Package Control function.

While I was writing my thesis about Kurt Gödel I discovered LaTeX, an incredible markup language which I felt in love with; it passed just a short time before I desired to use it with Sublime Text, but when I installed the LatexTools package via Package Control I had to face a little problem in order to make it work.

First of all: I think you already installed TexLive (a LaTeX distribution with many LaTeX tools) but if you did not, you can do so by typing this in your terminal:

sudo apt-get install texlive

Now you can try (as I did) to build your .tex file in Sublime Text by pressing Ctrl+B. Unfortunately, all I got at this point was this error message:

COULD NOT COMPILE!
Attempted command:latexmk -cd -e $pdflatex = 'pdflatex %O -interaction=nonstopmode -synctex=1 %S' -f -pdf <your-tex-file-path>


Read carefully these lines: what Sublime Text is trying to tell you is that it needs the latexmk package to build your file, and you didn't previously install it.
If you're encountering the same problem, the solution is trivial: you just have to install the latexmk package. Write this you your terminal:

sudo apt-get install latexmk

Now try again: you'll find that Sublime is now correctly building your tex file.

Saturday, May 25, 2013

How To access phpMyAdmin page

Here's the case: you installed Xampp (or Lampp, as it was called until some months ago), you made it run, but now you can't access your phpMyAdmin page because you get this error message:

New Xampp Security concept
Access to the requested object is only available from the local network.
This setting can be configured in the file "httpd-xampp.conf".

So, as the message says, let's open the file:
/opt/lampp/etc/extra/httpd-xampp.conf
(its path may vary depending on your system and installation).

Now edit the lines under this comment:
# since XAMPP 1.4.3
So that they look like these:
# since XAMPP 1.4.3
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Order allow,deny
Require all granted
Allow from all
</Directory>
Now restart your Xampp and you're done!

Monday, May 20, 2013

How To activate wireless and bluetooth interfaces on Ubuntu

Context: I bought a new laptop a few weeks ago, a brand new Dell Inspiron 15r 5521, and I immediately installed Ubuntu on it (since I don't like Windows 8 and I recently have more fun with Linux-like systems).

One of the many problems I faced, due to the poor Dell compatibility with Ubuntu, is that of the wireless network keyboard key. When I disabled my WiFi pressing "Fn + F2" it worked as it should. But when I tried to have my wireless connection back, the same key combination enabled just my bluetooth connection, while the wireless kept to be disabled.


If you're facing the same problem, or even if you just want to check the status of your wireless and bluetooth interfaces, here's the way to do so. These commands are intended to be written in your terminal, so you have to open it (the default key combination on Ubuntu is "Ctrl + Alt + T").

To check your wireless interfaces status, write down:
rfkill list

This command will tell you if your interfaces are blocked, both software and hardware side.

If you notice to have some kind of problems with their status and you want to activate them, type this in your terminal:
rfkill unblock all

And you're done (you should be, at least)!

Friday, May 10, 2013

Brief intro

Hi everyone :)
Not so much about presentations: I'm just someone who spends his not-so-precious hours trying to configure some softwares, packages, drivers and other things that you could imagine to be linked with computers and informatics.

I sometimes find it hard to retrieve all the informations I'm looking for on the internet, even if there are amazing sites out there that could easily help us to resolve our programming issues. My site is a solution-container and a trouble-container as well, and I'll be happy to give a grateful feedback to those who created the guides I followed during these years of hopeless programming. I hope you'll use the same kindness with me; feel free to share my solutions for the rest.
Let's go on!