Frickelblog

5. Februar 2010

JXMapKit: Karten schneller und gleichzeitig laden

Abgelegt unter: Java — frickelblog @ 10:04
Tags: , , ,

Verschiebt man die Karte eines JXMapKit, müssen ja logischerweise Kartenteile (Kacheln) nachgeladen werden.
Per Default werden immer nur 4 Kacheln gleichzeitg geladen. Bei entsprechend schneller Verbindung macht es durchaus Sinn, diese Zahl zu erhöhen:

((AbstractTileFactory) jXMapKit.getMainMap().getTileFactory()).setThreadPoolSize(10);

Und schon wird spürbar schneller nachgeladen. Allerdings muss der Aufruf durchgeführt werden, bevor die erste Kachel geladen wird, wie die Javadoc aussagt:

/**
* Set the number of threads to use for loading the tiles. This controls the number of threads
* used by the ExecutorService returned from getService(). Note, this method should
* be called before loading the first tile. Calls after the first tile are loaded will
* have no effect by default.
* @param size
*/

Siehe auch: “Erste Schritte mit JavaX JXMapKit

28. Januar 2010

PHP BibTex-Parser

Abgelegt unter: Sonstiges — frickelblog @ 21:05
Tags: ,

Nachdem ich derzeit BibTex-Einträge verarbeiten muss darf, habe ich doch gleich mal die Komplexität von bibTex unterschätzt und bin dem NIH-Syndrom verfallen und wollte selbst einen Parser schreiben. “Mal schnell” widerspricht dabei dem Drang nach Vollständigkeit – also: etwas Freizeit für die Erkenntnis geopfert, nächstes mal gleich länger zu suchen.

Nach einigen Missgriffen habe ich dann doch noch einen vielversprechenden Link gefunden: Bibliophile.

Der BibTex-Parser scheint doch vollständiger zu sein, als alles was ich bisher angesehen habe. Ist zwar seit 2006 nicht mehr aktualisiert, aber seither hat sich an BibTex (glaube ich) auch nichts Wesentliches getan.

Zum Download geht’s übrigens hier > bibtexParse > bibtexParse-2.2 > bibtexParse2.2.zip

19. Januar 2010

How to use TableModels and ListModel with NetBeans GUI Builder

Abgelegt unter: NetBeans FAQ — frickelblog @ 23:49
Tags: , ,

A default JTable or JList comes with it’s own pre initalized model. Okay – but: how can we modify this model? Which type of model is usually pre initialized?
In the following I’ll just list some of the may possible ways to work with tables and lists and the NetBeans Gui Builder:

1. Create your own Component

After adding the component to the form, go to the “Properties” window/tab  and open the “Code” view.
There you can use the “Custom Creation Code” in order to create the JList (for example) the way you want: new JList(new MyDefaultModel()));

2. Set Model manually

If you don’t like to modify the auto created code, you can just set the desired model after letting NetBeans create the List/Table.

Almost same as above, you can either add a custom Post-Creation or Post-Init Code. Of course you could also just modify the constructor and add your code after the call to initialize().

3. Use NetBeans to manage it all

Add the table/list to the form, then add a DefaultTableModel/DefaultListModel into the form as well. (Right click in the form, add from palette, beans, choose bean -
enter the full package path to the DefaultTable/ListModel and finished). In the inspector view, you should now see the default table model in
“Other components”.

Okay, now attach the model to the table:

Select the JTable/JList – and then you should see an entry “model” in the properties view. Click on the according button , use “Value from existing component”, check “Get Value From:”, check “Property” and select the model you introduced in the above step. – doneAn that’s it. No hand coding needed. If you need this more often you might be quite borded by always entering the full package path. In that case, you can just use the PaletteManager to add all the Default* classes into a new category.

4. Cast …

Another possibility is to just get the model after initialization by using getModel(). But well you end up with a regular ListModel which is just an interface and dows not provide any modification. If you rely on what happened before in your code, you could just cast the returned Model into the according DefaultTableModel/DefaultListModel.

4. Januar 2010

java.sql.SQLException: No suitable driver found for ‘jdbc:derby:…

Abgelegt unter: Java — frickelblog @ 13:52
Tags: , ,

Kleine Gemeinheit im “Using dblook” guide (Übersichtslink):

dblook -verbose -d ‘jdbc:derby:pathToDB\DBName’

– Zeitmarke: 2010-01-04 12:27:34.578
– Quellendatenbank: pathToDB\DBName
– Verbindungs-URL: ‘jdbc:derby:pathToDB\DBName
– appendLogs: false

java.sql.SQLException: No suitable driver found for ‘jdbc:derby:pathToDB\DBName
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at org.apache.derby.tools.dblook.go(Unknown Source)
at org.apache.derby.tools.dblook.(Unknown Source)
at org.apache.derby.tools.dblook.main(Unknown Source)
– **–> DEBUG: No suitable driver found for ‘jdbc:derby:pathToDB\DBName

