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

Tuesday, March 3, 2009

Set up a project managed by SVN

Samuel agreed to help me and get into this project, which makes me so happy. For the sake of teaching me conveniently, he set up a project in sourceforge.net, and told me how to use SVN to manage the project. The name of our project is Biological Network COmparison Toolkit(bnct), and weblink is: https://sourceforge.net/projects/bnct/.

Here is how to set up a project locally managed by SVN.

Firstly, download TortoiseSVN and install it. After the installation, it is integrated into the Windows Explorer. Create an empty folder to hold the coming project,for example, D:\Projects\bnct, and enter it.

Secondly, in this folder, right click and select SVN Checkout, then a property window pop out for setting.

Set the URL repository to: https://bnct.svn.sourceforge.net/svnroot/bnct/trunk, leave others default and click OK to make sure. After this, the fold will contain one gray .svn folder and several folder ticked like this:

Fourthly, right click on bnct, tortoiseSVN -> Settings, go to context menu. In the Cascaded context menu, make these options: Checkout.., Update, Commit.. , Diff and Check for modifications... checked then click OK for sure.

Next, go to Diff Viewer in the settings of TortoiseSVN, configure the program used for comparing different revisions of files as the External program. Here we use WinMerge. Set it like this:
After that, click OK.

TortoiseSVN -> Repo-browser, here is the view of the svn repository in sourceforge. You can check the project in sourceforge conveniently.

Thursday, February 19, 2009

How to debug or run a maven project

Here is the steps to add a tag for running or debugging a maven project. Open "Debug Configurations" by right click on the Eclipse. Also you can open this window by "Run" menu.
1. Give your tag a name, for exmaple, "run App";
2. Use "Browse file system " to fill in the Base directory. For my project, it should be "D:\Projects\netcomp\netcomp", the root path for the project.

3. Fill the blank of Goals by "clean package exec:java";

4. Click Configure at the right side of Maven Runtime and add an external address for the Maven running. It should be the path where your maven installed.

After all the steps, the "run App" tag for running a maven project is built up. When you need to do the debugging, enable the debug configurations window and click debug.

The import of netcomp

"netcomp" is the name of my little project.
Yesterday, after Samuel helped me modified it, I try to update the codes by cover the old files by the new ones. However, because Eclipse has some kind of history record for the old java files, after I re-open Eclipse to see the imported new java files, there are a lot of red crosses on the left side of the new packages and methods. Samuel told me to "Clean ..." and then "Update all the Maven projects" in the project menu of Eclipse. Because I didn't do it in the right order, it seemed useless. So I delete all the projects (there are kegg and netcomp previously) and try to import them in by click "import" and "Maven project". But it's wrong.
The right way to import the maven project to eclipse is,

Step 1. Unzip netcomp to D:\Projects. So now the right path for netcomp is D:\Projects\netcomp.

Step 2. run cmd and cd D:\projects\netcomp. Under this path, run : mvn eclipse:clean

Step 3. cd D:\projects\netcomp\netcomp. Under this path, run: mvn eclipse:eclipse.

Step 4. under D:\projects\netcomp, run: mvn clean install.
Up to now, my own .project for maven is generated.
Note: Run mvn eclipse:eclipse in the child netcomp, the one will be imported in the Eclipse as an existing java project later.

Step 5. In Eclipse, "Import" -> "General" -> "Existing Projects into Workspace" -> "Next" -> "Browse" to select the root directory. When you open "D:\Projects\netcomp" by browse, "netcomp" project will appear in the blank for Projects in this window. Then select it and "finish". If Kegg project appears in this blank too, omit it, it's enough only to import netcomp project.
Attention, in this step, it must be "Existing Projects into Workspace" instead of "Maven project" which is imported. It doesn't mean the option "Maven project" is useless, but since we've already built up the project by (cmd -> mvn eclipse:eclipse) , this project is an Existing project insead of an unbuilt Maven project. If you insist to use "import Maven project", then step 3 should be omitted. Or else, this import can be failed.

The installation of Eclipse and M2Eclipse

Before Eclipse, I've tried JBuilder, Together and MyEclipse. All these are the bundle of Java tools, whose core is Eclipse. They are cracked warez. So when I try to install M2Eclipse, the Maven add-on, various problem occurred. Finally I make up my mind to uninstall them all and turn to the simple Eclipse.

