Zdanek devBlog+

July 1, 2010

NoClassDefFoundError: org.slf4j.impl.StaticLoggerBinder

Filed under: java, maven — Tags: , , — zdanek @ 10:20

I get error while running code with Hibernate 3.5.x

java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:165)
at org.hibernate.ejb.Ejb3Configuration.<clinit>(Ejb3Configuration.java:127)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at pl.bartekzdanowski.MyTest.setUp(MyTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
… 43 more

The solution is described on SLF4j page. Simply you have to add slf4j-api with wersion greater than 1.5.6. In maven pom.xml you can declare slf4j explicitly:

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

April 27, 2010

InetAddress.isReachable() jest do bani

Filed under: develop, java — Tags: , — zdanek @ 09:56

Napisałem mały program testujący czy klient “widzi” prawidłowo adres i porty naszego serwera aplikacyjnego. Zdarza się, że Firewalle klientów skutecznie blokują łączność.

Zależało mi, aby w pierwszym kroku “spingować” hosta. Niestety wczoraj odkryliśmy buga, bo polegałem na metodzie InetAddress.isReachable(). Tymczasem sposób jest do chrzanu, bo implementacja nie pinguje a odpytuje usługę echo, która stoi na porcie 7. Wielu adminów blokuje tego typu usługi, starając się maksymalnie uszczelnić serwery. U nas w firmie też i dlatego nasi klienci dostawali informację, że istnieje brak łączności z jednym z serwerów.

Nie dostarczę dzisiaj rozwiązania, z braku czasu, ale wrócę do tematu kiedyś.
Poniżej wadliwy kod:


 final String host = "zdanek.ostrejezyki.pl";
 final int timeOut = 3000;

 final boolean status = InetAddress.getByName(host).isReachable(timeOut);

 if (status == false) {
      throw new IOException("Brak lacznosci z " + host);
 }

April 26, 2010

Zero Cobertura coverage

Filed under: develop, maven — Tags: , , — zdanek @ 14:58

Recently I had zero code coverage during tests. I had a maven2 project (under maven 1.0.9), with default cobertura version, which was 1.9.

All reports were generated normally except all code coverage was zero (0).

The reason was somehow buggy cobertura version 1.9.
After I put cobertura-maven-plugin configuration into my pom.xml specifying cobertura version 2.4


<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.4</version>
</plugin>

all went well and finally I had my non-zero coverage :D

(Edit: I’ve added some pretty screenshots :])

April 16, 2010

W końcu logować z IF (isDebugEnabled()) czy nie?!

Filed under: develop, java — Tags: , , — zdanek @ 12:52

Ostatnio staram się pisać małe metody, w imię czytelności kodu. W związku z tym każda dodatkowa linijka zwiększa objętość metody. W malutkich metodach jedna linia to nawet kilkadziesiąt procent objętości :) A co z logowaniem informacji debugujących? Zgodnie z zaleceniami autora Log4j (bo tego loggera zazwyczaj używam), przed zalogowaniem debug() powinno się sprawdzić czy ten poziom jest włączony, aby niepotrzebnie nie tracić czasu procesora na inicjalizowanie stringa do zalogowania. Ceki Gülcü, autor Log4j, w 2002 przekonywał, że sprawdzanie IFem poziomu na PII 233MHz zajmuje nanosekundy, co stanowi mały narzut. Rzeczywiście. A co, gdyby w imię czytelności kodu zrezygnować z tego sprawdzania? Co się wówczas stanie? Ile czasu stracimy? I czy mimo wyłączonego logowania niepotrzebnie wiadomość będzie przetwarzana wewnątrz loggera?

Otóż, oba popularne loggery Log4j i java.utils.Logging sprawdzają czy dany poziom jest włączony i oczywiście nie logują komunikatu, jeśli nie pasuje do poziomu. W takim razie jedynym istotnym problemem jest czas konstruowania wiadomości do zalogowania. Zazwyczaj jest to operacja sklejania kilku stringów, bo chcemy zalogować jakąś operacje np. z jej parametrami. Warto przy tym zauważyć, że czasy kiedy “jakiś string” + “inny” powodowało kilka wywołań konstruktora String(). Od javy 1.5 (lub wcześniej, bo nie wiem) , sklejanie stringów zawsze jest zastępowane StringBuilderem, a więc jest bardzo efektywne. W związku z tym, każdorazowo należy rozważyć czy dany string, który chcemy zalogować jest złożony czy nie. Jeśli nie, to moim zdaniem nie warto stosować IFów, tylko bezwzględnie pchać go loggera.

A teraz konkretne miary, jako, że jestem inżynierem. Test wykonany na procku dual core 2.66GHz, czyli rząd wielkości szybszy od twórcy Log4j. Dzisiaj uważany za przeciętnie dobry sprzęt.
Napisałem program, który 100 000 razy loguje wiadomość, przy wyłączonym debugowaniu. Przy czym w pierwszym teście odbija się od sprawdzenia IFem czy włączone jest debugowanie, a w drugim wchodzi do środka metody logującej. Logowany string to

"Wiadomosc testowa, index " + i + " i jeszcze string"

Mamy tu 3 operacjie StringBuilder.add(), przy czym dla int i jest najbardziej kosztowna, bo i jest od razu zamieniane na string. Wynik:

