Showing posts with label Techniques. Show all posts
Showing posts with label Techniques. Show all posts

2015-10-29

Install Node.js on EC2 Linux AMI



Recently I wanted to install  node.js on ec2 linux machine and to my surprise this task turned to be a little more tedious than I thought it would be. The reason for that is mainly because there are many ways to do it each of them with their pros and cons. The only alternative that I found easier to follow was to run the command: "sudo yum install nodejs npm --enablerepo=epel" . Unfortunately the epel repository has a very old version of node so I had to stick with a better option.

In this topic I am going to cover the option to download the binaries and just add the node directory to path.

The steps:

1. Go to https://nodejs.org/dist/ and select the version of node.js that you want. Normally you will need the latest. When I did the installation i used https://nodejs.org/dist/v4.2.1/node-v4.2.1-linux-x64.tar.gz .

2. After selecting the url that you want go to your machine and create a folder to have your node installation (be sure that the owner of the folder is ec2-user, if not change it with chown). In my case I created /opt/ . Then download your package with the command: wget https://nodejs.org/dist/v4.2.1/node-v4.2.1-linux-x64.tar.gz

3. Uncompress the file with command: tar -xvzf node-v4.2.1-linux-x64.tar.gz  and then navigate to created folder. In my case it was node-v4.2.1-linux-x64

4. The last step now is to add the node bin directory to path. To do so just create a new file in /etc/profile.d/node.sh . Edit the file and add the line: pathmunge /opt/node-v4.2.1-linux-x64/bin/ . Save the file and then run: source /etc/profile to refresh profile and you are ready.


This should normally be enough to have your node installation up and running.

2015-09-20

How to survive from Node.js and JavaScript callbacks




Many people coming from Java ecosystem to Node.js (like I did) are facing problems to adjust with the new platform philosophy since the basic principles of JavaScript itself are way different from the other well-known Object Oriented Languages.

Personally I think the biggest problem that I had was to understand the nature of functions in JavaScript and subsequently the way callbacks behave.

The truth is the first time I read about them I thought that I understood them. Unfortunately understanding them was not enough because all those years of experience turned into a barrier for me.

I will try to present the conceptual problem that I had in the beginning and also what I did in order to overcome it.


THE PROBLEM


Let’s say that you want to make a simple program that does 3 steps.

Step1. It reads a file.

Step 2. It accepts a prompt from console with username and password.

Step 3. It sends an email connecting to the mail server using the given credentials and having as a body the file contents read from step 1.


Normally with a conventional OO language you would create 3 functions each one doing one step and call them all three from the body of a third with the order 1, 2, 3.

Most programming languages are doing things synchronously by default which means that step 2 will be executed after 1 and 3 after 2.

This is a sample of something we could do in Java. For the sake of the example please ignore the static and the lack of OO architecture.

public static void main(String[] args) {
        readfile();
        getCredentials();
        sendMail();
}

    public static void readfile(){}

    public static void getCredentials(){}

    public static void sendMail(){}


Unfortunately (and fortunately) the following work flow would not work in Node.js. When your code reaches the step 2 the result of step 1 will not be ready and on step 3 the result of step 2 will not be ready either. The reason is that most modules of node.js work asynchronously and that requires a more delicate approach.


THE SOLUTION


As a matter of fact there are 3 solutions.

A) Using callbacks properly

B) Using nested callbacks

C) Using Promises.

I will skip solution B and C because B is not a decent solution since the readability of the code would be terrible and C because it is a different topic.

I will try to focus on solution (A).


As we saw on the previous code we had 3 functions doing the work and one more calling those 3 with a sequence.

In Node.js you will only need the fourth function to trigger the Step 1 and passing as a parameter the function that knows what to do after Step 1 ends.

Note that the fourth function - let’s call it trigger function – will not do anything more than calling step 1. The callback function 1 will be responsible to acquire the result of step 1 and trigger step 2 passing a new callback to step 2. Call back function 2 will be called by step 2 after finishing and that will call step 3.


Here is a diagram showing the procedure:



Here is some ample code:


function trigger(){
    readfile(callBack1);
}

function callBack1(){
    getCredentials(callBack2);
}

function callBack2(){
    sendMail();
}

// Step 1

function readfile(nextStep) {
    fs.readfile(path, function (error, text) {
        nextStep();
    });
}

// Step 2

function getCredentials(nextStep) {
    prompt.getCredentials(value, function (error, result) {
        nextStep();
    });
}

// Step 3

function sendMail() {
    transporter.sendMail(mailOptions, function (error, info) {
        //done
    });
}

2015-04-05

