Archiv der Kategorie: Java

Java techdocs

Compile, Run And Develop Java in the Console, Setup for TDD with JUnit

When you want to learn Java it is good to know about the basics.

Requirements

  1. Text editor
  2. Java installed

check if java is installed.

java -version

Should be displayed something like that:

java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07-348-9M3406a)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-348, mixed mode)

Creating Development Structure

expected we want to create a project folder and in it an src,bin,lib,test folder.
src = here you create source files (packages)
bin = Output folder
lib = for Libraries e.g. JUnit.jar
test = mirroed the package structure from src, here you develop your tests.

mkdir project
cd project
mkdir src
mkdir bin
mkdir lib
mkdir test

Write a first very simple program

cd src
vim Main.java

type the following:

public class Main{
 public static void main(String[] args){
  System.out.println("Hello User");
 }
}

Back to console compile! Just to see it runs. (You are still in folder src)

javac Main.java
ls

You should see now 2 Files Main.java and Main.class
To run the program just type

java Main

You should see

Hello User

Now delete the Main.class file.

Use Packages

It is recommend to use packages.
create a package (mkdir mypackage)
Java conventions says package names is always lowercase and have no special characters.
move Main.java into the package

mv Main.java mypackage/

Now compile (you are still in src)

javac mypackage/Main.java

You can run the program with 2 Ways

cd mypackage
java Main

Or back in folder src we have to set the classpath (-cp)

java -cp mypackage Main

Set output folder

delete mypackage/Main.class

javac -d ../bin mypackage/Main.java

Now the Main.class file should be in bin folder.
Run the program

cd ../bin
java Main

Or go to project folder and call the Main with classpath

cd ..
java -cp bin Main

Set CLASSPATH

Programmers are lazy so set the classpath.
To view the classpath type

echo $CLASSPATH

If the output is Nothing then the variable isn’t set.
ensure that you are in project folder

export CLASSPATH=./bin

Now you can start the program from here with

java Main

Install JUnit

Download newest version from https://github.com/KentBeck/junit/downloads
Copy the download junit.jar file to your lib folder.
Add the jar to CLASSPATH

export CLASSPATH=$CLASSPATH:./lib/junit-4.9b2.jar

Test wether you reach the JUnitCore class

java org.junit.runner.JUnitCore

You should see something like this.

JUnit version 4.9b2
Time: 0,001
OK (0 tests)

For more information take a look at http://junit.sourceforge.net/doc/faq/faq.htm#started_2

Write a Simple Test

Go to test folder and create a Class SimpleTest with the following content

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
 
public class SimpleTest{
    @Test
    public void testEmptyCollection(){
        Collection collection = new ArrayList();
        assertTrue(collection.isEmpty());
    }   
}

Go back to project folder, compile and run the test.

cd ..
javac -d bin test/SimpleTest.java
java org.junit.runner.JUnitCore SimpleTest

Should be output

JUnit version 4.9b2
.
Time: 0,006
 
OK (1 test)

Annotation

The example SimpleTest.java is taken from http://junit.sourceforge.net/doc/faq/faq.htm#started_2

The Cost of Testing or You don’t Know what You are Missing

The Cost of Testing or You don’t Know what You are Missing

Twice this week people challenged my belief in automated testing and Test Driven Development. The argument that was brought forward was simply: Unit tests are too expensive.

I actually believe the opposite is true. Let me tell you about a little dialog that happened in my development team after two developer where working on a feature for about an hour or two.

First Developer: “I think we got everything. Lets start the application and see if it works.” (starts the application)

Second Developer: “Hmm, doesn’t work.”

First: “Oh, I know, we forget to actually invoke the new feature” (fixes that and restarts the application)

Second: “Looks great. It works. Lets commit it to SVN”

What’s so special about this? They didn’t start the application a single time during the development process for over an hour. Can you do that without writing tests? Of course you can and you will spend restarting the application during the rest of the day until you fixed all the bugs. How long does your application need to restart? Including the time you need to navigate to the state where you can test your application. How long does that take?

