Category Archives: General

Getting to know about java.nio.file.Path – 2

In Part 1 of this, we looked at most of the APIs in the java.nio.file.Path class. In this article, we will look at the remaining APIs.

Using register()

This API allows us to register an implementation of java.nio.file.WatchService interface which will listen for events like directory creation, modification, and deletion. And it intimates the listeners by means of a java.nio.file.WatchKey. I would like to dedicate a different article for this API because it involves another new feature which was introduced in Java 7.

Using resolve()

This method deals with two Path instances. One instance on this the resolve() method is called and the other instance which is passed as an argument. The argument can be either a Path instance or a String representing the path.

This method resolves the other path against this path. The resolution is done as follows:

  1. If the other path is an absolute path, then it returns the other path. Because the other path can be reached by using the absolute path.
  2. If the other path is a relative path then the other path is appended to this path. For example:
    Path path = Paths.get("src", "main", "resources");
    Path other = Paths.get("blogsamples");
    
    assertThat(path.resolve(other)).isEqualTo(
            Paths.get("src", "main", "resources", "blogsamples"));

The different scenarios in which this method can be invoked is given in the test below:

@Test
public void testResolved() throws IOException {
    Path path = Paths.get("src", "main", "resources");
    Path other = Paths.get("blogsamples");

    assertThat(path.resolve(other)).isEqualTo(
            Paths.get("src", "main", "resources", "blogsamples"));

    other = Paths.get("/Users");
    assertThat(path.resolve(other)).isEqualTo(Paths.get("/Users"));

    path = Paths.get("/src", "main", "resource");
    assertThat(path.resolve("/Users")).isEqualTo(Paths.get("/Users"));
}

Using resolveSibling()

This method is similar to resolve() except that it considers this path’s parent to resolve the other path. Again there are different possibilities which I have captured in the test below:

@Test
public void testResolveSibling(){
    Path path = Paths.get("src", "main", "resources", "test1");
    Path other = Paths.get("test2");

    //both paths are not absolute
    assertThat(path.resolveSibling(other)).isEqualTo(
            Paths.get("src", "main", "resources", "test2"));

    //other path is absolute
    assertThat(path.resolveSibling("/test2")).isEqualTo(
        Paths.get("/test2"));

    //this path has no parent
    path = Paths.get("/");
    assertThat(path.resolveSibling("/test2")).isEqualTo(
        Paths.get("/test2"));

    //the other path is empty and this path has no parent
    assertThat(path.resolveSibling("")).isEqualTo(Paths.get(""));

    //the other path is empty and this path has parent
    path = Paths.get("src", "main", "resources", "test1");
    assertThat(path.resolveSibling("")).isEqualTo(
            Paths.get("src", "main", "resources"));
}

Using relativize()

This method returns a relative path that when resolved against this path returns the other path (i.e the path which is passed as a parameter).

I have tried to illustrate in the tests below the different possibilities while trying to create a relative path between two paths.

Path path = Paths.get("src", "main", "resources", "test1");
Path other = Paths.get("test2");

assertThat(path.relativize(other).toString())
    .isEqualTo("..\\..\\..\\..\\test2");

In the above case, both the paths are relative. It requires 4 hops backward from the src/main/resources/test1 to reach /test2. The same is obtained by applying the relativize method.

If one of the paths is absolute and the other is relative, then invoking relativize results in an IllegalArgumentException as shown below:

@Test(expected = IllegalArgumentException.class)
public void testRelativize_WithRelativeAndAbsolutePath(){
    Path path = Paths.get("/src", "main", "resources", "test1");
    Path other = Paths.get("src", "main", "resources");
    path.relativize(other);
}

If both the paths are absolute, then the output of relativize() is implementation dependent. The below test is written against JDK 8 on Windows platform:

@Test
public void testRelativize_WithAbsolutePaths(){
    Path path = Paths.get("/src", "main", "resources", "test1");
    Path other = Paths.get("/src", "main", "resources", "test1", "test2");
    assertThat(path.relativize(other).toString())
        .isEqualTo("test2");
}

Using startsWith()

This method checks if the path on which the startsWith() method has the same name elements in the beginning as that of the path passed as the argument. And the path passed as the argument has no extra name elements that are not present in this path.

For example: /a/b/c starts with /a/b , a/b/c/d starts with a/b/c

Let us look at the different possible cases while invoking the method:

@Test
public void testStartsWith(){
    //both paths are absolute
    Path path = Paths.get("/src", "main", "resources", "test1");
    Path other = Paths.get("/src", "main", "resources");
    assertThat(path.startsWith(other)).isTrue();

    /*
    both paths are absolute, where as the other 
    path has more name elements 
    */
    path = Paths.get("/src", "main", "resources", "test1");
    other = Paths.get("/src", "main", "resources", 
        "test1", "test2");
    assertThat(path.startsWith(other)).isFalse();

    //both paths are same
    path = Paths.get("/src", "main", "resources", "test1");
    other = Paths.get("/src", "main", "resources", "test1");
    assertThat(path.startsWith(other)).isTrue();

    //either of them is relative
    path = Paths.get("src", "main", "resources", "test1");
    other = Paths.get("/src", "main", "resources", "test1");
    assertThat(path.startsWith(other)).isFalse();

    //both of them are relative
    path = Paths.get("src", "main", "resources", "test1");
    other = Paths.get("src", "main", "resources");
    assertThat(path.startsWith(other)).isTrue();

}
Advertisements

