Sunday, October 19, 2014

Getting Crazy with Restlet: Method Not Allowed (405)

Are you getting crazy with Restlet in your recent project?


You have a Java SE project and you decided to give it a shoot at Restlet? Well that a nice choice besides some defects in their current documentation. But if you found yourself facing errors with "Method Not Allowed" here goes some solutions that worked for me.

  1. Include this function on your Application class:

       private static Form configureRestForm(Response response) {
            Form responseHeaders = (Form) response.getAttributes().get("org.restlet.http.headers");
    
            if (responseHeaders == null) {
                responseHeaders = new Form();
                response.getAttributes().put("org.restlet.http.headers", responseHeaders);
            }
    
            responseHeaders.add("Access-Control-Allow-Origin", "*");
            responseHeaders.add("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
            responseHeaders.add("Access-Control-Allow-Headers", "Content-Type");
            responseHeaders.add("Access-Control-Allow-Credentials", "false");
            responseHeaders.add("Access-Control-Max-Age", "60");
    
            return responseHeaders;
        }
    


    Then on your ServerResource class on the first line call it like this configureRestForm(getResponse()).

  2. Secondly and most important, if you are using Restlet current version (2.2), do not be creative like I did trying to use Java 1.8, if you do so, this is what going to happen:

    1. For Stand Alone Servers, it will work just fine;

    2. For Servers using a Component with your Application Class, that contain the createInboundRoute method overridden, your ServerResources will not be accessible.

      This happens because there is some kind of incompatibility between the way Restlet gets your annotated methods (@Get, @Post, @Put, ...) and Java 1.8.

      And so, if you debug Restlet code you will be able to see that on the class ServerResource on the get() method, Restlet is not capable of detecting your annotated methods!

      So, just switch to Java 1.7 and everything will automagically work!
      By the way I found this when stopping for a break after some hours trying to figure out the problem, and then it hit me, annotations must be related with the Java version... I hope Restlet fixes this in future, but for now, I'll have to stick with Java 1.7.

Hope this helped you figuring out a solution.

Alternatively you can look at my code here on bitbucket (look for rest package).




Thursday, May 15, 2014

Bomberman Android Game over Wi-Fi Direct (Coming Soon)

Hi Folks, there is been a while since my last post! I've been doing some projects @university and by the end of this semester I'll get back to this article, where I'll write about Wi-Fi Direct insights, covering some group merging and splitting concepts.

I've been developing the Bomberman game for android, in the past month, and the game main features include a distributed component over Wi-Fi Direct, which is a very interesting topic to share with you all.

I'm still on the rush to end this, so for now I let you with the picture of whats going on here @ my home office... as you can see, I'm still trying to put all the code together fixing some bugs and dealing with this distributed component of the game...



See you soon ;] .

Thursday, March 27, 2014

Ignore OSX Mavericks Specific Updates on App Store

So you love the way that your new Mavericks always keeps your apps up to date, everything is going just fine, until something happens... you realized that you have a bunch of new updates for some apps that you would like to ignore... But as you looked under settings, cmd+click over update button and all sorts of things you got frustrated because, guess what... That functionality was removed from this new OSX version!

You have been in app support forums, googled the web and nothing, and then you found my blog!

Well, come in you are welcome. The way to solve this will involve opening your terminal, so start by opening it:


  • Is it open? Nice, lets proceed. To install updates from you shell you can use an osx app called "softwareupdate":

    ~ softwareupdate -h
    usage: softwareupdate  [ ...]
    
     -l | --list  List all appropriate updates
     -d | --download  Download Only
     -i | --install  Install
      

  • Now to list the updates that you are seeing in your app store, you can type:

    sudo softwareupdate -l
    

    This will list all the your available updates in the form of:
    * <label>-<version>
          <update description>
    * <label>-<version>
          <update description>
    ...
    

  • To ignore a specific update you just have to do:

    sudo softwareupdate --ignore 

Bellow is an example of use:

Imagine that, Mr. Jonh Doe installed Final Cut Pro version X.Y specific for some work he was doing, and then updates started dropping in his app store (OSX Maverics), so all he had to do after finding my blog was:

➜~  sudo softwareupdate -l                  
Software Update Tool
Copyright 2002-2012 Apple Inc.

Finding available software
Software Update found the following new or updated software:
   * FCPContent-1.0
 Final Cut Pro X Supplemental Content (1.0), 622238K [recommended]

➜~  sudo softwareupdate --ignore "FCPContent"
Ignored updates:
(
    FCPContent
)  

Notice that, between the first and the second command the app store red notification icon, disappeared finally.

