Tuesday, June 16, 2015

TCP vs UDP

TCP:
Need to establish a connection before starting data transfer (Handshake)reliable, slow, heavy header:
Data order is guaranteedEx: HTTP, SMTP, FTP, Telnet, HTTPs,
uses: most of the finance domains uses TCP

UDP:
No handshaking required
fast, small header, unreliable
Ex: DHCP, DNS
uses: mostly used in Video streaming, online gamings

more:
http://javarevisited.blogspot.in/2014/07/9-difference-between-tcp-and-udp-protocol.html

Wednesday, May 20, 2015

Quick Squid proxy installation on Cent OS

       yum -y install squid
       chkconfig squid on

to start
       service squid start

to Stop
       service squid stop

to restart
       service squid restart

To allow only selected IPs, just add an entry in
       vim /etc/squid/squid.conf
just before
       acl SSL_ports port 443
#adding custom entries
       acl localnet src 146.531.2484.1234
and then restart

Thursday, May 7, 2015

Some useful Redis commands - quick view

SET foo bar
GET foo
-----------------
x = GET foo
x = x+1
SET foo 1 // chance of misleading

SET is not synchronized, so use INCR for safer side
INCR x
-----------------
LPUSH mylist a (now mylist holds 'a')
LPUSH mylist b (now mylist holds 'b','a')
RPUSH mylist c (now mylist holds 'b','a','c')
LPUSH mylist d
LPUSH mylist e
LPUSH mylist f (now mylist holds 'f','e','d','b','a','a)
LRANGE mylist 0 1 => b,a
LRANGE mylist 2 4 => d,b,a
LRANGE mylist 3 -1 => b,a,a // index -1 means till end
LLEN mylist => 6

-----------------
*** If you want to maintain order of insertion then use LIST other wise use SET
*** List can have duplicates
*** Set don't have duplicates and doesn't maintain insertion order
*** ZSet : Sorted Sets with score(priority)
-----------------
SADD is the add to set operation
SREM is the remove from set operation
SISMEMBER is the test if member operation
SINTER is the perform intersection operation
SCARD to get the cardinality (the number of elements)
SMEMBERS to return all the members of a Set
---
SADD myset a
SADD myset b
SADD myset foo
SADD myset bar
SCARD myset => 4
SMEMBERS myset => bar,a,foo,b //  Not the order in which we inserted
---
SADD mynewset b
SADD mynewset foo
SADD mynewset hello
SINTER myset mynewset => foo,b // intersection between myset mynewset
-----------------

-----------------
ZADD zset 10 a
ZADD zset 5 b
ZADD zset 12.55 c
ZRANGE zset 0 -1 => b,a,c

ZSCORE zset a => 10 // returns zscore
ZSCORE zset XKXK => NUNLL // return null if key not existed
-----------------
HMSET myuser name Salvatore surname Sanfilippo country Italy // Sets key values of a variable
HGET myuser surname => Sanfilippo // Retrieves key value
HEXISTS is key exist
HINCRBY increment an hash field

-----------------
more: http://redis.io/commands
http://redis.io/topics/twitter-clone

Memcached vs. Redis

Redis Quick installation on CentOS


Install below packages if missed
sudo yum install -y gcc
sudo yum install -y tcl

-------------------------------------------------------------------
Now Download and isntall
sudo mkdir cp /usr/share/blue/redis
cd /usr/share/blue/redis
sudo wget http://download.redis.io/redis-stable.tar.gz
sudo tar xvzf redis-stable.tar.gz
cd redis-stable
cd deps; sudo make hiredis lua jemalloc linenoise
cd ..
sudo make

-------------------------------------------------------------------
After successfull installation test it. This step takes around 2-3 minutes.
sudo make test
If every thing is perfect then you get below Message
\o/ All tests passed without errors!

-------------------------------------------------------------------
Now copy Redis server and command line interface in proper places
sudo make install
This above step does these given two operations
sudo cp src/redis-server /usr/local/bin/
sudo cp src/redis-cli /usr/local/bin/

-------------------------------------------------------------------
We are using the default configuration file, so for safe side, we can take a backup of original conf file
cp /usr/share/blue/redis/redis-stable/redis.conf /usr/share/blue/redis/redis-stable/redis.conf.bak

-------------------------------------------------------------------
***** PROPER installation for live system *****
sudo mkdir /etc/redis
sudo mkdir /var/redis
sudo cp /usr/share/blue/redis/redis-stable/utils/redis_init_script /etc/init.d/redis_6379
sudo cp /usr/share/blue/redis/redis-stable/redis.conf /etc/redis/6379.conf
sudo mkdir /var/redis/6379

-------------------------------------------------------------------
Update config file
sudo vim /etc/redis/6379.conf

Set daemonize to yes (by default it is set to no).
        To set server to start in the background, ope /etc/redis.conf and change "daemonize" key value "yes"

Set the pidfile to /var/run/redis_6379.pid (modify the port if needed).
Change the port accordingly. In our example it is not needed as the default port is already 6379.

Set the logfile to /var/log/redis_6379.log
Set the dir to /var/redis/6379 (very important step!)

-------------------------------------------------------------------
change the logfile permissions
sudo vim /var/log/redis_6379.log // create the file, if not existed
sudo chmod 777 /var/log/redis_6379.log
change permission so that server can "save" dump files as "dump.rdb"
sudo chmod 777 /var/redis/6379
adds the new Redis init script to all the default runlevels
         sudo update-rc.d redis_6379 defaults

-------------------------------------------------------------------
Now we can run our instance by below command
/etc/init.d/redis_6379 start
Redis listens on port number: 6379, check is started
ps aux | grep redis
now check the logs at
tail -f /var/log/redis_6379.log

-------------------------------------------------------------------
Now test the server by client
redis-cli ping
response will be: PONG
we can start client in interactive mode, by not passing any params
redis-cli

-------------------------------------------------------------------
Shutdown redis
      redis-cli shutdown
 OR you can do this by connecting client in interactive mode then give "shutdown" command

-------------------------------------------------------------------
Set the password
uncomment "requirepass" line and replace dummy password with real and long password
sudo vim /etc/redis/6379.conf

-------------------------------------------------------------------
Interactive Tutorial
    http://try.redis.io/
-------------------------------------------------------------------

more: http://redis.io/topics/quickstart
For securing your redis server, more info: http://redis.io/topics/security

Difference between REST Services and Restless SOAP Services Example

REST: Representational State Transfer
REST is an style of software architecture for distributed software.
RESTful is just used as an adjective describing something that respects the REST constraints.

RESTful web service has 4 basic characteristics which are:

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.


Wednesday, May 6, 2015

OAuth 2.0: Why we need it, What are the benefits and use cases

Both OAuth 1.0a & 2.0 support two-legged authentication, where a server is assured of a user's identity, and three-legged authentication, where a server is assured by a content provider of the user's identity. Three-legged authentication is where authorization requests and access tokens come into play, and it's important to note that OAuth 1 has those, too.

more: http://stackoverflow.com/questions/7561631/oauth-2-0-benefits-and-use-cases-why

Design Patters in Java core library

GoF's Design Pattern implementations found in both the Java SE and Java EE API's.
more: http://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries

Design patterns in one line: http://www.dofactory.com/net/design-patterns

Design patterns explained with Java classes
http://www.tutorialspoint.com/design_pattern/

How does load balancer actually work

The reason to use load balancer is because one node can't process all the requests. but how come the load balancer can process all the requests?

more: http://www.quora.com/How-does-load-balancer-actually-work

Servlets vs thread safety


each incoming request to a servlet is handed over to a thread to perform the task.

Read this for more info about how they are handled. http://www.javaworld.com/article/2072798/java-web-development/write-thread-safe-servlets.html

If your servlet implements SingleThreadModel interface, each thread use separate instance of servlet. SingleThreadModel is deprecated, Don't use it.

Why we need keep-alive header in HTTP response

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

More: http://stackoverflow.com/questions/20592698/keep-alive-header-clarification

Thursday, April 30, 2015

Java Collections Cheat Sheet

HashMap internal implementation in Java

HashSet internal implementation in Java

HashMap.put method will return
 
  oldValue: if key is already present, then it will overwrite the value and returns old value
  null: if key is not present, then it will add this key,value pair and then returns null.

In case of HashSet, internally it has a hashmap. When we call add method it will call 'put' method of the hashmap and if put method returns null means new entry is added into hashmap and hashset

more at: http://javahungry.blogspot.com/2013/08/how-sets-are-implemented-internally-in.html

Java example of impementing equals, hashCode, compareTo, toString methods

import java.util.*;

public class Name implements Comparable {
    private final String firstName, lastName;

    public Name(String firstName, String lastName) {
        if (firstName == null || lastName == null)
            throw new NullPointerException();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() { return firstName; }
    public String lastName()  { return lastName;  }

    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.firstName.equals(firstName) && n.lastName.equals(lastName);
    }

    public int hashCode() {
        return 31*firstName.hashCode() + lastName.hashCode();
    }

    public String toString() {
 return firstName + " " + lastName;
    }

    public int compareTo(Name n) {
        int lastCmp = lastName.compareTo(n.lastName);
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    }
}

Java purpose of AtomicInteger

We can use AtomicInteger to avoid count++ issue in mutli-threading environment.

AtomicInteger provides incrementAndGet() and decrementAndGet() methods which are thread safe.

With use of AtomicInteger, we can solve this problem without using synchronized keyword

more: https://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html

          http://javarevisited.blogspot.in/2012/01/how-to-write-thread-safe-code-in-java.html

Friday, April 24, 2015

Find the smallest positive integer value that cannot be represented as sum of any subset of a given array

Question Details:

Given a sorted array (sorted in non-decreasing order) of positive numbers, find the smallest positive integer value that cannot be represented as sum of elements of any subset of given set. 
Expected time complexity is O(n).


Examples:
Input:  arr[] = {1, 3, 6, 10, 11, 15};
Output: 2

Input:  arr[] = {1, 1, 1, 1};
Output: 5

Input:  arr[] = {1, 1, 3, 4};
Output: 10

Input:  arr[] = {1, 2, 5, 10, 20, 40};
Output: 4

Input:  arr[] = {1, 2, 3, 4, 5, 6};
Output: 22


more: http://www.geeksforgeeks.org/find-smallest-value-represented-sum-subset-given-array/

Solution Explanation:
http://stackoverflow.com/a/21078133/4507251

Websites to learn Algorithms, Data Structures and Java

For learning algorithms and data structures, please follow below links.





  Will update more.