As an open source software, Eclipse is no need to be installed. The version I use now is eclipse-java-ganymede-SR1-win32, the economical version. I copy the unzip folder to C:\. So the installation path is C:\Eclipse.

Step 1. Modify Eclipse.ini and change the target of quick link for eclipse.exe.
I don't know why this file have to be modified. But if not, you will get error report when you run Eclipse with Maven together.
Add the following line in front of -vmargs.
"-vm
C:\Java\jdk1.6.0_10\bin\javaw.exe"
Meanwhile, change the properties of the quick link for Eclipse. The new Target should be "C:\Eclipse\eclipse.exe -vm C:\java\jdk1.6.0_10\bin\javaw.exe".

Note: Here is a bug for JVM. If you add "-vm C:\Java\jdk1.6.0_10\bin\javaw" instead of "-vm C:\Java\jdk1.6.0_10\bin\javaw.exe". It will show a "FATAL ERROR" message after the "BUILD SUCCESSFUL" of Maven information when debugging.

Step 2. Install M2Eclipse for Eclipse. (Note: M2Eclipse means "maven version 2 for eclipse")
In Eclipse, click "Help", then "Software Update", then "Avaliable Software",then "Add site". In the blank for "Location", fill in "http://m2eclipse.sonatype.org/update/ ". After that, the List of avialbe software will include "Maven Integaration for Eclipse Update Site". Make sure it's selected, then click "Install" on the right side. When the installation is finished, then this add-on is installed successfully.

Log4j

Log4j, I think, means "log for java". It is an useful tool to show the list of debugging or running log. Log4j has 6 levels, which are FATAL, ERROR, WARN, INFO, DEBUG and TRACE.
There are two ways to configure log4j. One is with a properties file, named log4j.properties, and the other is with an XML file. Within either these 3 components are necessary: Loggers, Appenders and Layouts. Configuring logging via a file has the advantage of turning logging on or off without modifying the application that uses log4j.
Loggers are logical log file names; The actual outputs are done by Appenders. Appenders use Layouts to format log entries.
To debug a misbehaving configuration use the Java VM Property - Dlog4j.debug which will ouput to standard out. To find out where a log4j.properties was loaded from inspect getClass().getResource("/log4j.properties");
Here is An Example Samuel wrote, which is the content of log4j.properties in /Main/Resource.

# The root logger is assigned priority level info and it's appender is stdout
log4j.rootLogger=info, stdout

# stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{dd/MM/yy HH:mm:ss} %c{1} %p - %m%n

# limit categories
log4j.logger.com.tt.netcomp=INFO

He said actually he diddn't use log4j directedly, but use Commons Logging(JCL) instead, whose backend includes Log4j.
This sentence, "log4j.appender.stdout=org.apache.log4j.ConsoleAppender" is to write log information out to the console; but if we need to write it out to a certein file instead of console, we can use the following sentence:
log4j.appender.stdout=org.apache.log4j.RollingFileAppender
log4j.appender.stdout.File= filepath

For example, it can be something like this:

# ----------------------log4j.properties -----------------------------------------#
# The root logger is assigned priority level infor and it's appender is fileout;
log4j.rootLogger = INFO, fileout

# fileout
log4j.appender.file out=org.apache.log4j.RollingFileAppender
log4j.appender.fileout.File=output.log
log4j.appender.fileout.MaxFileSize=100KB
log4j.appender.fileout.MaxBackupIndex=1
log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
log4j.appender.fileout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

# limit categories
log4j.logger.com.tt.netcomp = INFO

# --------------------Over----------------------------#

In addition, different package can be set to different limit level. For example,

# limit categories
log4j.logger.com.tt.netcomp. domain = DEBUG
log4j.logger.com.tt.netcomp. service = WARN

In this case, domain package will have the limit level as debug while service package as warn. The other package are set to be info as default since we assign the rootLogger level as INFO in the root setting area.

Sunday, February 15, 2009

What's Maven


These days I learnt a lot on Maven and Java, especially how to use it. I need to record them one by one so as not to forget them soon.

First of all, what's Maven. (Maven in five minutes.)

The most useful two commands:
1.
project_path>mvn clean package, to rebuild
2. project_path>mvn clean package exec:java, to clean, rebuild and run it.

Import Maven add-on to MyEclipse. Since the Together and the JBuilder I used before didn't support this add-on, M2Eclipse, because of their old version, I have to change the work tool to MyEclipse.

