Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, November 6, 2019

Algorithm: Breadth First Search (BFS)

Graph as you must be aware is used to represent network. Network could be of any type:

1. Your friends network
2. Your work Network
3. Communication Network
4. Commute Network

As every network has nodes (src and destination) and we may have a way to reach from one to another (edge of the network).

Breadth First Search as name suggest, will try to reach neighbors first then only it will move ahead, so basically searching across the breadth of a node and then going deep.

for below graph breadth first search will go in below order, if our root node is 3.

3   4   0   1   2   5

For the graph creation please visit:

And for complete code: Github link

package madwani.sushil.Graph;
import madwani.sushil.model.Graph;
import madwani.sushil.model.Node;
import madwani.sushil.service.GraphService;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class BFS {

    List<Node> nodes = new ArrayList<>();
    // to keep track of neighboring node
    Queue<Node> nodeQueue = new ArrayBlockingQueue<>(200);
    // to keep track of nodes which are visited
    HashMap<Node, Boolean> visited = new HashMap<>();
    public void bfs(Graph g){

        if(g.getAdjacencyMap() !=null) {

            // read all the nodes
            nodes = new ArrayList<>(g.getAdjacencyMap().keySet());

            // initialize all nodes as false for visited
            initializeVisited();

            //actual algo
            doBfs(g);
        }
    }

    public void doBfs(Graph g){

        // root node to start the bfs, push to queue
        nodeQueue.add(new Node(3,"three"));

        // poll the queue and run algo till queue is empty
        do {

            Node initialNode = nodeQueue.poll();
            // get all the adjacent nodes of the polled node
            LinkedList<Node> adjacentNodes = g.getAdjacencyMap().get(initialNode) == null ?
                    new LinkedList<>():g.getAdjacencyMap().get(initialNode);

            // if not visited, get all adjacent nodes
            // print it for visibility purpose
            // mark it visited
            if(!visited.containsKey(initialNode) || !visited.get(initialNode)) {
                for (Node node: adjacentNodes){
                    nodeQueue.add(node);
                }
                System.out.print(initialNode.getN() + "   ");
                visited.put(initialNode, true);
            }
        } while (!nodeQueue.isEmpty());
    }


    public void initializeVisited() {
        for(Node n: nodes) {
            visited.put(n, false);
        }
    }

    public static void main(String[] args) {
        GraphService service = new GraphService();
        List<Graph> graphs = service.getSampleGraphs();
        BFS bfs = new BFS();
        bfs.bfs(graphs.get(0));
    }
}

Tuesday, November 5, 2019

Java 8: Functional Interfaces

Any interface with a SAM(Single Abstract Method) is a functional interface, and its implementation may be treated as lambda expressions.

Read below for detailed explanation

Java is an Object Oriented Programming.

When we say that, what does it means ? it wants to imply that without object you can't do anything. You require an object or mother of object i.e. class to call a function, access any field etc.

sometimes this creates lots of noise. let's suppose you just wanted to add two numbers, means you require a function which accepts 2 numbers, which adds them and returns the result.

in Java to expose this functionality, you have to write a Utility class and then write a method which accepts arguments and sum it up.

public class mathUtil {

         public static T add( T a, T b) {
                return a+b;
         }
}

now, wherever you wanted to use it, you have to call like MathUtil.add(4,5);

is it worth writing whole class for using it ? can't we directly use function to add it without the class, as class is just adding noise.

till Java 7 it is not allowed however from Java 8 it is allowed via a hook named lambda expressions, where you can perform some function without formally creating any class of it.

so above code can be written like this and used wherever we can pass lambda expression.
                  (a,b) -> a +b;

Basically Java 8 provided support for lambda expression using interfaces called Functional interfaces.

What the hack is Functional interface now ?

The Functional interface is any interface which exactly has one abstract method.

i.e. our old friend Runnable, Comparator interfaces are Functional interface as they hold only one method. To make sure any interface is really functional we can annotate them with @FunctionalInterface, by which compiler will ensure that interface contains only one abstract method.


@FunctionalInterface
public interface myInterface{
      public void doThis(T a);
}

As you are aware any interface can contain default() and static() methods from java 8, so same applies to Functional Interface.

When we talk about function, a function can do any of the below:

1. Consume something and return nothing (Consumer).
2. Accept nothing and just return something (Supplier)
3. Accept something and judge it (Predicate)
4. Accept something and return something (Function)

As these are the common activities for any function, Java  8 java.util.function package provides functional interfaces for all of these as well various variants of these, full list here.

Most of the time your function will fall under one of the category you just have to use them, no need to write functional interfaces.

Here are the basic definitions of each:

public interface Function<T,R> {

    public <R> apply(T parameter);
}
public interface Predicate {
    boolean test(T t);
}
public interface Consumer<T>{
    void accept(T t)
} 
public interface Supplier<T>{
    T get()
} 

Few Examples:

package madwani.sushil;
import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Predicate;import java.util.function.Supplier;
public class FunctionalInterfaceExample {

    public static void main(String[] args) {

        Predicate isNotNull = (value) -> value!=null;
        System.out.println(isNotNull.test("hello"));

        Supplier<Double> randomGenerator = () -> Math.random();
        System.out.println(randomGenerator.get());

        Function<String, Integer> integerConv = Integer::parseInt;
        System.out.println(integerConv.apply("2"));

        Consumer<Integer> exitCode = (num) -> System.exit(num);
        exitCode.accept(20);    }
}





Monday, November 4, 2019

Spring Boot: @ConfigurationProperties vs. @Value

You must have used @Value in your spring project for reading the values from property file and you have seen people started using @ConfigurationProperties to do the same.

You are wondering what exactly is the difference ?

I will try to explain.