Wednesday, February 19, 2014

Fixing Windows Registry broken permissions through SysInternals

If you are a Software Developer or Systems Administrators, and you are not familiar with Sys Internals, then you should read this article, because although I address a very specific problem here, I'm completely sure that what I'm going to tell you, will help you for sure during your path in the field, specially when dealing with Windows.

It was being a very long day, setting up all the .NET solutions, Visual Studio 2008, Visual Basic 6.0, COM Libraries registration, SQL Server, Git for versioning and source control, but I did it all.

After, I sat at my sofa and said to myself, "Nice Work"! But just before turning my machine off, I remembered that I didn't add that reference to MSXML v4 to my VB6 project... So, to prevent having nightmares about that, I just connected to the server and decided to add the reference, but it turns out that, I faced this instead:
That was about to spoil my night... but 2 hours later I found the solution, so I decided to share it with you, hoping that no one else, needs to pull off hair from their head cracking this up.

I hope you are familiar with SysInternals, a couple of tools developed by Microsoft employees to help you out diagnosing and dealing with the "guts of the beast" (Windows).

Let's start by analyzing the error message "Error accessing the system registry", well this doesn't say much does it? Or it actually says enough if you know the right tools. Notice this is a big problem, so we need to use Divide and Conquer or you will not solve this in an acceptable time range :) .

  • So VB6.exe says: "Error accessing the system register." right?
  • Now to understand what VB6.exe is accessing in the register, we need to use the sys internals tool: Process Monitor (just download it to your desktop and let's proceed);

    This tool will show you what register keys are being accessed by the applications running in your machine, although to find what we want we will filter the information, adding the following rules:

    - exclude: process name is not VB6.exe
  • After doing this, go to your VB6.exe and try to open the References window again. You will now see a lot of RegOpenKey operations in Process Monitor, that's it, we are getting closer to the origin of the problem;
  • If you look closer to the RegOpenKey entries in Process Monitor, you will see that we have a column called 'result', if you filter this column by 'ACCESS DENIED' (I found this by inspecting all values in this column), you will trim your results to just a few entries, and those entries are more easily handled because they represent the register keys that your VB6.exe is trying to read without success, and that's why you see that error message!

So now we just need to fix the permissions to that register keys right?! Well, it's not that easy I must say, because a register key can contain sub keys, and if the permissions are really mess up, you will not be able to change the permissions of the keys, and even if you are able to fix some of the permissions, do this for all the keys and their sub keys it's impractical in general.

In my case I ran regedit from a command line in administrator mode, and not even this way I was able to change the permissions of the register entries (keys)! Why? Because when the ACL's (Access Control Lists) of windows register entries get broken, you will not be able to change them, unless you are the SYSTEM account! An account that you can't use directly and is like GOD mode in Windows OS! 

Because of this, the first solution may seem to throw the Server out off the window :], but there is something we can do to fix this, which is more wise than the first solution. What if, we have a way to run a process as the SYSTEM account? 

Hum, there is one... sys internals has a tool for that called PsExec (psexec).
You can run it from the shell (cmd) like this:

psexec.exe -i -d -s cmd

This will open another command line window that executes commands as the SYSTEM account, so now we are ready to run the ultimate tool that will get our register keys fixed for good, the SubInACL. SubInACL is a command-line tool that enables administrators to obtain security information about files, registry keys, and services, and transfer this information from user to user, from local or global group to group, and from domain to domain.

Note that if you run this tool just as an administrator you will not have permissions to fix all the entries with broken ACL (permissions), you need to run it as SYSTEM to succeed on this task.

Now to run subinacl.exe I recommend you to create a batch file (.bat), for my case I just wanted to run the script for the register containers "HKEY_CLASSES_ROOT\TypeLib" so my script aims to this, but you can point to other containers.

My script to reset the permissions looks like this:

#navigate to the folder where subinacl is installed
cd /d "%programfiles% (x86)\Windows Resource Kits\Tools"

#this fixes the permissions for all subcontainers of 'HCR\TypeLib'
subinacl /errorlog="subinacl-debug.txt" /subkeyreg HKEY_CLASSES_ROOT\TypeLib 
         /grant=administrators=f /grant=system=f /grant=users=r /setowner=administrators

#this fixes the permissions for the container 'HCR\TypeLib'
subinacl /errorlog="subinacl-debug.txt" /keyreg HKEY_CLASSES_ROOT\TypeLib 
         /grant=administrators=f /grant=system=f /grant=users=r /setowner=administrators

#this opens the log file, containing debug info about the fix operations
notepad subinacl-debug.txt