Step 1.
Afte
r installation of MyEclipse, click Help, then Software Updates, then Find and install, then Search for new features to install. It will open a new window.

New Remote Site... Then Type M2Eclipse in the name area and copy this line: http://m2eclipse.sonatype.org/update/ to URL. Then finish.Select the options of the M2Eclipse tree which would not fail the update(there are three not to enable)
Step 2.
Winkey + R open
the cmd window. Go to the project folder, here is D:\project\netcomp. Execute this command of mvn:
mvn eclipse:eclipse


Step 3:
Go to Eclipse, import the two projects, kegg and netcomp.

Step 4.
Right click the projects one bye one. There is a maven menu, choose "Enable Dependency Management". Now the projects are managed by Maven dependently.








Saturday, January 17, 2009

What's a Java Project

Embarrassingly speaking, I don't know what is a Java Project exactly now although I've used it for several months. What's a Java Project? Is one project only set up to do one work? This problem puzzles me all day long.
Suppose here I need to do one work, which can be divided into three steps and conquered. Each step can be regarded as a smaller size work too. In this case, which is better, to set up a huge project to fulfill the overall work, or to set up three small projects for the three sub-tasks and then combined them together?
Samuel said it depended on my problem. Since now what I am touching is some small problem, I may only need to set up one project to include all of my problems as sub-tasks.
Usually a project can be considered as a system, from which a program for application will be generated. A project can have more than one Main function, and be compiled into more than one Jar files according to demand.
A small system can only have one application while a large one can have more. Meanwhile, a huge system can be composed of several smaller system, which in turn have several applications hierarchically.

Friday, January 9, 2009

The classic IO code

Get string from keyboard:

String input;
BufferedReader buf = new BufferedReader(new InputStreamReader(
System.in));
input = buf.readLine();

Write strings to the created file:

File f = new File(outfile);
f.createNewFile();

BufferedWriter output = new BufferedWriter(new FileWriter(f));
String out = "this is for test.";
output.write(out);
output.close();

On "java.lang.ArrayIndexOutOfBoundsException"

I try to assign the organism and pathway through arguments, but unexpectedly I got an exception: java.lang.ArrayIndexOutOfBoundsException. Having searched google I know it's caused because I try to index an empty array.
At first I didn't put in any arguments, so the argument array is empty. But I try to read in the organism name as well as pathway name from the empty arrays, then the exception is caused.

Now I have to try to find a better way to deal with the input arguments.

Highlight:
"java.lang.ArrayIndexOutOfBoundsException" is
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Tips and Tricks on How to Use Eclipse

http://www.javaresearch.org/article/57437.htm

Following these tips posted online, I set my Eclipse on the server. Here is some hotkeys:

1. sysout + shift + space, it will add "System.out.println();" automatically;
2. If you want to comment some blocks, choose these codes and press "ctrl + /" simultaneously. On the contrary, if you want to uncomment it, press "ctrl + \";
3." Ctrl + F8" is used for switching prospective quickly.
4. The hotkey for "Debug Java Application" is "Alt + D";

(To be continue);

Thursday, January 8, 2009

Connect to KEGG by KEGGAPI

These two days I spend much time on the codes for connecting KEGG by its API. Fortunately the KEGGAPI is updated to adapt to use AXIS 1.4 version, which means that I don't need to do the pretreatment as described at the website.

Here I write some code according to its Javadoc. Having got all the ports opened, it runs pretty well. Thus I know where the previous problem is: The remote machine doesn't allow the script out because only the port 3128 is open.


package org.tingting.bn.mn.networkbuilder.test;

import org.tingting.bn.mn.networkbuilder.domain.KeggConnector;

import keggapi.Definition;
import keggapi.KEGGPortType;