1. You must have seen cases where the expected value type is Integer, however we supplied String expecting it will take care of conversion and bang it failed during runtime. so basically what I wanted to convey @Value is not type safe.

2. For below example, how will you load property file in you application:

    spring:
          datasource:
                   url:
                   uname:
                   pwd:
          security:
                   uname:
                   pwd:
                   role:

you must be doing

@Value("{spring.datasource.uname}")
private String dbUsername;

@Value("{spring.security.uname}")
private String securityUname;

isn't it too verbose and confusing. What I wanted to say here is @Value is too verbose and can create confusion as you have to use fully qualified name to read the property.

3. Let's suppose you have used a particular file in 30 different places in the project and suddenly need arose to change the name :), hell lot of work and not guaranteed that all changed. imagine if the property is used in hundreds of places ? What I wanted to convey @Value doesn't give any centralized mechanism to control.
4. I am not sure everyone faced this issue or not, but I am very bad at giving names. Giving name like deviceIdNumber, bulkProcessorName etc. are good if anyone is reading but not soothing to eyes. if we write like, device-id-number or bulk_processor_name, its both soothing to eyes as well as readable. What I wanted to convey @Value is not relaxing enough to allow writing property names like it. 

That's all about shortcomings in @Value, which are supported by @ConfigurationProperties apart from many other advantages.

1. @ConfigurationProperties kind of centralized all property configuration in a single class with Type binding with Setter's where you can control type conversion instead of throwing exception and log the details:

for the above example we can have 2 location to read properties, one for Datasource and one for Security:

@ConfigurationProperties(prefix="spring.datasource")
public class DatasourceConfig {
            private String uname;
            private String pwd;
            private String url;

           //setters and getters
}

@ConfigurationProperties(prefix="spring.security")
public class SecurityConfig {
            private String uname;
            private String pwd;
            private String role

           //setters and getters
}

Wherever we wanted to use those just inject the required config bean and you are done, want to change name, change it at this one place and compiler will ensure it is getting changed at all places where it is used using getter.

2. We can validate config properties using @Validate annotation in conjunction with @ConfigurationProperties annotation. we can use JSR-303 annotation directly over the fields to do the validation.

@ConfigurationProperties(prefix="spring.datasource") @Validated public class DataSourceConfig { @NotNull private String uname; // ... getters and setters }


Feature@ConfigurationProperties@Value
Yes
No
Yes
No
SpEL evaluation
No
Yes


Saturday, December 1, 2018

Collabera – CWT – Philippines


The below are my personal views, any of the comments below should not be taken as general.

Different people will have different experiences. These are my personal experiences:


About CWT:

1.      Good Client.
2.      Good work –Majorly Java backend using Boot and front end using React.
3.      Nice work environment ( I like bit of pressure @ work ).
4.      2 weeks sprint and they follow agile process very very seriously.
5.      Have to logically and reasonably explain the carry overs if any.
6.      Keep tab of my each and every activity in terms of what & How I code? What, How, When & Why I commit ? What & Why I mailed ? What & Why I told anything specific ?
7.      Some times over reactive but appreciative as well.
8.      No work from home.
9.      Some teams are very helpful, some are very little. (again personal experience)
10. Around 14-16 Indians services are terminated for performance reasons, as par my knowledge, all are flown back to India as no other opportunities available. I am not in touch of any so don't know what are they doing? till now did they get the job or not, I am not sure...


About Collabera:
1.      Pay on time.
2.      Give answer to each and every query, but takes time to answer.
3.      HR and management are too slow.
4.      Took 1 month to open bank account.
5.      Still waiting for 9G (multi entry visa) after 5 months of coming. Even in case of emergency I have to ask atleast 3-5 people as by myself I cannot visit India, Collabera is having my passport for immigration purposes :( . even if I got my passport with 9G, client has to agree to give me leaves (which are unpaid) and I am agreeing to pay for arranging Business visa again (definitely Collabera is ensuring they will help, no one has tested them yet).
6. Management is responsive but pace of things is slow and most of the time I have to push to get answers and get things done.
7. Sometimes I feel delays are deliberate.

About Philippines:
1.      Scenic country.
2.      Whole country is like Goa of India. ( yes Daru is cheap )
3.      Gorgeous girls.
4.      Very friendly and respecting people.
5.      Many Indians, so will see Indians whichever part of country you go (I tried tourist destinations).
6.      Many Indian Tiffin centres, who will deliver at your work and home place like
       1.  Tajindar foods ( North Indian) :  100 piso par meal including delivery
       2.  Legend foods ( North ) : 150-170 piso par meal including delivery
       3.  Annapurna ( South Indian ) : 200 -250 piso par meal including delivery
       4.  RICH ( South Indian ) : not sure of price, but best I have heard ( never tried )
7.      I stay near WalterMart Makati, it has an Indo Pak restaurant @ 500m, which serves kind of unlimited Indian food @ 130-170 piso, which tastes average.
8.      Many other good Indian restaurants like Bombay house, Queens of Bollywood, Mantra etc.
9.      Many places to get Indian groceries (but @ double price).
10.   Major transportation are AC buses, which are comparatively cheaper.
11.   Very poor country, poverty rate is very high.
12.   Too much pollution and dirtiness, but little better in Makati.
13.   Internet is very costly - upload speed is too - too slow.

Tech Community:
1.      People @ CWT are knowledgeable.
2.      Compare to India, very few good tech companies.
3.      Pay in other companies is not that good, I heard for 8-10 years java experience they pay 40-80K/month. 
4.      CWT is highest paying company, what I have heard in Philippines tech java world (again what I have heard).
5.      I even can’t think to change company as they are paying highest (again it is relative), however pay and opportunities in India are far better than Philippines.
6.      Sometime feel outcast, but it would be same in all countries.