Sunday, August 19, 2012

Google Drive - Language Change issue.

This post is not something which is related to Programming. It's the issue I had with the newly launched Google Drive. I have my windows 7 in French but with some tweaks now its in English. The issue I had with Google Drive was that no matter how many times I installed/re-installed the application on windows, it always was with French as language. There is no option in the settings of Google Drive to change it. And I prefer to have it in English. So here is the trick to solve this issue.

Close Google Drive from the system tray and do following:

Solution 1 (Need to be done every time you restart windows and that's annoying):
Step 1: Go to command prompt. (Run -> cmd).
Step 2: run the following command: 
C:\>set LANG="en_US" C:\Program Files\Google\Drive\googledrive.exe 
Solution 2 (Easy and not Annoying):
Set a new environment variable with variable name "LANG" and value "en_US" (In case if you don't know how to set enviornment variable in Windows check my old post on Windows Environment Variable).

Once all this is done start Google drive again and Voila.. problem solved.

Hope this helped you. 

Thursday, August 9, 2012

Writing in a File using Java

In my previous posts I talked about how to Create and Delete files using Java. Now, once you have created a file the next step is to write some content in those files and that can be achieved by using:
  1. BufferedWriter, or
    FileWriter writer = new FileWriter(fileToWriteIn);
    BufferedWriter bufferedWriter = new BufferedWriter(writer);
    bufferedWriter.write(toWrite);
    bufferedWriter.close();
  2. FileOutputStream.
    FileOutputStream stream = new FileOutputStream(fileToWriteIn);
    stream.write(toWrite.getBytes());
    stream.flush();
    stream.close();
There are classes like FileWriter available to perform write operation on a file but since writer sends its output immediately to the underlying character or byte stream. So that is why until prompt output is required, it is recommended to wrap a BufferedWriter around it.

Here is an example with full code and main method:

package home.flicker.java.io.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class WriteInFile {
    File file = null;
    /**
     * Method to create a file with the given name.
     */
    public boolean createFile(String fileName) {
        boolean result = false;
        file = new File(fileName);
        // creating the new File. The Method createNewFile() returns TRUE if file is successfully created else it returns FALSE.
        try {
            result = file.createNewFile();
        } catch (IOException e) {
            System.err.println("Error while creating file!!! " + e.getMessage());
        }
        return result;
    }
    /**
     * Method to read content from user and write it in given file using BufferedReader.
     */
    public boolean writeInFileWithBufferedWriter(File fileToWriteIn){
        boolean result = false;
        String toWrite = readFromUser("Data to write");
        try {
            FileWriter writer = new FileWriter(fileToWriteIn);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(toWrite);
            bufferedWriter.close();
            result = true;
        } catch (IOException e) {
            System.err.println("Error while writing in file!!! " + e.getMessage());
        }
        return result;
    }

    /**
     * Method to read content from user and write it in given file using FileOutputStream.
     */
    public boolean writeInFileWithFileOutputStream(File fileToWriteIn) {
        boolean result = false;
        String toWrite = readFromUser("Data to write");
        try {
            FileOutputStream stream = new FileOutputStream(fileToWriteIn);
            stream.write(toWrite.getBytes());
            stream.flush();
            stream.close();
            result = true;
        } catch (FileNotFoundException e) {
            System.err.println("Error: File not found!!! How the hell I am supossed to write   :P " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Error while writing in file!!! It's stupid   x( " + e.getMessage());
        }
        return result;
    }

    /**
     * Reads input from user as string and puts the label as question.
     */
    public static String readFromUser(String label) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(label + ": ");
        String input = scanner.next();
        return input;
    }

    /**
     * Main method.
     */
    public static void main(String args[]) throws IOException{
        WriteInFile example = new WriteInFile();
        String fileName = readFromUser("Enter File name");
        example.createFile(fileName);
        example.writeInFileWithBufferedWriter(example.file);  
        example.writeInFileWithFileOutputStream(example.file);
    }
}


The thing with these methods is that they over-write the content which is already in the file. To avoid that you need to append data. Will cover that some other time. 
I hope this post helps you. Share your experience or issues...

Saturday, August 4, 2012

JUnit: Basic Annotations


What is JUnit?

JUnit 4.x is a test framework which uses annotations to identify methods that are test methods. JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not depend on other tests.
To write a test with JUnit
  • Annotate a method with @org.junit.Test
  • Use a method provided by JUnit to check the expected result of the code execution versus the actual result
You can use Eclipse or the org.junit.runner.JUnitCore class to run the test.

Various Annotations of JUnit:


  1. @Test: This annotations tells which method is a test method. 

    @Test
    public void methondName(){
    ...........
    }


    You can some parameters with this annotations.
    • @Test (expected = Exception.class) Fails, if the method does not throw the named exception. 
    • @Test(timeout=1000) Fails, if the method takes longer than 100 milliseconds.

  2. @Before: The method which this annotation will execute before each test method. For example in cases where you need to initialize new class or read input data.

    @Before
    public void methodName(){
    ........
    }
  3. @After: This annotation signifies the method which executes after each test. For example where you need to roll back changes done by tests. 

    @After
    public void methodName(){
    ........
    }
  4. @BeforeClass: Method with this annotations executes only once before the start of all tests. This can be used in case where you need a database connection for the tests and you create it only once in the beginning. 

    @BeforeClass
    public void methodName(){
    ........
  5. @AfterClass: This annotation signifies the method which executes only once and that too at the end of all tests for example to close the data connection. 

    @AfterClass
    public void methodName(){
    ........
    }
  6. @Ignore: Will ignore the test method. You can use it in cases where your code has changed and the test is not yet adapted to accommodate those changes. 

    @Ignore
    public void methodName(){
    ........
    }
     

Sunday, July 29, 2012

Delete File using Java

In continuation to my last post, Creating a File in Java, I am writing this post to show how to delete a file. It's very simple, you just use the delete() method of the File class and done. The method returns a boolean, true if the file is successfully deleted otherwise false. Here is an example:


package home.flicker.java.io.file;

import java.io.File;

/**
 * @author fLiCkEr
 * Example to show how to delete a file.
 */
public class FileDeletion {

  public static void main(String[] args) {
    try {
      File fileToDelete = new File("test.txt");
               if (fileToDelete.delete()) {
System.out.println("File deleted!!!");
      } 
      else {
System.out.println("Can't delete file!!!");
      }
    } catch (Exception e) {
       System.out.println("Error deleting file: " + e.getMessage());
    }
  }
}


Creating a file in Java

Until now, the posts I wrote were on setting up development environment but for the first time I am gonna write something about coding. It's a simple tutorial on how to create files in Java. It's nothing fancy but just a point for me to start and take you into a bit of programming. So let's get started. 

There are many times when you need a file during development may be to write some data (could be a txt or csv or your own format). It's very simple to create a file. You simply need to use the File class from the Java IO. It has many methods and one of them is File.createNewFile().

The steps are: 
  1. Create a File object: 

    File fileToCreate = new File("nameOfFile");
  2. The second step is to create the file:

    fileToCreate.creatNewFile() 
And that's all. Here is example code:


package home.flicker.java.io.file;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author flicker
 * Example to create a file with user given name.
 */
public class FileCreation {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter name of File you want to create: ");
    String fileName = scanner.next();
    File fileToCreate = new File(fileName);
    try {
if(fileToCreate.createNewFile()){
       System.out.println("File created!!!");
      }
else{
       System.out.println("Can't create new file as it already exists!!!");
}
    } catch (IOException e) {
System.out.println("Error while creating file!!! " + e.getMessage());
    }
  }
}


Here is a screen-shot of the output:


The example code is pretty simple and self explanatory. Share your issues or confusions. 
I will be posting more on File reading, writing and other file related operations. 


Wednesday, July 18, 2012

Say Hello to Python Flask Server

What is Flask Server?


From the official Flask website, Flask is a micro web development framework for Python based on Werkzeug (a WSGI utility library for Python),  Jinja 2 (a modern and designer friendly templating language for Python) and good intentions. It's released under BSD license
Some of the features of flask are: 
  • Built-in development server and debugger.
  • Integrated support for unittesting support. 
  • RESTful request dispatching. 
  • Uses Jinja 2 templating. 
  • Support for secure Cookies. 
  • 100% WSGI 1.0 complaint. 
  • Unicode based.
  • Extensively documented.
So, enough of the theoretical detail, lets start with the practical :). 

 Installation 

Flask depends on two external libraries, Werkzeug and Jinja2. So how do we get it to our local machine? There are many ways to do it but I did it with virtualenv. Now, for someone like me who is new to Python, the next question is "What the hell is a virtualenv?". Well virtualenv is a tool to create isolated Python environments. You can find more details on the official website.

So how do we get virtualenv. Well that's very simple. 

Note: 

1. The installation I did was on a Linux Fedora 14 machine with root privileges, there is a possibility that few of the commands can differ from one version of Linux to another.
2. Another thing, I am considering that you already have Python, python-setup-tools and python-pip installed on your machine. In case you don't have it and don't know how to get it see my last post "Getting Ready with Python-PIP".

Installing Virtualenv

You can get virtualenv package using easy_install or python-pip. In my case, I used python-pip. fire up a shell and run following commands: 

pip-python install virtualenv
This command will give you this:
[root@localhost dev]# pip-python install virtualenv

Downloading/unpacking virtualenv
Downloading virtualenv-1.7.tar.gz (2.1Mb): 2.1Mb downloaded
Running setup.py egg_info for package virtualenv

warning: no previously-included files matching '*.*' found under directory 'docs/_templates'
Installing collected packages: virtualenv

Running setup.py install for virtualenv

warning: no previously-included files matching '*.*' found under directory 'docs/_templates'
Installing virtualenv script to /usr/bin
Successfully installed virtualenv
Cleaning up...
[root@localhost dev]#

Once the virualevn installation is done the next step is to setup a virtual environment. 

Setting up virtual environment with virtualenv

To setup a virtual environment for python with virutalenv is very simple. 
Step 1 is to create a folder in which you want to have python virtual environment and then create  virtualenv folder within it. Run following commands:
mkdir flaskTestServer
cd flaskTestServer
virtualenv venv
The above set of commands will give you following: 
[root@localhost Dev]# mkdir flaskTestServer
[root@localhost Dev]# cd flaskTestServer/
[root@localhost flaskTestServer]# ll
total 0
[root@localhost flaskTestServer]# virtualenv venv
New python executable in venv/bin/python

Installing setuptools............done.
Installing pip...............done.
Once that's done you just have to activate the virtual environment you just created: 
[root@localhost flaskTestServer]# . venv/bin/activate
(venv)[root@localhost flaskTestServer]#
And you are all set to install you flask server in your own virtual environment. 

Installing Flask Server

Simply run following command:
(venv)[root@localhost flaskTestServer]# pip install flask
And you are all set to start developing your own flask server and run it. 

Example

Now lets make a flask web server to say hello to the world. It's very simple, very very simple.
Make a python script, lets say flaskHelloWorld.py and put in following code: 

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello World!'
if __name__ == '__main__':
    app.run()
So, what did we do here: 
  1. First we imported the Flask class. An instance of this class will be our WSGI application. The first argument is the name of the application’s module. If you are using a single module (as in this example), you should use __name__ because depending on if it’s started as application or imported as module the name will be different ('__main__' versus the actual import name). For more information, have a look at the Flask documentation.
  2. Next we create an instance of this class. We pass it the name of the module or package. This is needed so that Flask knows where to look for templates, static files, and so on.
  3. We then use the route() decorator to tell Flask what URL should trigger our function.
  4. The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.
  5. Finally we use the run() function to run the local server with our application. The if __name__ == '__main__': makes sure the server only runs if the script is executed directly from the Python interpreter and not used as imported module.
And run it with Python.
(venv)[root@localhost flaskTestServer]# python flaskHelloWorld.py
 
* Running on http://127.0.0.1:5000/
Now open up a browser and go to the address  http://localhost:5000/ or http://127.0.0.1:5000/ and flask will say hello to you like in the screen-shot below:


 












And that's it. Wasn't that easy :).