Now you should call this script from within the command line opened before as SYSTEM. After running this, all you permissions with broken ACL's in Process Monitor should be fixed and when going to References Window now, inside Visual Studio 6 you should be able to see your references again without the initial error!

And that's it, did you see how we solve this? By dividing and conquering the solution?
So my advice is, when facing a problem like this, always try to look for all the details and analyze everything carefully. And above all, remember that, we should not blame Microsoft for this.

The reason for this kind of things is related to all the automatic stuff that happens under the hood when someone decides to start installing everything they remember in the machine, and like everything, sometimes things go wrong.

Windows does it's best to bring the joy of "next, next" experience to their users, but sometimes, this is not possible and you must know your machine to know how to fix the problems yourself. Hopefully this tends to be a rare situation, if that's not your case, and you face problems with your server every week then something are going wrong between the keyboard and the chair somewhere in the process :) .

Hope you enjoyed my article and that you got your problem solved.


Wednesday, February 12, 2014

Bit Manipulation in StackOverflow

I was preparing to get some sleep when I stumped with this question on StackOverflow:"Need to store a string values into a int instead of a 4 byte sized char array". Owhhhh... I totally flipped, sorry the enthusiasm, everybody as addictions, some drink, others smoke, I'm addicted to programming, because when I do it there is something in the code that makes me feel zen!

So the problem is:

1 9 2 . 1 6 8 . 0 0 0 . 0 0 1
How to store this in an int (32 bits)?

Hum, let's see: 2^8 = 0-255 (stores values from 0 to 255)

2^(8 + 8 + 8 + 8) = 2^32 = sizeof(int) = 4 nice!

We can store 4 numbers from 0 to 255 in it, great!

Draft of solution:

int ipaddress = 0; //0x00000000
ipaddress = (192 <<; 32 - 8*1) || (168 << 32 - 8*2) || (0 << 32 - 8*3) || 1; //0x2CBE1AFA01

classA_part = (ipaddress & 0xff000000) >> (32-8*1)
classB_part = ipaddress & 0xff0000
classC_part = ipaddress & 0xff00
classD_part = ipaddress & 0xff

So couple minutes after I read this, I just come with this solution, and it worked like a charm:

#define UPPER32 24
#define UPPER16 16
#define UPPER8  8

int main(void)
{
    int ipaddr = 192 << UPPER32 | 168 << UPPER16 | 0 << UPPER8 | 1; //192 168 000 001
    
    printf("ip address: %d.%d.%d.%d\n",
        (ipaddr & 0xff000000) >> UPPER32,
        (ipaddr & 0xff0000) >> UPPER16,
        (ipaddr & 0xff00) >> UPPER8,
        (ipaddr & 0xff)
    );
    
    return 0;
}

P.S: Yes, couple of minutes, but I'll be humble about this, today I drunk about 2 RedBulls and some coffees, so I'm kind of electric, as you can see... I'm still writing in my blog, while I should be sleeping about an 1 hour ago :) .

Continuing, notice that, the code written as it is, can be strange for some, not everybody wants to deal with bits, so a more elegant approach is possible by simplifying my initial solution, using some macros:

#define UPPER32 24
#define UPPER16 16
#define UPPER8  8

#define IPADDRESS(a,b,c,d)    (a << UPPER32 | b << UPPER16 | c << UPPER8 | d)
#define IPADDRESS_CLASS_A(ip) (((ip & 0xff000000) >> UPPER32) & 0xff)
#define IPADDRESS_CLASS_B(ip) ((ip & 0xff0000) >> UPPER16)
#define IPADDRESS_CLASS_C(ip) ((ip & 0xff00) >> UPPER8)
#define IPADDRESS_CLASS_D(ip) (ipaddr & 0xff)

#define IPADDRESS_FORMAT       "%d.%d.%d.%d"
#define EXTRACT_IPADDR(ip)    
          IPADDRESS_CLASS_A(ip), IPADDRESS_CLASS_B(ip), IPADDRESS_CLASS_C(ip), IPADDRESS_CLASS_D(ip)

int main(void)
{
    int ipaddr = IPADDRESS(192,168,0,1); //192 168 000 001
    printf("ip address: " IPADDRESS_FORMAT "\n", EXTRACT_IPADDR(ipaddr));
    return 0;
}

The clean version looks very much better! 
Note, that the params a,b,c,d in macro IPADDRESS refer to the network classes of the ip address (Class A, B, C, D).

Hope you liked it and stay tuned!

Tuesday, February 11, 2014

Object Oriented Programming in JavaScript (Part 1)