(Fast) Derselbe Aufruf geht via ij und NetBeans …

Lösung: dblook -d jdbc:derby:pathToDB\DBName
Unterschied: einfach ohne die Hochkommata, auch wenn es im Guide immer wieder mal mit Gänsefüßchen steht.

1. Januar 2010

Autostitch: Format der pano.txt

Abgelegt unter: Sonstiges — frickelblog @ 22:13
Tags: , ,

Gerade Autostitch ausprobiert. Und siehe da: die Panos sind besser als die von meiner alten Canon Stitch-Software.

Aber: Der Ram-Verbrauch von autostitch ist brachial. Ich wollte 5 Fotos à 4592*3056 Pixel zusammenstitchen. Natürlich sollte das Ausgabefoto auch ca 3000Pixel hoch sein. Nur reichten dazu die mir zur Verfügung stehenden 2GB leider nicht aus(?!). 2500px Höhe gingen dann gerade noch.

Da autostitch ja netterweise eine pano.txt anlegt, in der die Transformationsdaten stehen, ist die Versuchung gerade groß, das selbst auszuprobieren. – Wenn mal Zeit ist vielleicht …

Dokumentation der pano.txt:

The format of pano.txt is:

filename
width height
T (3 x 3)
R (3 x 3)
f

so that the projection matrix for each image (original size) is:

P = T * K(f) * R

where K(f) = [ f 0 0; 0 f 0; 0 0 1]

The homography between a pair of images is

s * [r_2, c_2, 1] = P_2 * inv(P_1) * [r_1, c_1, 1]

where r is the row coordinate and c is the column.

The demo version renders panoramas in spherical coordinates theta VS
phi (longitude/latitude). You can get the theta/phi ranges from
Edit->Options after stitching. The relationships between theta/phi and
image coordinates are:

s * [r, c, 1] = P * X

where

X = [ -sin(phi); cos(phi)sin(theta); cos(phi)cos(theta) ]

31. Dezember 2009

Heise Security UpdateCheck

Abgelegt unter: Sonstiges — frickelblog @ 14:15
Tags:

Endlich mal den UpdateCheck von Heise ausprobiert:

Der Update-Check auf heise online entdeckt Programme mit bekannten Sicherheitslücken und hilft dabei, diese schnell auf den aktuellen Stand zu bringen. Der Test deckt die wichtigsten Programme ab und dauert typischerweise nur ein bis zwei Minuten. (Quelle)

Und siehe da, nach 3min 34sec sogar 2 veraltete Versionen gefunden. Durchaus empfehlenswert.

Escape analysis, Lock Coarsening und Biased locking

Abgelegt unter: Java — frickelblog @ 13:53
Tags: ,

Die Ausgabe 179 des “The Java Specialists’ Newsletter” stellt ein paar interessante – wenn auch noch experimentelle – Features der Server-VM vor:

Escape analysis: Damit kann die JVM prüfen, ob ein Objekt einen bestimmten Scope nicht verlässt (z.B. nur in einer Methode verwendet wird) und dieses Objekt dann direkt auf dem Stack anlegen.

Lock Coarsening: Fordert ein Thread aufeinanderfolgend mehrere Locks auf ein Objekt an und gibt sie dann wieder frei (wie z.B. bei der Verwendung von Vector), kann die JVM diese wiederholten, teuren Anfragen zu einem lock/release zusammenfassen,

Biased locking: Wird ein Objekt von nur einem Thread ge’lock’ed, kann auf die Sperre ebenso verzichtet werden.

Im The Java Specialists’ Newsletter werden einige eindrucksvolle MicroBenchmarks gezeigt, die einiges an Performance bringen können. Aber: es sind nur MicroBenchmarks, die den Effekt sehr gut zeigen. In komplexen Applikationen kann der Benefit natürlich deutlich schlechter ausfallen. Soweit ich das aus anderen Seiten gelesen habe, sind die Optionen derzeit noch als experimentell zu betrachten – aber sie sind schon ein schöner Vorgeschmack.

Ein sehr schönes Statement im Zusammenhang mit Performance Tuning, das den Nagel auf den Kopf trifft: “Assumption is the mother of all f* ups”. Der Spruch drückt sehr schön das aus, was ich bei Performance-Optimierungen immer wieder sage: Erst Messen, dann Tunen. Und niemals Tunen ohne zu Messen. Andernfalls kann man schnell mal Stunden damit zubringen, ein Programmstück auf 5% Ausführungszeit zu drücken … das aber in der Gesamtausführung nahezu keine Zeit verbraucht – womit die Verbesserung quasi nicht existent ist. Oder schlimmer: man denkt, ein Programmteil wäre langsam, optimiert aber erfolglos an der Ursache vorbei.

Relevante Links:

http://profiler.netbeans.org/

21. Dezember 2009

Avoid too much sorting

Abgelegt unter: Java is (not that) slow — frickelblog @ 21:59
Tags: , ,

