Thursday, July 11, 2013

log4j hibernate show_sql to log file

Hibernate writes the SQL commands, which are logged via

<property name="hibernate.show_sql">true</property>
 
by default to console. In a tomcat envirement the default ist the catalina.out log file. To write your plain SQL logs to a seperate log file you have to configure a seperate logger for the SQL statements. You can do this by adding the following Logger in log4j.xml:
  <logger name="org.hibernate.SQL">
    <!-- level info logs -->
    <level  value="DEBUG" />
    <appender-ref ref="sqlAppender"/>    
  </logger>
 
And don’t forget to create a appender for it:

  <appender name="sqlAppender" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="datePattern" value="'.'yyyy-MM-dd" />
    <param name="file" value="${log.path}/myproject-sql.log" />
    <param name="Append" value="true" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern"
             value="%d{ISO8601} %-5p [%t] %c: %m%n" />
    </layout>
  </appender>

Saturday, June 22, 2013

Java Image Scaling awt.Graphics2D vs. Scalr

The Target was very simple I had the last days. You will get a big image and have to scale it low for the web.
At the beginning I googled a little bit and found out the imagemagic is the best solution for quality scaling. I think it is, because it has a very big libary of commands and supportet image formats.Because I like to scale the images during a gwt server call I was not so happy to install a complete software on our hosting machines. So I checked other solution to Scale this image to a [x<=200 and y<=200] format. The first approach was using java awt image scaling stuff:
Unit Test Code


BufferedImage bsrc = ImageIO.read(new File(src));
for (String name : ImageIO.getWriterFormatNames()) {
System.out.println(name);
}
System.out.println("original size_" + bsrc.getWidth() + " height:" + bsrc.getHeight());
double scaleWith = (double) width / bsrc.getWidth();
double scaleheigth = (double) height / bsrc.getHeight();
double scalefactor = scaleheigth > scaleWith ? scaleWith : scaleheigth;
double finalWith = bsrc.getWidth() * scalefactor;
double finalHeight = bsrc.getHeight() * scalefactor;
System.out.println("Dest img size:" + finalWith + " height:" + finalHeight);
BufferedImage bdest = new BufferedImage((int) finalWith, (int) finalHeight, bsrc.getType());
Graphics2D g = bdest.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform at = AffineTransform.getScaleInstance(scalefactor, scalefactor);
g.drawRenderedImage(bsrc, at);
ImageIO.write(bdest, "JPG", new File(dest));

This was the result
the-hobbit-an-unexpected-journey-dvd-cover-68-out
For a Programmer it was ok. But not for an Artist, or people which don’t have a red-green handicap :-)
So I tried out imgscalr
here my Unit Test code:
public static void scaleNEW(final String src, final int width, final int height, final String dest) throws IOException {
BufferedImage bsrc = ImageIO.read(new File(src));
String extension = src.substring(src.lastIndexOf(".") + 1, src.length());
System.out.println("extension is:" + extension);
for (String name : ImageIO.getWriterFormatNames()) {
System.out.println(name);
}
System.out.println("original size_" + bsrc.getWidth() + " height:" + bsrc.getHeight());
double scaleWith = (double) width / bsrc.getWidth();
double scaleheigth = (double) height / bsrc.getHeight();
double scalefactor = scaleheigth > scaleWith ? scaleWith : scaleheigth;
double finalWith = bsrc.getWidth() * scalefactor;
double finalHeight = bsrc.getHeight() * scalefactor;
BufferedImage thumbnail = Scalr.resize(bsrc, (int) finalWith, (int) finalHeight, Scalr.OP_ANTIALIAS);
ImageIO.write(thumbnail, extension, new File(dest));
}

I was very supprised, that the api was so easy to use…. Here you see the result:
the-hobbit-an-unexpected-journey-dvd-cover-68-out2

Sunday, February 10, 2013

Abstraction ui elements with labels

You always have the issue, that you need next to ui elements a label to name the element.
There are many options to solve the problem. First the easy way:
ListBox box=new ListBox();
Label lbl=new Label("Countrys");

this.add(box);
this.add(lbl);
This code a lot of programmers have to do for hundrets of input fields, comboboxes and so on.I would recomment, to build up for your most needed UI Elements a class, which also contains the label and the data containing element.
public class MisTextAreaWithLabel extends MisVerticalPanel {
 private TextArea area;
 private Label lbl;

 public MisTextAreaWithLabel(String label) {
  this.lbl = new Label(label);
  this.area = new TextArea();

  this.add(area);
  this.add(lbl);
 }

 public void setValue(String newValue) {
  this.area.setValue(newValue);
 }

 public String getValue() {
  return this.area.getValue();
 }
}
This code is easyly useable with:
MisTextAreaWithLabel  area=new MisTextAreaWithLabel("firstname");
this.add(area);
By creating a new Panel where the element and it’s description is on, you can save a lot of code and you will be able to change the behavior of all your UI Elements easyly.

hibernate configure transaction Isolation Level