There is been a while since my last post, I've been occupied studying for my exams mainly, also, this semester, my teams in two class projects decided to take vacations, and I ended up with extra load. Anyways, my experience was good, because the projects were really interesting, one was about secure communications via SSL, between an Educational Grades Submission System and the other was about Cacti, a Network Monitoring Tool that allows you to draw beautiful graphics about almost everything that can be extracted via shell scripting! All my semesters in the university tend to show me, that the Team factor is the most important part of any software project.

This post will be about Object Oriented Programming in JavaScript: Classes and Encapsulation, since my first experience with JavaScript I always felt like there were thousand ways to achieve a task due to the high flexibility of the language, although with expertise and some knowledge, it's in fact possible to work with JavaScript in an Object Oriented way.

Because of this, I think that is fundamental for every JavaScript Programmer to learn, how to program in this language in an OO way. 

Just in case you are really asking the question "Why is that? What's wrong with function foo(){ alert('bar'); } in my code? It works!", well the direct answer is, it depends, and it depends on the lifetime of you code, if you wrote that function for a website that will be active just for a weekend event, then your code is great, don't bother improving it. 

But if your code is suppose to be read, modified or even fixed by others, you will want to improve your code, or that or you will endup taking lunch alone :) , while your colleagues will be pissed at you because of the time they took to understand your code logic. Please notice that, master the fundamentals of what OO defends is just like for example, UML, why learn UML? It's boring as hell, It's a pain to do it well, and again, It's boring. And the key answer to that is, we interact with people and it's important that all speak or know how to speak in the same language.

The Concept of Object Oriented Programming, is made of 3 fundamental key concepts:
  • Encapsulation;
  • Inheritance;
  • Polimorphism.

I will show you, how to achieve each of this key concepts, in a series of articles, being this about Classes and Encapsulation.

The first think you need to know is how to create a class:

/* class Book */
function Book(){
   ...
}

Hey, stop! But function is analog to a method in OO programming right? Well, if you're writing a function Book with the objective of using it together with the operator new then function should be read as class, this is one of the reasons why you should master OO programming in JavaScript  (P.S: comments are very important too, always comment your code)!

Now, creating a full class with methods, constructors and everything:

/* class Book */
function Book(){
   /* private variables */
   var _name,
       _description,
       _isbn,
       _authors;

   /* get/set/property for field 'name' */
   this.getName = function(){ return _name; }
   this.setName = function(name){ _name = name; }

   /* get/set/property for field 'description' */
   this.getDescription = function(){ return _description; }
   this.setDescription = function(desc){ _description = desc; }

   /* get/set/property for field 'isbn' */
   this.getISBN = function(){ return _isbn; }
   this.setName = function(isbn){ _isbn = isbn; }

   /* get/set/property for field 'authors' */
   this.getAuthors = function(){ return _authors; }
   this.addAuthor = function(author){ _authors.push(author); }

   //constructor-code
   //read bellow (will talk about this)
   _authors = [];
}
In the code above you can see that we have private fields prefixed with "_", this is just a code convention, the reason why they are private is because they are declared as var fieldname inside of the function Book, so their scope is limited to the code running inside function Book.

Also you can see that we have methods declared like this this.methodname = function(){}, so this type of methods are called privileged methods, because they are methods that have access to private variables.

We have a constructor too, see the comments in the end of our function Book? All the code inside the function Book is the constructor, by convention, we can put constructor specific code in the end of the function Book, although at the end of this article you will see the right way to do it.

By the way, have I said that functions in javascript have a context of their own and they are are all seen as objects? No? Well, let me use the code above, the code above as a problem, what will happen if we call the keyword this, inside of the function getAuthors? let's say... like this this._authors? What will happen, is an undefined exception, because in the context of the anonymous function defined in the this.getAuthors, _authors is not defined.

What? Yes, it's true, this happens because of something I haven't told you before, function(){ } is an anonymous function, and this inside of it is referring to the anonymous function, not the function Book. We will see later how to handle this.

Now a class with a good constructor:

/* class Book */
function Book(){
   /* private variables */
   var _name,
       _description,
       _isbn,
       _authors;
   
   (function Book_(){
      _authors = [];
   }).apply(this, arguments);
   
   /* get/set/property for field 'name' */
   this.getName = function(){ return _name; }
   this.setName = function(name){ _name = name; }
   
   /* get/set/property for field 'description' */
   this.getDescription = function(){ return _description; }
   this.setDescription = function(desc){ _description = desc; }
   
   /* get/set/property for field 'isbn' */
   this.getISBN = function(){ return _isbn; }
   this.setName = function(isbn){ _isbn = isbn; }

   /* get/set/property for field 'authors' */
   this.getAuthors = function(){ return _authors; }
   this.addAuthor = function(author){ _authors.push(author); }
}