A stupid Mistake

stupidestmistake

the above mistake cost me close to 1 hour. Can you spot the mistake?

I tried all these possibilities:

model.put("validation_success",1);

model.put("validation_success",true);

model.put("validation_success","true");

and then realized my stupid mistake.

I have installed sonar plugin, it suggested me to “Extract this nested code block into a method”. I thought it was suggesting me to extract the nested if statements into a method.

Anyways I guess I needed a break, I left for the day after struggling to resolve it. And I figured out the mistake next day morning with a fresh pair of eyes.

 

Command to find files from windows command prompt

So if you want to find files with a given extension in windows, this is how you would do:

$> where /r . *.java
C:\Program Files\Java\jdk-9\my-samples\sample1\src\org.astro\module-info.java
C:\Program Files\Java\jdk-9\my-samples\sample1\src\org.astro\org\astro\World.java

where,

  • /r says recursively search and match for files with given pattern,
  • and the argument after /r says to start from current directory

If you want to get more information use where/? which is the way to reach the help for the command

Very useful Console Window for windows

ConEmu (http://www.fosshub.com/ConEmu.html) is a very useful and much much better Console window for Windows. It acts as a facade over the cmd.exe. There are loads of good things in it and highly recommended for programmers who are windows users.

If you have installed Cygwin, you can integrate bash with your ComEmu terminal so that you can open a new tab running your bash shell :). On similar lines you can open new tabs running Git shell if you have installed git-shell.

To integrate Cygwin bash –
1. Open the setting – Windows + Alt + P
2. Select Startup -> Tasks
3. Click on “+” to add a new task
4. Name it as “Cygwin bash” or “cygwin” which ever is comfortable.
5. In the commands text area paste this: “%SystemDrive%cygwin64binbash.exe” –login -i
6. Save and exit the settings.

Useful Audio Podcasts for Software developers

I have been listening to few technical podcasts for software developers and thought of sharing them for the benefit of the readers.

Software Engineering Radio: Very useful podcast for software developers. There are about 186 episodes as of writing this post. The frequency of new podcasts is pretty less, but there are lot of good podcasts in their archives. Topics range from Architecture to Development Practices to various frameworks, programming languages, databases to name a few. I would highly recommend this podcast.

The Java Posse: I dont think this needs any explanation. Its the most popular Java podcast around and I really enjoy the discussions which take place during the podcast. Really informative. Its vendor neutral podcast, so you get to know about all the good, bad and ugly parts of Java.

The Java Spotlight: Another useful Java podcast from the horses mouth. Usually the topics tend to me more Java and Oracle’s updates on Java. But overall a good listen as it usually short with good amount of information to tickle your curious brains.

This Week In Google: I have been listening to this podcast lately. They have video podcast as well as live broadcast, but I use their audio podcast. Often I get to know what’s happening in the Google technology space with some informative discussions.

In Beta:
I started listening to this since yesterday and this is a very new podcast. I think they have live broadcast like This Week In Google(TWIG) and one of the members, Gina Trapani of TWIG is also part of In Beta. I found the discussions very useful. Mostly it has been around open source, web applications, mobile applications.

Pragmatic Podcasts: This is no longer getting newer episodes, but I would like to mention it here because there are quite a few useful podcasts in their archive, definitely worth checking out.

The Basement Coders: I found the topics dealt in this podcast are interesting. I have few episodes on my Shuffle but yet to listen to them. Will update this post once I listen to them, but listing for benefit of my readers.

IBM DeveloperWorks Java Podcast: Andrew Glover covers some really good topics. I am not sure if its actively maintained, but the archive has really good podcasts. I couldn’t find the iTunes link for this Java Podcast, but managed to get IBM DeveloperWorks Podcasts iTunes link and frankly I havent been able to get those episodes yet.

For JavaScript fans- I found Javascript Show, from the people who brought you Javascript Weekly, interesting. I couldn’t follow them because I dont have much experience in Javascript.

I tried to choose general development related and Java related podcasts for my use. I am not IOS/Apple/.NET guy so I didnt choose any podcasts in that area. If you have any of your favorites not listed here, please share them as comments below and I would update them at the earliest. You can find lot of podcasts suggested on the Stackoverflow questions and I dont want to list them all here because I havent tried them so I cannot recommend any of them.

Are you running 10kms for the first time?

I always say this: “Running 10K is easier said than done”, this can be compared with “Test Driven Development(TDD) is easier said than done”. The reason I say this is that both Running and TDD can be mastered by dedication and rigourous practice. That said, let me share my experiences of running 10K for the first time( not really first time, but equivalent to a first time).