public class TestKeggConnector {

/**
* @param args
*/

public static void main(String[] args){

KeggConnector conn = new KeggConnector();
KEGGPortType serv;

try{
serv = conn.getServ();
Definition result[] = serv.list_pathways("hsa");

for( int i = 0; i <>

Wednesday, December 10, 2008

Inner Classes

Q1:

When you create an inner class, an object of that inner class has a link to the enclosing object that made it, and so it can access the members of that enclosing object -- without any special qualifications. In addition, inner classes have access rights to all the elements in the enclosing class.

How to understand this paragraph?

Answer: The inner class secretly captures a reference to the particular object of the enclosing class that was responsible for creating it. Then, when you refer to a member of the enclosing class, that reference is used to select that member. Construction of the inner-class object requires the reference to the object of the enclosing class, and the compiler will complain if it cannot access that reference. Most of the time this occurs without any intervention on the part of the programmer.

Q2. Does an outer class have access to the private elements of its inner class?

Seems the answer is yes from the result of my little test code. But why?

Q3.
If you're defining an anonymous inner class and want to use an object that's defined outside the anonymous inner class, the compiler requires that the argument reference be final. If you forget, you'll get a compile-time error message. Why?

Tuesday, December 9, 2008

Interfaces

The fields in an interface are implicitly static and final. The fields, of course, are not part of the interface. The values are stored in the static storage area for that interface.

Factory Method design patter: instead of calling a constructor directly, you call a creation method on a factory object which produces an implementation of the interface -- this way, in theory, your code is completely isolated from the implementation of the interface, thus making it possible to transparently swap one implementation for another.

An appropriate guideline is to prefer classes to interfaces. Start with classes, and if it becomes clear that interfaces are necessary, then refactor. Interfaces are a great tool, but they can easily be overused.

Thursday, December 4, 2008

The Key Words: static & public & final

public: so they are usable outside the package;
static: to emphasize that there's only one
final : to say that it's a constant.

Note that final static primitives with constant initial values(that is, compile-time constants)

Choosing composition vs. inheritatnce

Both composition and inheritance allow you to place subobjects inside your new class(Composition explicitly does this- with inheritance it's implicit.) You might wonder about the difference between the two, and when to choose one over the other.

Composition is generally used when you want the features of an existing class inside your new class, but not it's interface. That is, you embed an object so that you can use it to implement features in your new class, but the user of your new class sees the interface you've defined for the new class rather than the interface from the embedded object. For this effect, you embed private objects of existing classes inside your new classes.

Sometimes it makes sense to allow the class user to directly access the composition of your new class; that is, to make the member objects public. The member objects use implementation hiding themselves, so this is a safe thing to do. When the user knows you're assembling a bunch of parts, it makes the interface easier to understand.

When you inherit, you take an existing class and make a special version of it. In general, this means that you're taking a general-purpose class and specializing it for a particular need.

The is-a relationship is expressed with inheritance, and the has-a relationship is expressed with composition.

In OOP, the most likely way that you'll create and use code is by simply packaging data and methods together into a class, and using object of that class. You'll also use existing classes to build new classes with composition. Less frequently, you'll use inheritance. So although inheritance gets a lot of emphasis while learning OOP, it doesn't mean that you should use it everywhere you possibly can. On the contrary, you should use it sparingly, only when it's clear that inheritance is useful. One of the clearest ways to determine whether you should use composition or inheritance is to ask whether you'll ever need to upcast from your new class to the base class. If you must upcast, then inheritance is necessary, but if you don't need to upcast, then you should look closely at whether you need inheritance. The Polymorphism chapter provides one of the most compelling reasons for upcasting, but if you remember to ask "Do I need to upcast?" you'll have a good tool for deciding between composition and inheritance.

Overloading and Overriding

Overloading is a one of the ways in which Java implements one of the key concepts of Object orientation, polymorphism.Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method.(That is in brief, different signatures, different implementation, for the method)


Overriding a method means that its entire functionality is being replaced. It is something done in a child class to a method defined in a parent class. To override a method a new method is defined in the child class with exactly the same signature as the one in the parent class.(That is in brief, same signatures but different implementation)

Java SE5 has added the @Override annotation, which is not a keyword but can be used as if it were. When you mean to override a method, you can choose to add this annotation and the compiler will produce an error message if you accidentally overload instead of overriding.

The @Override annotation will thus prevent you from accidentally overloading when you don't meant to.

When to initialize an object

It makes sense that the compiler doesn't just create a default object for every reference, because that would incur unnecessary overhead in many cases. If you want the references initialized, you can do it:

1. At the point the objects are defined. This means that they'll always be initialized before the constructor is called.

2. In the constructor for that class.

3. Right before you actually need to use the object. This is often called lazy initialization. It can reduce overhead in situations where object creation is expensive and the object doesn't need to be created every time.

4. Using instance initialization.