VirtualBox error “VT-x is disabled in the BIOS. (VERR_VMX_MSR_VMXON_DISABLED)”

After updating my Fedora 19 x64 I tried to open a VM I have installed on it but received this error:

VT-x is disabled in the BIOS. (VERR_VMX_MSR_VMXON_DISABLED)

It is supposed that I had to enable some VT-x configuration in the BIOS, but I’ve never touch the configuration before or after the update, so that couldn’t be the problem.
The current VirtualBox version installed is 4.3.4 and kernel is 3.11.10.

If you are in the same situation as me (you can’t change or you don’t want to change the BIOS config), what you can do is touch the VM. First, get the name and UUID of the VM you want to fix:

VBoxManage list vms
"My Guest VM Name" {e6b08efd-0453-497b-b934-ff8ad17baad3}

This gives you the VM’s name and UUID. Then turn off the long mode flag:

VBoxManage modifyvm "My Guest VM Name" --longmode off

Tha bad side of this is that I don’t know why it got broken after the update, the good thing is that I can continue working.

Android: Could not access the Package Manager. Is the system running?

I work on several little Android apps which I update sometimes. One or two years ago I was using Eclipse for that, and it worked and works well, but several months ago I changed to Android Studio. This new tool is based on IntelliJ and it’s very comfortable, but it’s in an early stage and sometimes does strange things.

After last update to 0.3.2 version I experimented an error I never had before, or at least I don’t recall to have it. Trying to running the app in the phone emulator I got this error when Android Studio was installing the app through the package manager:

DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.elpaso.android.gpro.ps"
Could not access the Package Manager. Is the system running?

Obviously the system was running, and all of this was working before the update, as usual, so I was a bit concerned because when this kind of strange things happen, it means you’re going to waste time searching for a solution. Well, finally I found the solution, it was easier than I thought… simply unlock the emulator sliding the lock icon. After unlocking it I ran the process again and the app was installed right.

P.S.: Always use a real phone if you can when working with Android apps, it’s lot of times faster.

Redirect after AJAX request / Control authentication failure after AJAX request

Last two days I’ve been dealing with a problem I’ve had with some of the projects I work on. For our Java web apps we use an authentication/authorization filter that redirects to a login page after an authentication/authorization error. This error can be a login error, a session timeout or other things.

Redirect calls are managed by browsers without problems, they do the request for the new location and the login page is presented to you. But if your app does AJAX requests, as every app nowadays does, you’ll get into troubles, the browser won’t do any redirection, so your app will stay in the same page as before the request, and probably the user will be annoyed because your app doesn’t respond or does strange things. The login page won’t be shown until the user clicks on a non AJAX component (menu, link or so), or does a refresh.

Usually the authentication filter does a sendRedirect to the login page when there is an authentication problem:

response.sendRedirect(response.encodeRedirectURL(url));
response.flushBuffer();

So after some research I found that doing a manual redirect should solve the problem with AJAX calls. Really I didn’t know why doing this would solve the problem, but I tried it:

...
if (isAjax(request)) {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='UTF-8'?>");
    sb.append("<partial-response><redirect url=\"").append(response.encodeRedirectURL(url.toString())).append("\"/></partial-response>");
    response.getWriter().print(sb.toString());
    response.flushBuffer();
}

private boolean isAjax(HttpServletRequest request) {
    return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}

Even I tried to send a redirect HTTP’s 302 code or adding a Location header… without any succeed:

if (isAjax(request)) {
    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", response.encodeRedirectURL(url.toString()));
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='UTF-8'?>");
    sb.append("<partial-response><redirect url=\"").append(response.encodeRedirectURL(url.toString())).append("\"/></partial-response>");
    response.getWriter().print(sb.toString());
    response.flushBuffer();
}

private boolean isAjax(HttpServletRequest request) {
    return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}

Then I tried to solve it from the other side, thus is, the client. I didn’t like it, because it is easier to distribute a JAR file with the authentication filter solution than telling people what they must do in every app they are developing. Although we have projects with JSP/JQuery or Seam 2, the last apps we’re working on use Primefaces, so I tried to find a solution related to this framework. First I tried to catch onComplete events within ajaxStatus Primefaces tag, but this component doesn’t pass the XMLHttpRequest argument to the callbacks, also I tried to bind a callback to onComplete events at body or document level, but any result was good.