Tuesday, July 17, 2012

Maven Repositories and configuration

I have recently started writing about Apache Maven. What I wrote till now and what I am going to write in this post are quite basic stuff about Maven, the must know kind of stuff.


So till now I have written about the Apache Maven - Setting Up and Configuring Maven Local Repository in my previous posts. What I am going to write now is about the different types of repositories in Maven. How you can configure them and some basic theoretical explanation on this. From my point of view, these are some of the basic stuff one should know before getting their hands dirty with Apache Maven.


What is Repository?

A repository in maven is like a library in real world. Its a place where all the build artifacts and dependencies of varying types are stored. According to Apache Maven documentation, there are strictly two types of repository, local and remote. 

Different types of Maven Repositories

So, to start with, there are 3 types of Maven repositories:
  • Maven Local Repository.

    Maven local repository is like a library we have at home with books which only concern us. Here in this case, it's a place on our own machine where all the dependency libraries of your project which have been downloaded using Maven are stored. These files usually include plugin jars. It acts as a cache of the remote downloads. 
  • Maven Remote Repository.

    Now, the Remote Repository is like a public libraries in real world. Anyone can access it. In Maven's case, it refers to any repository which one can access using variety of protocols like file:// or http://. Now these repositories can be at least two types:
    • Third-Party public repository
      These are truly remote repository which are completely public, set up by a third party to provide their artifacts for downloading like maven2 repo.Also, you can search for dependencies here. You need an internet connection to connect to these repositories.

    • Internal Repositories
      These are internal repositories set up within an organization with limited access to their own network. It's used to share private artifacts between development teams and for releases. You need at least a network connection (not internet specifically until and unless the repository is at another geographical location) to connect to these repositories.