Test logow bez wlaczonego debuga, ze sprawdzaniem IF
Czas 0ms
Test logow bez wlaczonego debuga, bez sprawdzania IF
Czas 93ms

0 ms oznacza rzeczywiście submilisekundowe czasy sprawdzania czy poziom to DEBUG. 93 ms w rozłożeniu na 100 tyś. wywołań daje nam 93 ns (nano sekund!) na sklejanie. Dodam na koniec, że zaskoczony wynikiem podejrzewałem mocną optymalizację ze strony JVM, czego nie da się wykluczyć, ale drugi test z wielokrotnym powtórzeniem logowanej wiadomości (czyli rezygnacja z pętli) dało również submilisekundowe wyniki. Wkleiłem setkę razy

logger.debug("Wiadomosc testowa, index " + (i++) + " i jeszcze string");

Konkluzja: moim zdaniem przy prostej treści logowanej wiadomości, można zrezygnować ze sprawdzania poziomu logowania na rzecz uproszczenia (wizualnego) kodu.

Źródełko:

package pl.ostrejezyki.zdanek;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LoggingEffectivenessTests {

    private static Logger logger = Logger.getLogger(LoggingEffectivenessTests.class);

    public static void main(String[] args) {

        initLog4j();

       testCheckingIfDebugIsEnabled();
       testWithoutCheckingIfDebugIsEnabled();

    }

    private static void testWithoutCheckingIfDebugIsEnabled() {
        long start;
        long stop;
        System.out.println("Test logow bez wlaczonego debuga, bez sprawdzania IF");

        start = System.currentTimeMillis();
        for (int i = 0; i &lt; 100000; i++) {
            logger.debug("Wiadomosc testowa, index " + i + " i jeszcze string");
        }
        stop = System.currentTimeMillis();

        System.out.println("Czas " + (stop - start) + "ms");
    }

    private static void testCheckingIfDebugIsEnabled() {
        System.out.println("Test logow bez wlaczonego debuga, ze sprawdzaniem IF");

        long start = System.currentTimeMillis();
        for (int i = 0; i &lt; 100000; i++) {
            if (logger.isDebugEnabled()) {
                throw new IllegalStateException("Debug wlaczony, a powinien byc wylaczony");
            }
        }
        long stop = System.currentTimeMillis();

        System.out.println("Czas " + (stop - start) + "ms");
    }

    private static void initLog4j() {
        Logger l = Logger.getRootLogger();
        ConsoleAppender ca = new ConsoleAppender();
        l.addAppender(ca);
        l.setLevel(Level.ERROR);
    }
}

October 8, 2008

Java performance: Strings

Filed under: develop — Tags: , — zdanek @ 13:46

Here’s a short report about different Strings concatenation methods I performed.

Strings joining is very often repeated operation.

String str1 = “Mary had “;
String str2 = “a little “;

String finalStr = str1 + str2 + ” lamb”;

Did you know that creating finalStr will cost you 3 String object creations? Maybe it’s somehow optimized inside JVM but still takes very long time and resources. The solution is to use StringBuffer (synchronized) or StringBuilder (not synchronized). Difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe which means that finalString could be assembled by few concurrent threads. But if you don’t need multithreaded string concatenating (which is the most often case!) use StringBuilder.

Below is the time comparison of three concatenation methods. First I joined 10 strings (often case) and then I checked work time for 1000 strings which will point out sharply performace differences. (Time is given in microseconds)

10 strings

+ concatenation: 126us
StringBuffer: 23us
StringBuilder: 11us

1000 strings

+ concatenation: 11810us (11.81ms)
StringBuffer: 253us
StringBuilder: 123us

Conclusion:
Use StringBuilder!

October 7, 2008

Paralell port programming under Java (Windows XP)

Filed under: develop — Tags: , — zdanek @ 22:32

There’s been a lot of neat articles. So I won’t repeat this topic again. There’s very handy Communications API by sun. But while serial ports worked as a charm I had troubles with paralell port. I couldn’t write any byte into LPT port. I’ve searched the net and I’ve found an important notice from Paul J. Perrone, a java programmer, which I will cite here because it can disappear in the future from cited forum.

“The OS and
driver software must cleary require that the status input lines be
broadcasting signals that indicate the external device is OK (…)

After some more tinkering, the trick was to tie the parallel port
status lines 10 & 11 (Ack and Busy) to low/ground and lines 12, 13, &
15 (paper out, select, & error) to high/5V. This should be done
through the output of a buffer chip though. I also tied lines 18-25 to
low/ground.”

The point is that driver must be shure that there’s a plenty of paper, “printer” is ready to go, there’s no error… All these informations are provided by special status lines, mentioned above. So I did all the soldering. And provided external +5V for proper high states. And well… it didn’t work… :) Maybe it will for you.

So I dug and finally I’ve found a solution for Windows XP. Sorry, this time not for Linux. The problem is that port connection is hardware and OS dependent, so every library must have some kind of JNI library with proper DLL or other native lib.

Library that worked for me can be obtained at http://www.hytherion.com/beattidp/comput/pport.htm I must confess that all the soldering from citation above left in my LPT connector. I’m sure that’s not necessary to put some “config” bits on all these state inputs.

Best regards, and enjoy parallel port programming!

Powered by WordPress

WP-Highlight