JavaEE7 Websocket Example


In this tutorial I will try to present a very easy way to create a minimal Websocket Application using Java EE7.

The specific web application will have a working  Websocket Server deployable on every Java EE7 container plus a basic HTML5 page that will act as a client just to test your work.

Let's get started then. The first thing that you will have to do is to create a web application. I used Netbeans IDE but you can do exactly the same thing using your IDE of preference or even just using maven and a text editor.

For those that use Netbeans go to -> New Project -> Maven -> Web Application. Give a name to your application and Select Java EE 7 Web.

The whole Websocket server will consist of 4 classes, the Message Class, the Encoder Class, the Decoder Class and the ServerEndpoint Class.

Here is the sample code for all 4 classes plus the HTML client:



2015-03-08

Enable CORS on JavaEE Web Application



Let's say that you have created a REST API in your Java EE WEB Application and you want to use it in HTML pages through AngularJS, jQuery or even plain JS. If you were newb (like I was), you would expect that this is going to work out of the box (as is) since your API has already been used in many cross platform clients without any problem.

Unfortunately though, for Murphy's sake, this is not the case. Due to Same-origin policy  http requests that are made in browsers must be done with a very specific way in order to work when the caller (web site) is on different domain than the web service (REST API).

In order to make it work, the caller must perform CORS  HTTP request to the WEB service and the web service subsequently must be modified in order to support CORS requests.

When I first came across to that problem I thought that this would be a-half-an-hour-problem but it wasn't. I had to spend a full day on this (thankfully on weekend) until the problem was completely "solved and working" on every modern browser.

For your web services, to support CORS requests you must deal with 2 problems.

1) CORS HEADERS

The first problem is about adding some additional HTTP headers (CORS) in your HTTP responses. This is relatively easy to find since googling about CORS almost everyone will tell about this. The new CORS headers will "tell" the caller if you support CORS requests and some other things like from which origin or which headers you accept as valid.
For example the header with value "Access-Control-Allow-Origin" expects the valid caller domain names. If the caller site is on domain mydomain.com, then the value of that header should be "http://mydomain.com". Alternatively in order to indicate that callers from any domain can access your resource you may just use the value "*".

If your application requires authentication (which was my case), the header "Access-Control-Allow-Headers" should also include the value "Authorization".

2)  Preflighted requests

The second one is about Preflighted requests. This was very tricky and hard to find since I only saw that happen on Firefox and Chrome - which in my opinion are the most important browsers out there. These two browsers first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send.  Cross-site requests are preflighted like this since they may have implications to user data.  In particular, a request is preflighted if:

- It uses methods other than GET, HEAD or POST.  Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
- It sets custom headers in the request.


SOLUTION

In order to overcome both of the problems you must change your web.xml file and also create a custom class that implements javax.servlet.Filter interface.

This is what I had to do in order to overcome Problem 1:





As you can see I created a Filter Class that accepts from web.xml one parameter which is the permitted origin and I used * as a value. The specific filter will intercept all of your application responses and add the custom CORS headers.

To overcome Problem 2 you will also need to modify your web.xml and in your security-constraint tag under web-resource-collection add all the HTTP method except OPTIONS. This will remove your current security from OPTIONS requests and actually make preflight requests feasible.
Here is a sample of what I did in our API:





As you can seeI have exluded OPTIONS request from authentication filter. If you don't do that your requests will always get a 401 error although the security on client is set correctly.

Here is the JavaScript code that I used to call one om Web services:


2014-12-28

S.O.L.I.D. Software Development



Most professional software developers understand the academic definitions of coupling, cohesion, and encapsulation. However, many developers do not understand how to achieve the benefits of low coupling, high cohesion and strong encapsulation, as outlined in this article. Fortunately, others have created stepping stones that lead to these goals,

resulting in software that is easier to read, easier to understand and easier to change. In this article series, I will define three of the primary object-oriented principles and show how to reach them through the five S.O.L.I.D. design principles.

Have you ever played Jenga? It’s that game of wooden blocks that are stacked on top of each other in rows of three. In Jenga you try to push or pull a block out of the stack and place it on top of the stack without knocking the stack over. The player that causes the stack to fall loses.

Read more ...

Using Generics To Build Fluent API's In Java











This article explains in detail the steps to create fluent API in Java using Generics.

Read it!

Code Generation using Annotation Processors in the Java language












I have found a very nice post explaining in detail how handle code generation through annotation processing.

Have a look here:

Part 1

Part 2

Part 3


Related useful articles

https://netbeans.org/kb/docs/java/annotations-custom.html

Popular Posts