In the hibernate config file you can configure the default jdbc-transaction level. Hibernate uses the codes of the java.sql.Connection  class, which are listed above.
  •   public static final int TRANSACTION_NONE = 0;
  •   public static final int TRANSACTION_READ_UNCOMMITTED = 1;
  •   public static final int TRANSACTION_READ_COMMITTED = 2;
  •   public static final int TRANSACTION_REPEATABLE_READ = 4;
  •   public static final int TRANSACTION_SERIALIZABLE = 8;
To use Repeatable Read transactions you just have to type the number 4 in your isolation property.
<property name=”hibernate.connection.isolation”>4</property>
Here a short list, what each level means:
  • TRANSACTION_READ_UNCOMMITTED -> Allows dirty reads, non-repeatable reads, and phantom reads to occur.
  • TRANSACTION_READ_COMMITTED -> Ensures only committed data can be read.
  • TRANSACTION_REPEATABLE_READ -> Is close to being “serializable,” however, “phantom” reads are possible.
  • TRANSACTION_SERIALIZABLE -> Dirty reads, non-repeatable reads, and phantom reads are prevented. Serializable.
Performance of the software decreased by a higher transaction level. So you should check if you need more stability or performance. Depends always by the software you build up.

Monday, January 28, 2013

Tool of the day: Atlassian Confluence

Since many years I am working now with atlassian confluence as project documentation plattform. I am still suprised, how easy the integration with jira, greenhopper and co. works.4 months ago I introduced confluence in my current company with a lot of non technical employees.It was very cool, to see how easy they got confident in working on a day to day base with confluece.

We are very happy with it and I personally think that everybody should use it: freelancers, startups and big companys!Atlassian has a very nice license model. Until 10 User Accounts you just pay 10$  a moth to use confluence.That is not much money, for such a great documentation plattform. Also that setup with an MySQL and the deployment to a java Tomcat Server is pretty simple. The documentation of confluence is awesome.For me more or less one of the best tools I ever worked with. There is also a free trial version available.

Check the demonstration video to build yourself a picture!


CTRL+Z


java hibernate nullable integer fields


To be able to use a nullable integer field with hibernate code generation hbm2java, you just have to change the type since java 1.5 to the java.lang.Integer class.

Before:
<property name="weightInGramm" type="int"/>


After:
<property name="weightInGramm" type="java.lang.Integer" not-null="false"/>


Sunday, January 27, 2013

Windows


hibernate mapping create a unique constraint


That’s pretty simple in a hibernate mapping file. Also hbm2java generations works out of the box,.

<property name="field_one" type="int" unique-key="UNIQUE_GAME_XX" />
<property name="field_two" type="int" unique-key="UNIQUE_GAME_XX" />

Put the unique-key=”UNIQUE_GAME_XX” to every field or asociation you like to add to your constraint.

JAVA_HOME Classpath

Wenn man Eclipse zum ersten mal auf einer Workstation starten möchte, ist häufig die JAVA_HOME Classpathvariable nicht gesetzt.
Grundsätzlich ist dies kein Problem, kann allerdings eines sein wenn man nur eingeschränkte Rechte auf der Maschine- und keinen Zugriff auf die Systemvariablen hat.
Unter diesen Umständen ist man in der Regel auf das eingreifen des Administrators angewiesen. Mit einem kleinen Trick kann man Eclipse allerdings auch ohne dessen eingreifen zum laufen bekommen.
Und zwar kann man innerhalb einer DOS-Box Systemvariablen beliebig setzen - dies allerdings zeitlich und räumlich beschränkt.
Dieses Problem lässt sich unter Windows sehr einfach- zumindest temporär lösen. Und hier ist eine Beschreibung wie:
1. Die DOS-Konsole starten.
-> Start -> Ausführen -> cmd -> Enter
2. Die JAVA_HOME Variable in der DOS-Box wie gewünscht setzen.
SET JAVA_HOME="c:\Programme\Java\jdk\
3. Aus der DOS-Box Heraus Eclipse starten.
D:\eclipse\eclipse.exe
Zusatzinfos:
Die Variable wird hierbei nur temporär und nur innerhalb der entsprechenden DOS-Box gesetzt.
Nach einem Computerneustart ist JAVA_HOME nicht mehr gesetzt. Die JAVA_HOME ist nicht Windowsweit gesetzt.
by
ToniG

Saturday, January 26, 2013

Java GWT log4j client logging

Right now I googled a little bit to find out how enable log4j logging on client side.
Out there is lib which supports this named log4j-gwt.
In order to use log4j on the client side of a GWT application, you need to:
    1. add log4j-gwt.jar to the classpath right next to log4j.jar. Usually this is done by copying it to war/WEB-INF/lib
    2. add the following line to your module.gwt.xml file:
 
Just use it in your client site code like normal log4j.
private static Logger logger = Logger.getLogger(MyClass.class);

Friday, January 25, 2013

Java: is String null or number