I participated in the Open 10K category of the 2012 TCS World 10K Bangalore and I managed to complete the race in 1hr 07mins with around 2300 participants finishing ahead of me. There were quite a few mistakes I did which I thought would share:
1. Not preparing enough for tackling the high intensity situtations. To be frank there wasn’t any right preparation for the run, I thought cardio for 25mins at stretch (cross training in my case) would be enough to build the stamina. But I was wrong. The preparation helped me to keep a consistant pace for the first 6-7kms i.e for the first 25mins of the run, but after that it was hell. So one has to perpare for those post 20-25 mins of the run.
2. Not choosing the right shoes. I knew there was an issue with my running shoes, but I didn’t want to change the shoe at the last minute and hence paid price of not being able to give my 150% towards the last 2kms.
3. Thinking about the distance to cover lets us down lot of times. I knew the route well and hence I knew how far I had to run. This kind of deterred me to some extent.
4. Not getting inspired by the other runners among whom were much older than me and also from a different gender.
5. Not running 10Kms before and leaving it on the race day to decide if I can run or not.

Few other things I though of sharing:
1. Prepare yourself mentally for the 10K run. Its not going to be easy, especially the last 2-3kms of the run.
2. Dont set very high hopes/ unachievable targets.
3. While you are training- include strength training as well. Also spend some time on the cross trainer preferraly with high intensity levels.
4. Give importance to the lower back strengthening and also over flexibilty of the body. Proper stretching of muscles during the training is important.
5. Dont try anything too hard while training so as to avoid injuries.
6. Include/Prefer outdoor running to indoor running on treadmills.

The training regime followed for this would not only help you to run 10Kms or more but also helps in strengthening of muscles, increased flexibility, increased stamina, better confidence and also helps you to stay away from work related health hazards.

Lot of people working in the Software industries are usually so much loaded with work- work at office, hobby based work, travelling, lots of thinking, bad eating habits and so on, we are most likely to be the victims of health hazards. As some wise men said: “Prevention is better than cure”,and its better late than never. Lot of companies encourage their employees by providing Gyms in the office, corporate sports teams and even participating in such running events at the corporate level.

Some of the books I found useful:

  • Foundation: Redefine Your Core, Conquer Back Pain, and Move with Confidence(Flipkart, Amazon)
  • The Men’s Health Big Book Of Exercises (Flipkart, Amazon)

Any of you have some interesting things to share about your fitness? or about your first running experiences? Do drop in your feedback as comments below.

Learning in a Result Oriented Software Development environment

This article is being written in context of Software development, but should be applicable to all areas where ever there is human involvement.

Looking at the current scenario, all of us are becoming more result oriented. And in the process giving less importance to the learning. Its not our fault, but its due to the importance given to the results. No one looks at the path taken to get to the result, instead the result is what is considered as the ultimate achievement.

For example, you are assigned the responsibility of developing a feature and it requires you to explore certain new API. There are 2 ways I think one can get to know how to use the API- One is to learn about the API and then use it, or the other is to search on the internet for examples where the API is used and copy paste it. The latter approach saves you time and helps you build the feature faster than the former approach of learning. And the stakeholder of the feature would be impressed looking at the end result, they dont care how much of the API you have learnt. Because it doesn’t matter to them directly.

Everything looks good until the client/stakeholder (it can be your manager/customer) comes back with a change in the feature. So what does the Ctrl-C+Ctrl-V person would do? Yes of course, search for the solution and then again do Ctrl-C+Ctrl-V. Now if the API usage is not obvious and there isn’t much help on the web regarding that, what can the Ctrl-C+Ctrl-V person do? Sit and learn the API and can he do that? With the pressure from the client and limited time, it becomes hard to learn.  What would the other person who learnt the API in the first place do? Just use the API as required to add the enhancement.

If you are not familiar with the code you have written, then for each of the enhancement or the bug fix you have to add, you need to read through the code again and again to find what is used where. And in the end the larger the codebase becomes, harder it becomes to fix a bug or add an enhancement. It shouldn’t happen that: “When you wrote the code only you and god would understand it and after sometime only god can understand it“. [Thanks to my teacher for this lovely quote]. What I want to convey here is that- time spent on learning is not a waste of time, instead it one step towards reducing the time spent in developing the software, one step towards improving the quality of code and the software developed.

I have been in this position quite a lot of times. And on all the occasions where I have Ctrl-C+Ctrl-V’d the solution, I have had to do the same when I encountered the problem again. But in places where I have learnt about the problem and the solution I have been in a better position to solve the problem next time.

The reason for writing this post is the popularity of sites like: http://www.java2s.com/http://www.roseindia.net/java/http://www.java-tips.org who just provide the solution to certain problems, for example: reading a file in Java or obtaining the hostname in Java and the like. There are lot more sites like this which are popular. Also on CodeRanch forums lot of people ask for direct solution to a certain problem. But the more experienced users, the moderators do not encourage anyone asking for answers. The main focus on forums like CodeRanch is the learning which is involved in the solving of a problem and not the solution itself.

Related to this is Software Craftmanship which is all about the developer and the skill of the developer. If you are not continuously learning then you are missing out of lot of things. I will write about it sometime in future as well.

What are your thoughts about the importance given to results than to learning?