Now when the function Book is instantiated, all the code inside of it, will be executed, and when the code (function Book_(){  }).apply(this, arguments) is called, what will happen is that, the function Book_ will be called with the arguments passed to the class Book! The variable arguments exists in every javascript function and represents an array of the parameters passed to it, so for example if you call some function like this foo(a,b,c,d,e), arguments will be [a,b,c,d,e].

The this in the apply function makes the this keyword inside Book_ point to the Book function instead, which is more useful since the this of the Book_ function is pretty much useless.

This means that now we can do this var x = this.getName(); inside of the constructor Book_, you need to use this to access getName the same way you need to do it in Java or C#, this is, you use it or you don't, it's your choice, what we need to ensure is that, if one decides to use this inside Book_, the this will work as supposed in an OO language, instead of introducing a bug.

After all of this, you may be asking, ok, we have private fields (variables), but what about private methods? How can we specify a public interface for our classes? Well, I will explain it with an example:

When we do :

var book = new Book();

The book variable holds and instance of Book, where you can call, all the members defined inside of Book's constructor using this.something = ...  .

To create private methods you use Nested Functions, which are functions declared inside of Book constructor:

/* class Book */
function Book()
{
   /**
    * Private Fields (private)
    */

   var _name,
       _description,
       _isbn,
       _authors,
       _rating;

   /**
    * Public Fields (public)
    */
   
   this.imageURL = 'http://google.com?q=images';
    
   /**
    * Constructor
    */   

   (function Book_(){
      _authors = [];
      _rating = 5;
   }).apply(this, arguments);

   
   /**
    * Private Methods (private)
    */

   function getAmazonBookImage(){
       //some ajax request ($.ajax or $.json)       
   }

   function getAmazonBookInfo(){
       //some ajax request ($.ajax or $.json)
   }


   /**
    * Privileged Methods - Methods with access to private scope.
    */

   /* get/set/property for field 'name' */
   this.getName = function(){ return _name; }
   this.setName = function(name){ _name = name; }
   
   /* get/set/property for field 'description' */
   this.getDescription = function(){ return _description; }
   this.setDescription = function(desc){ _description = desc; }
   
   /* get/set/property for field 'isbn' */
   this.getISBN = function(){ return _isbn; }
   this.setName = function(isbn){ _isbn = isbn; }

   /* get/set/property for field 'authors' */
   this.getAuthors = function(){ return _authors; }
   this.addAuthor = function(author){ _authors.push(author); }
};

/**
 * Public Methods of Book
 */
Book.prototype = {
    getRating: function(){
        return this.imageURL;
    }
};

//little example
var book = new Book();
alert(book.getRating());


Some thoughts of all of this I have talked about, that you should have in mind:
  • The public methods declared in prototype will be available in all instances of Book, and they occupy space in memory just one time, this is, all methods of Book declared via prototype will be created from it. While this is good in terms of memory, the only drawback is that, public methods will not have access to private scope (variables/methods).
  • To declare functions that have access to the private scope, you must declare them from within the constructor code using this keyword. This kind of methods are called privileged methods, because they are public and have access to the private scope. The drawbacks are that you must be careful using the this keyword inside of this methods, because they are declared using anonymous functions this.getName = function(){ //this, in here refers to this function! }, and the other drawback, probably the biggest is that, for each instance of Book you will be using extra memory for each one of the private and privileged methods you declared, remember that everything in JavaScript except for variables of the 3 primitive types is an object. This means that functions are also an object.
  • This as the potencial to use more memory than other approaches, so it should only be used when you require true private members. This approach is also hard to subclass when using inheritance (I will talk about this in another article). The new inherited class will not have access to any of the superclass private methods or attributes.
    We often listen that "Inheritance breaks Encapsulation", because the subclasses have access to the superclass protected methods and attributes, in javascript this is not true.

For the unexperienced and even for the experience javascript can be tricky to understand sometimes, but once you find a convention it becomes easier to program good and maintainable programs. 

Although for many corporations can be hard to ensure that all programmers handle JavaScript the same way, so I advise you to take a look at CoffeeScript. Whether to use it or not, my opinion is that it's depends on, what's the lifetime of your code? How many code is involved? ...

So this article talked about classes and encapsulation in JavaScript and how you can create private/public members in a Class, I hope you liked it.

Next time, I'll write about other approaches on how to handle JavaScript Encapsulation, Closures,
followed by Inheritance and Polymorphism, stay tuned.