“Java is slow” is the sentence that I heard very often when I began studying computer science – and I forunately never really believed it. But why the predjudice? Well Java CAN be slow if it’s just handeled wrong. Often it’s just convenience of just the missing knowledge of implemntations that makes code slow, so I’ll try to post once in a while whenever I come across such code parts in my hobby programming or at my programmings at work.

So my first issue is about sorting and autoboxing: About last week we profiled some code that felt just sloooow. It turned out that we lost most of the time within a certain loop that was executed very often. The critical part of the code was (stripped from all other stuff) like this :

ArrayList<Double> list = new ArrayList<Double>(20); // keep 20 smallest calculated values
while (condition) {
  double value = calculate(args);
  if (list.size < 20 || value < list.get(19)){
    list.add(value);
    Collections.sort(list)
  }
  // strip elements if size is > 20
}

So what’s the issue here?

  1. condition holds true for a LOT of iterations (well, can’t change this)
  2. the list is small (just 20) BUT it is to be sorted completely for each insert
  3. could autoboxing be an issue here?

Okay, what did we change?

We changed the ArrayList to a SortedDoubleArray (an implementation that I coded some time ago) that inserts the value already in the correct place using Arrays#binaraySearch() and System.arrayCopy(). As I wasn’t quite sure whether or not autoboxing could be an issue here, I created a copy of the class that operates on Doubles instead of the double primitives.

The Test

In order to compare the 3 methods (using Collections.sort(), and the SortedArrays using double and Double), I inserted 1,000,000 random double values into the structures and measured the times. The results are:

  • Collection.sort(): 2907 ms (=100%)
  • SortedDoubleArray (with Double-autoboxed values):  93 ms (~3%)
  • SortedDoubleArray (with double primitives):  94 ms (~3%)

Conclusion

  • Using Collections.sort() is convenient and in most cases absolutely okay! But if you use it in critical locations within the code (for example in loops that are executed very often), you might want to check if there isn’t a better solution.
  • Autoboxing does not hurt in our case

But never forget: Profile first, then tune. Otherwise you might tune code that has almost no impact to the overall execution time (for example, if the for-loop above is just executed 10 times).  And just change one issue after the other and perform measurements between each step so that you can identify the changes with the most impact.
If you have no profiler at hand, you might want to try the NetBeans profier.

value

19. Dezember 2009

How to load images in Java

Abgelegt unter: NetBeans FAQ — frickelblog @ 21:30
Tags: , , ,

Every once ina  while there is a question on the NetBeans mailinglist about how to load an image (or other ressource, like a text file) relative to the executing JAR.

The Java Tutorial gives the answer in the chapter “How to use Icons“:

java.net.URL imgURL = getClass().getResource("./inSamePackage.png");
java.net.URL imgURL = getClass().getResource("../inParentPackage.png");

An alternative is to put all images into a separate resource-JAR so that the images can be changed without needing to repack the executable jar – this is covered in the chapter “Loading Images Using getResource“. Also very important: The chapter “Improving Perceived Performance When Loading Image Icons” which demonstrates the use of asynchronous loading using SwingWorkers (Using SwingWorkers is a very convenient way of using multithreading).

25. November 2009

How to pack multiple JARs into one using ANT (and NetBeans)

Abgelegt unter: Java, NetBeans — frickelblog @ 22:29
Tags: , , ,

Eines der Features, die ich bei NetBeans eine ganze Zeit lang nicht realisiert hatte war die Tatsache, dass NetBeans beim Compilieren automatisch ein ausführbares JAR erstellt, und JAR nebst Libraries in das “dist”-Verzeichnis im Projektordner kopiert. Das heißt das sieht dann so aus:

Coole Sache eigentlich. Nur – um die Applikation einfach so online zu stellen oder jemandem aufs Auge zu drücken (oder in den Java Store hochzuladen), wäre es doch fein, wenn man nur noch ein einziges JAR hätte und nicht noch zusätzlich die ganzen Libs aus “/dist/libs/” mitschicken muss (und das können schon einige sein – in meinem Mini-Projekt zB schon 19).

Viele Leute ziehen ein Jar zB einfach auf den Desktop um es direkt dort per Doppelklick zu starten. Das geht in dem Fall nicht mehr, da ja der libs-Ordner auch auf dem Desktop liegen müsste. Klar, eine Möglichkeit wäre, die Applikation woanders hin kopieren und eine Verknüpfung auf den Desktop legen – aber wir wollen dem User ja entgegenkommen.

Also:  ein einziges JAR muss her. Im Sun Developer Network (SDN) findet sich dazu auch die passende Anleitung im Artikel: “Use NetBeans IDE 6.7 to Combine JAR Files Into a Single JAR File“. Dort wird schön erklärt, wie man die build.xml ändern muss um genau das zu erreichen.

In diesem Sinne: Viel Erfolg beim ausprobieren.

Nächste Seite »

Bloggen Sie auf WordPress.com.