we saw how to install node and npm on widows and also saw running a demo program. In windows it is as simple as downloading the installer and running it. In this post we will see how to install the same in Linux using command line.
Installing Node and NPM on your Linux machine
I am using Ubuntu so I am going to use apt-get to install software’s. You can do the same using yum if you are using fedora or alike.
First install some of the dependencies that are requied with following command-
sudo apt-get install python-software-properties python g++ make
Next you will need to add repository to install node and npm from -
sudo add-apt-repository ppa:chris-lea/node.js
Next get an update
sudo apt-get update
Now finally install nodejs
sudo apt-get install nodejs
This should install both node and npm for you. You can print their version to confirm they are installed -
NOTE : If you see nodejs module installed instead of node then resolve as follows (May differ across various Ubuntu versions)-
You need to manually create a symlink /usr/bin/node. Shortcut for bash compatible shells:
sudo ln -s `which nodejs` /usr/bin/node
Or if you use non-standard shells, just hardcode the path you find with which nodejs:
sudo ln -s /usr/bin/nodejs /usr/bin/node
Now lets quickly test it. Create a file called server.js and following contents in it -
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Now save it as run it -
You should see following in command promt -
aniket@aniket-Compaq-610:~/programs$ node server.js Server running at http://127.0.0.1:1337
Now go to browser and hit following url -
http://127.0.0.1:1337
You should see - Hello World
That means our server is up and running
Updating Node.Js version
You can use a module called n to upgrade you node package in Mac/Ubuntu
sudo npm install -g n
sudo n stable
This will install latest stable node package. You can run
node --version
If you are still seeing old version it might be directory issues where new package is installed. I had to create a symlink to make it work-
and create your free account. Note you will have to provide your credit card details and as a part of the verification process, they will cut 2/- rs from your account. But don't worry it will get refunded to your account within 3-4 business days. I am going to skip this part where you create your account - it is very straightforward after you visit above URL. In this post, we will see how to get the EC2 instance which is the basic free tier up and running.
EC2 stands for Elastic compute cloud and it is essentially virtual machines in the cloud.
Launching EC2 instance
Once you log in your dashboard should look as below -
Click on the EC2 (Virtual server in the cloud). You should see EC2 dashboard
Click on "Launch Instance" to start the launch configuration. Note the "instances" link on the left. We will visit it once our EC2 instance is up and running.
Next, you will have to choose which OS to boot up. I am selecting Ubuntu server 14.04 LTS which is a part of the free tier. You can choose the OS you want.
Next, you will have to select the instance type. Select t2.micro with 1 CPU and 1GB mem.
NOTE: t2.micro is eligible for free tier. You can try others as well but they will incur you some cost. So if you are experimenting with free tire stick to t2.micro. They can be of following families -
Family Speciality Use case
D2 Desne storage File servers/Data warehousing/Hadoop
R4 Memory optimized Memory intensive apps/DBS
M4 General purpose Application servers
C4 Compute optimized CPU intensive apps/DBs
G2 Graphics intensive Video encoding/3d Application streaming
I2 High speed storage No sql dbs/data warehousing
F1 Field programmable gate array Hardware acceleration for your code
T2 Lowest cost general purpose web servers/small dbs
P2 Graphics/General purpose GPU Machine learning
X1 Memory optimized SAP hana/ apache spark
Now click on Configure Instance Details.
Keep number if instances to 1 as we just need 1 instance. There are multiple EC2 payment options available -
On demand - Fixed rate by hour (by the second only for Linux)
Reserved - Same as On demand but for 1 year or 3 year terms so that you get some discount
Standard RIs (Up to 75% off on demand)
Convertible RIs (Up to 54% off on demand)
Scheduled RIs
spot - Enables you to bid whatever price you want if your start and end times are flexible. If the cost goes below your bid price your EC2 instances are provisioned and when it goes above they are canceled.
If you terminate the instance you pay for the hour
If AWS terminates the SPOT instance you get the hour it was terminated for free
Dedicated host - Physical EC2 server dedicated for use. Can reduce cost by allowing to use our existing server bound software license like Oracle or VMware.
Purchase option shows an option to go for spot option. This may not be available in your region so check that out. You can also go to tenancy and choose between shared and dedicated host.
We saw on demand, Spot and dedicated host. For reserved instances, you can see under instances section in your EC2 dashboard.
If you see network a default VPC (virtual private cloud is selected for you. You can create one if you need). Don't worry if you don't understand these terminologies. We don't require these to run our EC2. Just keep defaults. Also, you can see a subnet assigned to you. This is basically an IP range. Subnet is per availability zone -
Also, select the option to auto-assign IP (It should be checked by default). To select static IP refer -
Keep the defaults you see and proceed to storage settings.
Here you can select the type of EBS volume. General types of EBS volumes are -
General purpose SSD (GP2)
Up to 10000 IOPS (I/O per second)
Provisioned IOPS SSD (IO1)
Designed for IO intensive applications like large relational DB or No Sql db.
10000 IOPS ~ 20000 IOPS
Throughput optimized HDD (ST1)
Use cases Eg. Big data, Data warehousing
Cannot be a boot volume
Frequently accessed workloads
Cold HDD (SC1)
Lowest cost storage for infrequently accessed workloads
Cannot be a boot volume
Use case Eg. File server
Magnetic (standard)
Lowest cost per GB
Bootable
As you can probably see from above types only types that are available for booting and hence qualified for root EBS volume are -
GP2
IO1
Magnetic
You can also add new volumes (Other that Root which is bootable volume). Here you can see all types of EBS instances.
NOTE: Your EBS volume will get deleted by default on termination your EC2 instance. This is a setting under Add storage section while configuring your EC2 instance.
Next, go to Tag Instance. This is where you name your EC2 instance.
I have named it athakur-webserver. You can name it whatever you want. You will see this in instances tab later.
Next, go to configure security groups. Here you can configure which IPs can access the EC2 instance. The default group is 0.0.0.0 which mean all IPs can access it. I am going to keep it as such. Also, not this settings are per Protocol/Port. By default port 22 is allowed which is your SSH.
If you want to host your site and be able to access it you can open HTTP or HTTPS types as well.
Next click on "Review And Launch". You will get a screen with details of all configurations you have done so far. Review it and select Launch.
Before your instance is actually launched you will need to create a pair of the public and the private key that will enable you to connect to your EC2 instance. Basically, you will have the private key (used on the machine you use to connect remotely to your EC2 server) and EC2 server has the public key. You can download your private key (it will be a .pem file) and save it on your local machine.
So create your key and "Download Key Pair" and finally launch your instance.
It may take some time for your EC2 instance. Once it is up you are good to go. You can go to dashboard and select the instances link I referred to in 2nd screenshot.
You should see your instance details here. You can also note the public DNS that is basically your hostname.
Connecting to your EC2 instance
Now you can SSH to your EC2 instance from your local machine. To know the steps right click on your running instance and select connect. You should see steps to connect via ssh.
to connect to your EC2 instance via putty. You will have to convert your pem file to ppk file and give it as input to putty for connecting. PuTTY has a tool named PuTTYgen, which can convert keys to the required PuTTY format (.ppk). You must convert your private key into this format (.ppk) before attempting to connect to your instance using PuTTY.
Once you are done you should be able to connect -
For windows use putty and in auth section give this new private key create -
NOTE: Your public DNS or your hostname will change every time you reboot your instance. To get a permanent IP address, click Elastic IPs in the AWS Management Console (left navigation bar), allocate a new IP address and associate it with your instance.
Based on our knowledge till Java 7 we know that methods in an interface are by default public and abstract and that you cannot have a non abstract method in interface. However this does not hold true from Java 8 with the introduction of default methods. You can declare a method default and provide it's body in the interface itself and you need not implement it in the classes that implement corresponding interface (You can definitely override it though).
Need for default methods
Lets say you have following interface -
public interface Movable {
String walk();
}
and following class that implements it -
public class Human implements Movable {
@Override
public String walk() {
return "Human is walking";
}
}
Now lets say your needs change and you need to incorporate running as well. You would probably add a run() method in your Movable interface.
public interface Movable {
String walk();
String run();
}
But this will break your Human class as you will have to implement run() method in Human class (or any other class that implements Movable interface). You will get following compilation error -
The type Human must implement the inherited abstract method Movable.run()
To avoid such a situation we can use default methods.
Default Methods in Java 8
To add a default method in interface you need to use default keyword in your method declaration -
public interface Movable {
String walk();
default String run() {
return "Moavable Object is running";
}
}
and run your class as follows -
public class Human implements Movable {
@Override
public String walk() {
return "Human is walking";
}
public static void main(String args[]){
Movable movable = new Human();
System.out.println(movable.walk());
System.out.println(movable.run());
}
}
You will get -
Human is walking Moavable Object is running
You can ofcourse override your default method as it suits you but notice that this does not break your existing code.
public class Human implements Movable {
@Override
public String walk() {
return "Human is walking";
}
@Override
public String run() {
return "Human is running";
}
public static void main(String args[]){
Movable movable = new Human();
System.out.println(movable.walk());
System.out.println(movable.run());
}
}
And you should get -
Human is walking Human is running
Multiple interface conflicts
Conflict will arise if you have default method with same signature in two interfaces and a class implements them both -
public interface A {
default String testMethod(){
return "Called from A";
}
}
public interface B {
default String testMethod(){
return "Called from B";
}
}
public class Test implements A,B {
public static void main(String args[]) {
Test test = new Test();
System.out.println(test.testMethod());
}
}
Above code will not compile with following compilation error -
Duplicate default methods named testMethod with the parameters () and () are inherited from the types B and A
Alternatives here would be to override method in the class -
public class Test implements A,B {
@Override
public String testMethod(){
return "Called from Test";
}
public static void main(String args[]) {
Test test = new Test();
System.out.println(test.testMethod());
}
}
This should print - Called from Test
OR if you want implementation of any specific interface you can do -
public class Test implements A,B {
@Override
public String testMethod(){
return A.super.testMethod();
}
public static void main(String args[]) {
Test test = new Test();
System.out.println(test.testMethod());
}
}
In this case you will get - Called from A
NOTE : If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. (JLS)
Though you can specify methods from Object in an interface you cannot override them. For eg. -
In last post we say what is Lambda expression and how we can use it. In this post we will see some advance topics related to Lambda expression like -
Generic Functional Interfaces
Passing Lambda expressions as method arguments
Exception handling in Lambda expressions
Generic Functional Interfaces
lambda expression themselves cannot have generics but the functional interface that corresponds to a lambda expression can have generics.
Consider following demo code-
public class HelloWorld {
public static void main(String args[]) {
MyInterface<String> myStringInterface = (input) -> "Hello " + input;
MyInterface<Integer> myIntInterface = (input) -> 10 + input;
System.out.println("String based lambda exp : " + myStringInterface.myFunc("OSFG"));
System.out.println("Integer based labmda exp : " + myIntInterface.myFunc(14));
}
}
interface MyInterface<T> {
T myFunc(T t);
}
And the output is - String based lambda exp : Hello OSFG Integer based labmda exp : 24
Notice how same method is made generic to operate on both String and Integer inputs.
Passing Lambda expressions as method arguments
Lambda expressions can be sent as method arguments. This makes Java more powerful as you can now send executable code as a part of method argument. Consider following demo code -
A lambda expression can throw an exception just like any other method. However if that exception is a checked exception then it should be compatible with the exceptions listed in the throws clause of the abstract method in the corresponding functional interface.
Consider following demo code -
public class HelloWorld {
public static void main(String args[]) throws MyException {
MyInterface myInterface = (input) -> {
if(input == null) {
throw new MyException();
}
return "Hello World";
};
}
}
interface MyInterface {
String myFunc(String t) throws MyException;
}
class MyException extends Exception {
public MyException() {
super("MyException");
}
}
NOTE : Here if you abstract method does not throw the checked exception code will fail to compile.
That's it. Let me know if you have any questions on Lambda expressions.
In last post we saw how to use Lambda expressions (well at an introductory level). It is equally important to run it in an IDE like Eclipse to start with. Hence in this post we will see how to compile and run Java 8 compatible code in your Eclipse. Eclipse has a JRE which it uses to compile and run the code and there is compiler compliance level which basically recognizes your syntax. For example something like below -
List<String> myList = new ArrayList<>();
won't work with compliance level 6 as the diamond structure was introduced in Java 7. So compliance level 7 is required. We will come to all of this in a moment. This is just a background to get you started. My Eclipse version is Kepler (After upgrading from Juno)-
NOTE : Eclipse Kepler SR2 & Eclipse Luna are the versions that will support Java 8. Older versions will not (And by not I mean you will see compiler warnings, you can still compile and run if you have Java8 JRE). So of you are using older versions please consider upgrading.