Perhabs this code is helpfully for you. I used it to check if the content of a GWT TextBox contains an integer number. It use regular expressions to check if the content of the String is an integer and not null.
protected boolean isNotNullAndNumber(String value) {
 return (value != null && value.matches("\\d+"));
}

Measurement of code quality

Not far away from truth :-)
Measurement of code quality

Thursday, January 24, 2013

Tool of the day: yEd

yEd is an easy to use UML and Graph editor. I used it to create a uml sequence diagramm, which was pretty simple. And the best of all yEd is free !


yEd introduction


You can download it here:
http://www.yworks.com/

SQL alter table column commands

Today I had to change a little bit some column of some database tables. I don't like in future to search the SQL-Commands again, so I like to add them to
my blog and hope, that they will also helpfully for you.
Drop Not Null Constraint from column :
ALTER TABLE TEST_ABC MODIFY ID_CUSTOMER bigint(20) NULL
Remove column
ALTER TABLE SALESORDER DROP columname1
Add column
ALTER TABLE CUSTOMER_ADRESS ADD testcolumnName2 VARCHAR(255) NULL
Rename column
ALTER TABLE WEB_SITE change `headerURL`  `headerURLorData` text
All commands are tested on MySQL 5.5.28.

Java GWT Custom Popup mit Panel

Anbei mal ein kleines abgewandeltes code-snipped von mir um einfach Popups mit Java GWT zu erzeugen und für eigene Panels zu reusen
public class PopupManager {

 public static void showDialogWithPanel(Panel panel, String headline) {
  DialogBox box = createNewDialogbox(headline);
  box.setWidget(panel);
  box.show();
 }

 private static DialogBox createNewDialogbox(String headline) {
  DialogBox dialogBox = new DialogBox();
  dialogBox.setModal(true);
  dialogBox.center();
  dialogBox.setText(headline);
  return dialogBox;
 }
}

Nun kann man das Ganze einfach mit folgendem Befehl ausführen um seinen Selfmade Panel als Popup zu zeigen.:
PopupManager.showDialogWithPanel(new MyPopupPanel(),"Testpopup");

Windows CMD shortcut DOSKEY

Wenn man lange Zeit auf einem Linux System gearbeitet hat, vermisst man beim switch auf Windows zurück die ein oder andere Annehmlichkeit die einem das Leben einfacher
macht, oder man ist einfach nur genervt das einige 0815 Befehle wie (ls -la) unter Windows anders heißen. So ist es mir oft passier, dass ich in die Windows CMD mal ein ll eingegeben habe.
Zudem haben mich bei meinem letzten Arbeitgeber die unzähligen Maven Configurationen Wahnsinnig gemacht. Um die Maven Tasks zu starten musste man nicht selten lange Zeilen in die Console eingeben wie:
mvn -Denv=Integration0A1 clean install
Natürlich kam es dort Aufgrund von Rechtsschreibfehlern immer wieder zu 5-10 Minütigen Suchaktionen. Also habe ich so faul wie ich bin einen Weg gesucht um mir das Leben einfacher zu machen.
Die Lösung war der DOSKEY Befehl von Windows mit dem man einen Shortcut erstellen kann.
Anstatt:
mvn -Denv=Integration0A1 clean install
einzugeben habe ich einfach:
mvnint
in die Console eingetippt.
Wie kam ich dahin?
1. Windows CMD öffnen
2. DOSKEY ll=DIR eingeben
3. ll in der Console eingeben
Da die Shortcuts nach dem Schließen der Console wieder verschwinden hab ich mir auf D:\ ein Batchfile erstellt, welches meine CMD mit meinem meisst benötigten Befehlen initialisiert. Mein Batchfile sieht ca. so aus:

DOSKEY mvnint=mvn -Denv=Integration0A1 clean install
DOKEY ll=DIR
DOKEY rm=DEL
DOSKEY projects=cd D:\data\projects

Eclipse Scrapbook guide

Ein Scrapbook ist eine Datei in der man Javacode testen kann ohne eine Main Methode zu haben und ohne ein seperates Projekt zu erstellen.
Einfaches Beispiel wir arbeiten an einem großen Projekt für einen Kunden und möchten herausfinden was passiert wenn man einen float durch einen float und dann wieder multipliziert. Man hat jetzt einige Optionen:
1. Einen Unit Tests dafür erstellen-> macht nicht wirklich sinn
2. Eine zweite Main Klasse in die Applilkation hinzufügen-> ganz schön fusch
3. Ein seperates Test Projekt erstellen-> ok aber macht arbeit
4. Eine Scrapbook Datei dem Projekt hinzufügen-> Super!

Und jetzt einfach anfangen in der Datei zu programmieren. Wenn der Code abgeschlossen ist kann man ihn starten indem man alles markiert und einen Rechtsklick darauf macht.

Console2

Da ich beruflich sehr oft auf Windows Systemen Software entwickel, welche mehrere Command Shells benötigt. Habe ich mal etwas gegoogled und ein schickes Tool gefunden welches Tab Consoles ermöglicht.
Console2
http://sourceforge.net/projects/console/files/