Not having to do that. Or at least not very often is a huge time saver. And it’s not only the direct cost of restarting the application. Waiting for the application is often an interruption of your concentration. Do you really think about the next aspect of the feature to implement? Or do you check mail? Get a coffee? In my experience going Test Driven in Pairs is a way more concentrated type of working.

And that is not even considering that your tests will run over and over again, making sure later changes don’t break anything. This alone saved my butt a couple of times.

If you reached that level of TDD it will save money for you and your team. I promise.

But I’ll admit, I didn’t believed that a couple of years ago. I was using tests only when implementing rather abstract stuff. And I thought it wouldn’t be possible to efficiently automate tests for most of the code we wrote. I had to learn a lot. Testing isn’t easy. Most of the code we produce isn’t fizz buzz, but is concerned with GUIs and databases, both make testing hard and expensive. But these problems can be solved, so you can gain the benefit of TDD even for these cases.

And as a side effect you will have to come up with a really nice and clean design of your code in order to test it. This in itself will make future changes more easy and cheap.

Therefore I urge you: Start learning how to test today. If you don’t you will never know what you are missing.

And if promises don’t motivate you: I’m convinced that in a couple of years from now the places where you can just puke code into your IDE will get rare. So if you still have a couple of years to cover until retirement: Beef up your testing skills. It’s one of the best investments you can make in your own future as a software developer.

via Schauderhaft » The Cost of Testing or You don’t Know what You are Missing.

Gegen Schnittstellen, NICHT gegen Implementierungen programmieren

Wenn Sie gegen eine Schnittstelle programmieren, schreiben Sie bspw. List list = new ArrayList(); anstelle von ArrayList list = new ArrayList();, oder definieren als Parameter und Attribute Ihrer Methoden und Klassen keine konkreten Implementierungen, sondern lediglich die Interfaces List, Set, Map, Collection, …. Dies hat den Vorteil der höheren Generalisierung und Kompatibilität, aber auch den Nachteil von fehlenden Methoden und Funktionsweisen konkreter Klassen.

via :http://www.java-blog-buch.de/0802-die-collection-schnittstelle/

The main reason to do this is to decouple your code from a specific implementation of the interface. By writing your code like this:
Map data = new HashMap();
then the rest of your code only knows that data is a Map, which is good, because it you can now easily change to a different implementation of interface Map if necessary. You’d only need to change that one line of code, for example to:
Map data = new TreeMap();
For the rest of your program, nothing changes – data is still a Map.
If you would have written:
HashMap data = new HashMap();
then changing it would have been much harder, because the rest of your code might have used methods that are specific to HashMap.

via: JavaRanch

Java: Constructors

Constructors

When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences.

  • Constructor name is class name. A constructors must have the same name as the class its in.
  • Default constructor. If you don’t define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
  • Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
  • Differences between methods and constructors.
    • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
    • There is no return statement in the body of the constructor.
    • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.

    These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

  • this(...) – Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.
  • super(...). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

via Java: Constructors.

Good Logging Practice

Here are some useful thoughts about logging. Thanks to Jens Schauder.
Take a look at the link at the end to view the orginal post.

Good Logging Practices