Finally I went for a more drastic and I think the most secure solution: Setting up every AJAX call that could be made within our apps to do what I want when an authentication error raised. For this, JQuery has a solution, the $.ajaxSetup function. With it you can define at a global level how AJAX calls behave, and when I say at a global level I mean that every AJAX call from your code, or from whatever library or framework you are using will do what you define with this function. So first of all I changed the HTTP code the filter was sending, instead of a 302 now it sends a 401 (unauthorized), then I defined the behaviour of AJAX calls after receiving this code:

First the changes in the Java code:

if (isAjax(request)) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setHeader("Location", response.encodeRedirectURL(url.toString()));
    response.flushBuffer();
}
private boolean isAjax(HttpServletRequest request) {
    return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}

Now the Javascript code:

function requestUnauthorized(xhr) {
    window.location.href = xhr.getResponseHeader("Location");
}
 
(function($) {
    $.ajaxSetup({
        statusCode: {
            401: requestUnauthorized,
        }
    });
})(window.jQuery);

The syntax…

(function($){.....})(window.jQuery) 

…means that you’re defining an anonymous function with an parameter called $, that will be self-executed with window.jQuery as value. It’s better to use window.jQuery because some libraries or frameworks rename jQuery to $, $$ or whatever they want.

And that’s all, you have to put the Javascript code somewhere that is visible for the whole app.

Validador de Javascript en Eclipse

Como he visto que la entrada Javascript validator problem in Eclipse es bastante popular lo voy a traducir al español para los lectores hispanohablantes.

Este es un problema que me ha pasado con varios proyectos de tipo ‘Web Dynamic’. Cada vez que el proyecto se compila Eclipse me da este error:

“Errors occurred during the build.
Errors running builder ‘JavaScript Validator’ on project ‘some-project’.
java.lang.NullPointerException”

En un principio parece que el validador de javascript está lanzando la excepción NullPointerException, así que probablemente lo primero que intentas es deshabilitar el validador de Javascript ‘Client-side Javascript’ desde Project->Properties->Validation… pero ya te digo que el problema no es ese, debes ir a Project->Properties->Builders y ahí deshabilitar el ‘Javascript Validator’.

Problema resuelto. En realidad no es un verdadero problema, pero el mensaje es bastante molesto si aparece cada vez que se compila el proyecto…

iText: Adding web links at an absolute position in Java

A problem I have had to solve recently has been adding links within PDFs. At work we use a private library to create PDFs. This library uses iText (obvious) to work, and one of the users’ requirements is the possibility of having fields that are links to a web site. The links must look like web links (underlined and blue text) and must be positioned in specific places, so absolute positioning is a must.

After searching and trying different solutions, I have finally figured out how to do it. As always, it’s an easy solution.
This code is based on iText 2.1.7, I know there are some new methods that do some of this things in shorter ways, but this version doesn’t have them. First of all I create the link in an underlined and blue font:

// Underlined, courier and 10px font size
Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.UNDERLINE);
// Blue
font.setColor(0, 0, 255);
// We need a Chunk in order to have a font's style
Chunk chunk = new Chunk("Google", font);
Anchor anchor = new Anchor(chunk);
// Link
anchor.setReference("http://www.google.com");

Then the paragraph is positioned in some coordinates X and Y:

// I take the coordinates from a text field which is defined within a
// PDF template, but you can position the link wherever you want.
float[] coords = form.getFieldPositions("field.name");
// In my case I center the link vertically
float coordY = coords[2] + ((coords[4] - coords[2]) / 2);
// Show the link
// You need to get the PdfContentByte object
// It depends on how you are working with the PDF document
PdfContentByte cb = ... 
ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, anchor, coords[1], coordY, 0);

Publish button disabled (greyed out) in Aptana plugin for Eclipse 4.2 (Juno)

This problem begun happening when I had upgraded to Eclipse 4.2 (Juno) and installed the Aptana’s 3 plugin. I have some PHP projects and I like Aptana’s plugin because it lets you synchronize your project with a local directory or a remote host, but when I moved the mouse over the Publish button associated with the project, it became disabled (greyed out)!. That is very annoying, but have an easy solution thanks to Chris William.

You only have to download this patch and copy it into eclipse/dropins/plugins directory, restart Eclipse and voilá, the button will work like a charm.