How to use/configure repositories?

  • Maven Local repositories.

    In general, there is no need to do anything with the local repository on regular basis, until and unless you are required to free some disk space and you need to do a clean up or you can erase it provided you are willing to download everything from beginning.
    For configuring the local repository see my old post Configuring Maven Local Repository.
  • Maven Remote repository.

    Central and Third Party Repository:
    You can use these to download dependencies and sometime upload provided you have permission to do so.
Maven Central Repository
Downloading a dependency in Maven is triggered as a result of missing dependency in the local repository. By default, Maven will look for dependency in the central repository which is set to look in maven2 repo.
The central repository is managed by Maven community. You can edit the setting.xml for maven to globally use some other repository or you can edit in the project's pom.xml, which will only work for that project.
Now let's see how can we configure Maven (pom.xml) to look for a dependency in a remote repository (not the central repository). 
<project> 
   .....
   <dependencies>
      <dependency>
         .....
      </dependency>
      .....
   <dependencies>
   .....
   <repositories>
      <repository>
         <id>organization-name.lib1</id>
         <url>http://download.organization-name.org/maven2/lib1</url>
      </repository>
      <repository>
         <id>organization-name.lib2</id>
         <url>http://download.organization-name.org/maven2/lib2</url>
      </repository>
      .....
   </repositories>
   .....
</project>
Maven Internal Repository:
Using the internal repository is quite simple. You just add the repository element and mention the location of internal repository. Something like this:
<project>
  ...
  <repositories>
    <repository>
      <id>my-internal-site</id>
      <url>http://myserver/repo</url>
    </repository>
  </repositories>
  ...
</project>
If your internal repository requires authentication, an id element can be used in the settings file to specify login information.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>
  </servers>
  ...
</settings>
After studying a little a about Maven, in my opinion it's not that difficult. What do you think? Share your experience and issues related to maven.