Nearly everybody does some kind of logging in their application, but few do it in a well structured way. I’d like to point out some practices that I consider helpful in order to get the most out of your logging. This post will also work as a handout for my talk about logging at the herbstcampus conference. So here we go:

  1. Know your audience. If you look at the log files of many applications you quickly realize who the intended audience is: Developers. The log is full with technical detail, but not much of it makes sense to anybody else. The groups you probably should have on your list are: Developers on the search for bugs, performance issues, Administrators trying to install, start or shutdown your application and Support personal trying to detect and analyze problems or trying to verify that a problem did not occur. Once you realize there are different audiences you’ll understand what kind of information is helpfull in the logs.
  2. Use a framework. The major options are: Log4j, SLF4J, JUL, Commons Logging or Logback. Each one has it’s pros and cons, but they are all better then System.out.println. They allow you to configure at deploy or runtime, what gets logged where and in what format. If you don’t want to do any research, and don’t have special requirements, use SLF4J.
  3. Logging must be rock solid. If a logging causes problems. Throw it out. Don’t do experiments like remote logging, if you can avoid it.
  4. Define rules, when to use which Log Level: I propose the following:
    • DEBUG: Not important, except if you are researching a very specific problem.
    • INFO: General information like startup, shutdown, version and configuration of an application. Information about important decisions in the code or changes in the configuration.
    • WARN: Things that are fishy, but don’t represent a problem in themself, but might indicate a problem when appearing very often. E.g. a failed log in attempt is such a candidate. If it happens sometime it is not a problem, but if it happens a lot somebody might want to look into that.
    • ERROR: This should only be used when a problem occurs that somebody needs to look into. Typically but not necessarily relating to an exception in the code. Use this when only a limited part of the application is affected.
    • FATAL: If something goes completely wrong, rendering the application unable to recover this log level is appropriate, very likely accompanied by a shutdown of the application or the session.

    Of course your rules need some tayloring for your context, but absolutely need rules, and every developer must know and understand those.

  5. Log everything you log exactly once: When analyzing log files I often see log messages that always come in groups. This happens often when exceptions get caught, logged, and rethrown. Don’t do that. Log at the place where you actually do handle the exception. This is the only way to log an exception exactly once and also being able to decide which log level to use.
  6. Include useful information and data: The information should typically include answers to the following questions
    • Why are you logging this, typically the root cause of an exception.
    • What is the affected use case? Did it happen during creation of an order or when importing product data from a remote site?
    • What effect has it on the use case that was executing? Does the user need to repeat the action, or did it succeed? Did the complete batch fail, or just a single step?
    • What instance of the use case was effected? For example an order id.

    In order to make all this information available to your logs MDC (Mapped Diagnostic Context) is tremendously helpful. If you don’t know MDC, follow the link and read about it NOW. MDC exists also in SLF4J and Log4J and should be easy to port for other frameworks as well.

  7. Use more then one logging hierachy: The link contains more information about why. The simple idea is, that you can seperate different aspects you want to log by using different prefixes. This becomes especially usefull when adhering to the following points
  8. Log the time needed for stuff which might be intersting for tuning: Of course this includes the time used for access to remote resources (e.g. webservices or databases) and execution of complex algorithms, but possibly also the time spend in the various layers in the application. You can use different log level for three categories, a separate logging hierarchy for separating performance logging from other stuff. Performance problems a notorious difficult to hunt down, especially when they appear over time. You’ll love this logs, when performance becomes an issue.
  9. Log stuff that worked, not only what failed: Distributed systems become common place more and more. When debugging distributed system one often has the situation that requests just disappear, and it can be extremely challenging to decide which component failed. After all not everybody does such a fine logging as us, right? So I recommend the following log events:
    • RECEIVED: The application received a request through the UI, a Webservice or any kind of interface offered.
    • SEND: The application send a request to some other component.
    • GOT ANSWER:  The application got a reply to a request it send.
    • ANSWERED: The application answered to a request it received.
  • Log how often stuff happens: One possible reason for decreasing performance is a changed usage pattern. So logging how often per day, hour or minute a certain kind of use case is triggered can help tremendously.
  • via Schauderhaft | http://blog.schauderhaft.de/2009/09/16/good-logging-practices/

    Überlegungen zum Logging

    Logging (z.B. in eine .log-Datei oder in eine SQL-Datenbank) ist eine große Hilfe sowohl während der Entwicklungszeit als auch später zur Fehlersuche beim Kunden.

    Logger erlauben das selektive Ein- und Ausschalten bestimmter oder aller Log-Meldungen zur Laufzeit über eine einfache textbasierte Steuerdatei.

    Bewährt haben sich folgende Vorschläge:

    • Verlassen Sie sich nicht auf das sehr rudimentäre und nur für bestimmte Exceptions durchgeführte Logging des Application Servers (normalerweise nur für unchecked RuntimeExceptions, die bis zum EJB-Container gelangen).
    • Verwenden Sie kein Logging per ‘System.out.println(“…”);’, die Konsole ist nicht immer sichtbar und solche Ausgaben sind nicht zur Laufzeit konfigurierbar.
    • Verwendung von Log4j.
    • Alle unerwarteten Exceptions sollten zu einem Logging-Eintrag führen.
    • Zusätzlich können Auslastungs- und Performancekennzahlen sinnvoll sein.
    • Umlaute (ä, ö, ü) und deutsche Sonderzeichen (ß, §, €) sollten vermieden werden.
    • Falls Ausgabe in Datei: Jede Meldung produziert genau eine Zeile, damit ‘grep’ verwendet werden kann (Ausnahme: StackTrace).
    • Wichtig ist eine einheitliche Struktur der Logging-Meldungen, damit sie mit Tools ausgewertet werden können.
    • Definition stets zu verwendender ‘Rubriken': Bei Ausgabe in SQL-Datenbank entsprechen die Rubriken den Tabellenspalten, bei Ausgabe in Datei werden Rubriken durch Semikolons getrennt (.csv-Datei, kann direkt z.B. in Excel bearbeitet werden).
    • Die Rubriken können zum Beispiel sein (in Application-Server-Umgebung): Zeitstempel; Anwendungsname; Thread-Name; Log-Level; Exception-ID; Fehlercode; Meldetext.
    • Der Zeitstempel (Timestamp) formatiert nach ISO 8601 (EN 28601, DIN 5008), also beginnend mit dem Jahr (z.B. ‘yyyy-MM-dd HH:mm:ss.SSS’), damit einheitlich mit Tools ausgewertet werden kann und damit nach Datum sortiert werden kann.
    • Damit in mehrschichtigen Multithreading-Umgebungen zusammengehörende Exceptions identifiziert werden können, kann eine ‘Exception-ID’ (automatisch) generiert werden. Auch sollte doppeltes Logging vermieden werden. Siehe hierzu: ‘http://www-128.ibm.com/developerworks/java/library/j-ejbexcept.html’.
    • Fehler, die möglicherweise zum Beispiel vom System-Operator bearbeitet werden müssen, sollten eindeutige Fehlercode-Nummern erhalten, zu denen in einer Dokumentation das weitere Vorgehen beschrieben ist.
    • Falls Fehlermeldungen oder Logging-Meldungen mehrsprachig sein sollen, verwenden Sie statt der Meldetexte Fehlernummern, die dann über .properties-ResourceBundles aufgelöst werden.

    via Exception Handling und Logging.

    global variables in Java

    There are no global variables in Java in the meaning of variables which would be valid in the whole program.

    There are

    • class variables: These are most similar to what are called “global” variables in other languages. They are declared inside a class with the static keyword. There is only one variable for the whole class. (If the class would be loaded again with another classloader, this new class would have new variables, of course.)

      They should be used prefixed with the class: MyClass.varName. Inside of the class you also can let the prefix away, and you also could use them prefixed with an object of that type (but this is discouraged).

    • instance (or object) variables: These are what you have in your example: anything declared inside a class (and outside of any method/constructor/block) without the static keyword is a instance variable. For each object of the containing class (which includes objects of any subclasses of this class) there is exactly one variable. (From the “state” view, one could say an object consists of all its instance variables + an identity.)

      They are used prefixed by an object (of the right type): myObject.varName. Inside of non-static methods of this class you can use them unprefixed (this is then referring to the variables of the current object).

    • local variables: These are all variables declared inside of a method or a constructor (or block). They exist once for each invocation of this method, and cease to exist after the method finished. They can only be accessed from inside this method, not from methods called from there.

      Special cases of these are method/constructor parameters and catch-block-parameters.

    • array elements: Every element of an array is a variable of the same type. They can be used everywhere where one has a reference to this array (often in one of the other types of variables).

    via: Java only allowing global variables to be static? – Stack Overflow.

    How to validate email address with regular expression

    How to validate email address with regular expression.

    ^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@
    [A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

    Whole combination is means, email address must start with “_A-Za-z0-9-” , optional follow by “.[_A-Za-z0-9-]“, and end with a “@” symbol. The email’s domain name must start with “A-Za-z0-9″, follow by first level Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, .com.my) “\\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.

    API – Blog von Jens Franke » Flash

    Ich will niemandem den Spaß am Spielen mit den APIs nehmen, aber schreitet als Entwickler ein, wenn Dritte API-Demos zu einem Konzept zaubern. Verwendet ihr APIs von Dritten, dann solltet ihr immer ausreichend Buffer einkalkulieren.

    Nicht selten kommt man in Grenzbereiche der API, wo man sich entweder tief in die API einarbeiten muss, um sein Ziel zu erreichen oder einfach in der Abhängigkeit gefangen ist und warten muss bis die API-Entwickler einen erhören und dann auch noch das Richtige veröffentlichen.

    Eine Gradwanderung, die viel Feingefühl und einen kühlen Kopf benötigt.

    Blog von Jens Franke » Flash.

    Eclipse Shortcuts

    Meine Lieblings-shortcuts

    F4
    Zeigt die Hierachie an. Sehr nützlich. Von welchem Classe wird abgeleitet? Welche weiteren Ableitungen gibt es?
    Ctrl + Leertaste
    Verfügbare Methoden anzeigen, Autovervollständigung
    Ctrl + 1
    Quickfix öffnen. Wenn ein Methodeaufruf einen error meldet. Cursor drauf und Ctrl+1. Quickfix Vorschläge werden angezeigt
    Ctrl + Shift + O
    Imports Organisieren (überflüssige löschen, notwendige hinzufügen)
    Ctrl + Shift + G
    zeige alle Referencen im Workspace.
    Ctrl + s
    Speichern
    Alt + Shift + J
    Javadoc comment skeleton erstellen.
    Shift + F2
    Javadoc aufrufen. (Java) mit Cusor auf einem Klassennamen. Es wird die API aufgerufen und zur Beschreibung der Klasse oder Methode gesprungen.
    ALT + Pfeil Hoch / Pfeil Runter
    Verschiebt die markierten Zeilen.
    CTRL + ALT + Pfeil Hoch / Pfeil Runter
    Kopiert die markierten Zeilen.
    Ctrl+Shift+M
    Static Import.
    Ctrl + Shift + L
    Zeigt alle verfügbaren Shortcuts an

    Hinweis

    Die hier aufgelisteten Shortcuts beziehen sich auf eine “normale” Eclipse Installation mit Java Plugins.
    Es gibt ja auch IDE´s, z.B. ColdFusion Builder, die auf Basis von Eclipse erstellt wurden. Diese IDE´s haben mitunter andere Shortcuts bzw. nicht die selben oder auch einfach nur deaktiviert.

    Coldfusion Builder
    Die Shortcuts für den Coldfusion Builder lassen sich wie folgt anzeigen.
    Help -> Key Assist…

    Meine Lieblings-shortcuts für den CF-Builder

    Ctrl + Shift + D
    cfdump var =”##”
    Ctrl + Shift + O
    umschließendes cfoutput … /cfoutput
    Ctrl + Shift + H
    umschließendes # … #
    Ctrl + Shift + M
    umschließendes Kommentar. Aus,- und Einkommentieren.

    Diese Liste ist auch im Coldfusion Blog veröffentlicht.