Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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:

Image

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. 


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.

    Sunday, July 15, 2012

    Configuring Maven Local Repository

    What is Maven Local Repository?

    Maven local repository is the place on your machine where all the dependency libraries of your project which have been downloaded using Maven are stored. These files usually include plugin jars. 

    Maven Configuration File:

    Maven local repository is defined in it's configuration file which is usually located under directory \conf with name settings.xml.

    Changing Default Maven Repository:

    By default on windows 7, the maven local repository is set for C:\Users\user_name\.m2\. You can change this by editing the settings.xml
    In the settings.xml look for the commented localRepository definition which looks like:
     Image

    Either un-comment it or add the following line:
    D:/dev/maven_repo
    Save the file and you are done. Now all the future dependencies will be downloaded to the path you set. 


    Refer to the Maven Repositories and Configuration post to see what types of Maven repositories are there and how you can configure them.

    Sunday, July 1, 2012

    Apache Maven - Setting up

    What is Apache Maven?

    In simple words Maven is a build automation tool for Java projects. 
    There are many things which can be written for maven but to get more theoretical details  visit Apache Maven-Wikipedia page or can refer to the official Apache Maven website.


    Setting-up Apache Maven:

    Setup - Windows:

    1. First download the latest version maven form here. For this tutorial, I have downloaded maven-3.0.4.
    2. Unzip the downloaded apache-maven-3.0.4-bin.zip. In my case, unzipped it in C:\dev\maven3.0.4.
    3. Set a new environment variable M2_HOME pointing to the directory where maven is installed or  unzipped. In case if you don't know how to set an environment variable in windows, follow the link
    4. Set another environment variable M2 with value %M2_HOME%\bin. In the same way create/update the PATH variable with value %M2% so that Maven can be accessed from command line. 
    5. Check if the PATH variable also has the value of JAVA_HOME pointing to the installed jdk.
    6. Open command prompt (WinKey + R and type cmd) and execute the command mvn --version to see if its installed well.

    Setup - Eclipse:


    For this there is a plugin for Eclipse called M2E which can be used to launch Maven builds from within Eclipse and other stuff which maven can do.
    Follow the steps given below to get M2E on eclipse:
    1. Open Eclipse.
    2. From the eclipse menu list, go to help -> Install New Software...
    3. Get maven from the update site "maven - http://download.eclipse.org/technology/m2e/releases".
      • Add the maven update site and get the list of plugins provided by it.
        Image
      • Select the plugin Maven Integration for Eclipse and press next and next.
        Image
      • Read and accept the terms of license agreement and press finish.
        Image

        Image
      • Restart eclipse.

    More on Maven:

    Feel free to share your experience/issues. 

    Friday, August 7, 2009

    Implementation of Java Interface to Prolog (JPL)

    Following post is the outcome of the time I spent trying to connect a module written in Prolog with another module written in Java.

    Steps for implementing Java Prolog Interface - JPL


    I was trying to interface Java and Prolog using JPL(Java Interface to Prolog). I faced many problem and finally got it working. So I am posting this reply so that if someone else is trying to do this may be it will help him/her.


    The following implementation is for windows XP.


    A string ("an english sentence") was read from user on an HTML page (form) as input using a Java servlet which then passesthe input to a Prolog module which parses the sentence and returns the output.


    Setup:
    To start with, first we hav to install few things:


    1. Install SWI-Prolog Version 5.6.64 . It contains the JPL package so, no need to download it separately.
    2. I used Eclipse IDE for Java EE Developers for my implementation.
    3. Look for "jpl.dll" file in the bin directory of prolog, in my case it was "c:\pl\bin". copy-paste it to "c:\windows\system32" or set the windows path variable to the "c:\pl\bin".
    4. Now look for the "jpl.jar" in the prolog installation folder. Most probably it'll be in "lib" folder of prolog installation. For me it was "c:\pl\lib" and add it to the java library when creating the webproject in eclipse.
    So , now we are ready to call a prolog code from java.


    I am giving a simple example in which we call a prolog code from java and get the output.


    import jpl.Atom;
    import jpl.Query;
    import jpl.Term;
    import jpl.Variable;
    public class J2pl1{
      public static void main(String[] args) {
        // creating a query to consult the prolog program
        if (!Query.hasSolution("consult('D:/PROLOG/learn/familytree.pl').")) {
          System.out.println("Consult failed");
        } else {
          test3a("ria");
        }
      }
      static void test3a(String sent) {
        // a variable which will get the output.
        Variable X=new Variable("X");
        //creating query object to make a query to prolog code.
        Query q3 = new Query("parent", new Term[] {X,new Atom(sent)});
        System.out.println("Parent of "+sent+" is "+q3.oneSolution().get("X"));//get the value stored in X
      }
    }

    The prolog code which was called was:


    % parent(C,P) is true when C has a parent called P
    parent(charles1, james1).
    parent(elizabeth, james1).
    parent(charles2, charles1).
    parent(catherine, charles1).
    parent(james2, charles1).
    parent(sophia, elizabeth).
    parent(george1, sophia).
    parent(catherine,ria).


    So this was a simple implementation for JPL.
    Now what we tried to do here was to pass an English sentence to Prolog and get the output. In my case, the output was a XML file.
    Now in the above java code the arguments of the predicate was passed as atom.


    Query q3 = new Query("parent", new Term[] {X,new Atom(sent)});


    So, in case if your prolog code starts with accepting a list as argument in your predicate the above will not work and I think there is no method in JPL to pass a list to prolog.
    But no need to worry as it can be done by a simple tweak.
    So what we can do? We'll pass the sentence as an atom. So, no need to change the java code.
    What we have to do is to include one more predicate which accepts an atom as input, convertes it into chars or code and then calls ur main fucntion using the builtin predicates "atom_chars(?Atom,?Charlist)" or "atom_codes(?Atom,?String)". To get more details, Check this out.
    So, it'll be like as if a predicate is called "mycode(String)" to start ur prolog execution. Add following:


    start(Atom):-atom_codes(Atom,String),mycode(String).


    And it's done.
    I hope it's clear enough. 


    Enjoy,


    fLiCkEr