preload
Dez 11
Override equals

Although some people think it might be easy to override the equals method of a class, you can do it wrong in many cases and this can cause problems.

The easiest case is not to override the equals method, then each class is equals only to itself and equals from object is used. Do this only in following cases:

  • When each instance is inherently unique. For example classes as Thread. These represent active entites rather than values. So for value objects this is no applicable.
  • You don’t need a “logical equality” test. For example the java.util.Random where it does not make sense to check if two random numbers are equal.
  • The superclass equals is fully appropriate. E.g. Set -> AbstractSet, List -> AbstractList
  • The class or the package is private and it is assured that it will not been invoced

When to override equals method?

When the logical equality differs from object identity. This is the case for value classes. This class represents a value such as Integer or Date. If these objects will be compared you want to know if the values are the same and not if the objects are the same.

The Java6 specification says about the contract which must be assured when overriding equals:

• Reflexive:Foranynon-nullreferencevaluex,x.equals(x)mustreturntrue.
• Symmetric:Foranynon-nullreferencevaluesxandy,x.equals(y)mustre- turn true if and only if y.equals(x) returns true.
• Transitive:Foranynon-nullreferencevaluesx,y,z,ifx.equals(y)returns true and y.equals(z) returns true, then x.equals(z) must return true.
• Consistent: For any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, pro- vided no information used in equals comparisons on the objects is modified.
• For any non-null reference value x, x.equals(null) must return false.

How should equals be overridden?

This list was taken from Effective Java 2nd Edition.

  • Use the == operator to check if the argument is a reference to this object.
  • Use the instanceof operator to check if the argument has the correct type.
  • Cast the argument to the correct type.
  • For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object.
  • When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?
Override hashCode

Always override hashCode when you override equals.

Here is the contract from the Java specification:

Here is the contract, copied from the Object specification [JavaSE6]:
• Whenever it is invoked on the same object more than once during an execu- tion of an application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execu- tion of an application to another execution of the same application.
• If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
• It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

Furthermore two equal objects must have the same hash code.

How to create a good has method?

Here are some tips taken from Effective Java book:

  • Store some constant nonzero value, say 17, in an int variable called result.
  • For each significant field f in your object (each field taken into account by the equals method, that is), do the following:
    • Compute an int has code c for the field:
      • If the field is a boolean, compute (f ? 1 : 0)
      • if the field is a byte, char, short, or int, computer (int) f.
      • If the field is a long, computer (int) (f^>>>32)).
      • If the field is a float, computer Float.floatToIntBits(f).
      • If the field is a double, compute Double.doubleToLongBits(f), and then hash the resulting long as in step for long.
      • If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison is required, compute a “canonical representation” for this field and invoke hasCode on the canonical representation. If the value of the field is null, return 0 or some other constant.
      • If the field is an array, treat it as if each element were a separate field. That is, compute a hash code for each significant element by applying these rules recursively, and combine these values per step 2 for byte,short etc. If every element in an array field is significant, you can use one of the Arrays.hasCode methods added in release 1.5.
    • Combine the has code c computed in step 2 into result as follows:
      result = 31 * result + c;
  • Return result.
  • When you are finished writing the hashCode method, ask yourself whether equal instances have equal hash codes. Write unit tests to verify your intuition! If equal instances have unequal hash codes, figure out why and fix the problem.

Override toString

If you do not override toString method and print an object you usally see something like this PhoneNumber@434b65. Ok, it is clear that this is a phone number, but wouldn’t it be better to have a representation like “(0221) 77744499″?

So when overriding the toString method it should return all of the interesting information contained in the object. If you have large objects or objects with a not conductive state you can return something like “Yellow pages (2355333 listings)”.

Provide your toString method with good documentation and describe your format. Here is an example taken from Effective Java 2nd Edition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/** 
* Returns the string representation of this phone number. 
* The string consists of fourteen characters whose format 
* is "(XXX) YYY-ZZZZ", where XXX is the area code, YYY is 
* the prefix, and ZZZZ is the line number. (Each of the 
* capital letters represents a single decimal digit.) 
* 
* If any of the three parts of this phone number is too small 
* to fill up its field, the field is padded with leading zeros. 
* For example, if the value of the line number is 123, the last 
* four characters of the string representation will be "0123". 
* 
* Note that there is a single space separating the closing 
* parenthesis after the area code from the first digit of the 
* prefix. 
*/
@Override public String toString() { 
    return String.format("(%03d) %03d-%04d", areaCode, prefix, lineNumber);
}

If you want not a specific format make something like this:

1
2
3
4
5
6
/**
* Returns a brief description of this potion. The exact details 
* of the representation are unspecified and subject to change, 
* but the following may be regarded as typical:
* "[Potion #9: type=love, smell=turpentine, look=india ink]" 
@Override public String toString() { ... }
Tagged with:
Okt 26

I recently read in a chapter of Rod Johnsons Book “expert one-to-one, J2EE Design and Development” an interesting sentence:

A professional programmer or architect cares more about learning and discovering the best solution than the buzz of finding their own solution to a particular problem.

This is so true. Don’t waste (project) time with finding a very own solution and reinventing the wheel. Find solutions that fit your needs, learn how they solved the problem. Of course they must fit to your problem with a coerage of lets say >90%. But these solutions are tested.

Tagged with:
Mrz 02

Due to the fact I got in touch with maven2 and I think that maven2 is very helpful will give a short introduction. Bigger projects normally have a more complex configuration but I will start from the scratch.

Maven will create a kind of project sceleton with the following command

1
mvn archetype:create -DgroupId=info.sobek.testapp -DartifactId=testapp

If you work with e.g. eclipse, you can create the project files for eclipse:

1
mvn eclipse:eclipse

Now you can import it into eclipse with “import into existing workspace” option of eclipse.

Maven will normally copy the created so called “artifacts” into your local maven repository. Normally located under your home dir and then .m2

When you program depends on several jars and these dependencies are defined in the pom.xml, then maven will copy the jars in their specific version into the local maven repository. This is very helpful because you can simply build your project with another newer or older version of your dependent jar-file.

How to create multi-module projects will be explained in another episode.

Tagged with:
Dez 18

You would like to know the spellout word from an integer? Use the ICU library from IBM.

1
2
3
4
import com.ibm.icu.text.RuleBasedNumberFormat;
// ...
int num = 100198
System.out.println(new RuleBasedNumberFormat(Locale.US, RuleBasedNumberFormat.SPELLOUT).format(number));

The result is: one hundred thousand, one hundred and ninety-eight
You can get the spellout of the number in other languages. Check Locale.GERMANY instead of Locale.US and you have: hunderttausendhundertachtundneunzig

Tagged with:
Dez 17

I just stumbled upon an article about the java.awt.robot from java while reading java stuff. When you would like to fill textboxes or to click buttons etc. on an swing or awt window automatically you can use the java.awt.robot class.

Check this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 
package desktopapplication1;
 
import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.Point;
import java.awt.event.InputEvent;
import org.jdesktop.application.FrameView;
 
public class Robot implements Runnable {
 
    private FrameView frameview;
 
    public Robot(FrameView frameview) {
        this.frameview = frameview;
    }
 
    public void run() {
        try {
            initRobot();
        } catch (AWTException ex) {
            Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
        private void initRobot() throws AWTException {
        // create a robot to feed in GUI events
 
        java.awt.Robot rob = new java.awt.Robot();
 
        // enter some keystrokes
 
        int keyinput[] = {
            KeyEvent.VK_T,
            KeyEvent.VK_E,
            KeyEvent.VK_S,
            KeyEvent.VK_T,
            KeyEvent.VK_I,
            KeyEvent.VK_N,
            KeyEvent.VK_G
        };
        rob.delay(1000);
        rob.keyPress(KeyEvent.VK_SHIFT);
 
        ((DesktopApplication1View)this.frameview).getjTextField1().requestFocus();
        for (int i = 0; i < keyinput.length; i++) {
            rob.keyPress(keyinput[i]);
            rob.delay(1000);
        }
        rob.keyRelease(KeyEvent.VK_SHIFT);
        rob.keyPress(KeyEvent.VK_ENTER);
 
        // move cursor to exit button
 
        Point p = ((DesktopApplication1View)this.frameview).getjButton1().getLocationOnScreen();
        rob.mouseMove(p.x + 5, p.y + 5);
        rob.delay(2000);
 
        // press and release left mouse button
 
        rob.mousePress(InputEvent.BUTTON1_MASK);
        rob.delay(2000);
        rob.mouseRelease(InputEvent.BUTTON1_MASK);
 
    }
 
}

I started the class in a separate thread, the example from sun, where I took most parts of the code uses ActionListener to update the textfield.

Now you have to start the thread with:

1
2
       Thread t = new Thread(new desktopapplication1.Robot(this));
       t.start();

Check the example from sun – http://java.sun.com/developer/TechTips/2000/tt0711.html

Tagged with:
Dez 14

To send simple mails im Java, e.g. without header modifications or attachment you can use apache commons library.

Download it at http://commons.apache.org/ and add the jar to your project.

1
2
3
4
5
6
7
8
9
SimpleEmail email = new SimpleEmail();
email.setHostName("host.test.com");
email.setFrom("from@test.com", "testfromname");
email.addTo("to@test.com", "testtoname");
email.addBcc("bcc@test.com", "testbccname");
email.setSubject("testsubject");
email.setMsg("testmessage");
email.setAuthentication("username", "pass");
email.send();

Check simple email-class documentation for further configuration as smtp-port etc.

Tagged with:
Dez 10

To create the stub classes in c# you have to add a web reference.

  • Create a new Application, e.g. Console Projekt or Window Application Projekt
  • Right click on References
  • Left click on Add Service Reference
  • Left click at the bottom on the Add Service Reference-Window on Advanced Add Service Reference
  • Left click at the bottom on the Sevice Reference Settings-Window on Add Web Reference
  • Enter the Web Service URL in the URL-Textfield and press go
  • Optional choose another Web Service Namespace
  • Click Add Reference

Et Voilà. Extremly simple.

Tagged with:
Dez 09

Normally you can create stub classes from a wsdl-file via console by calling wsdl2java. To generate stub classes from wsdl with netbeans you have to add to the build.xml file the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<path id="axis.classpath">
   <fileset dir="/usr/local/axis/lib/">
      <include name="**/*.jar" />
    </fileset>
</path>
 
<taskdef resource="axis-tasks.properties" classpathref="axis.classpath" />
 
<target name="Generate From WSDL">
    <axis-wsdl2java
    output="src/"
    testcase="false"
    verbose="true"
    serverside="false"
    url="http://url.to-webservice.com/?wsdl">
    <mapping namespace="http://axis.apache.org/ns/interop"
    package="wsdltester" />
    <mapping namespace="http://www.namespace.de/types/"
    package="wsdltester.stubs" />
    <mapping namespace="http://www.namespace.de/services/"
    package="wsdltester.service" />
 
    </axis-wsdl2java>
</target>

Note that you have to modify several settings like the namespaces and the url to the web service on line 15! Do not just copy the code.

Tagged with:
Dez 01

Imagine you have java code like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
   if (o.isShipped) //order is shipped --> archive
                {
                    //archived 21 days after delivery
                    Calendar cal = new GregorianCalendar();
                    cal.add(Calendar.DAY_OF_MONTH,DAYS_TO_ARCHIVE_AFTER_SHIPPING);
                    try {
                       ...
                        }
                    } catch (Exception ex) {
                        ...
                    }
                } else if (o.isCancelled == true || o.isClosed == true) {
                    //cancelled more than 7 days ago
                    ...
                                } else {
                                   ...
                                }
                            }
                        }
                    } catch (Exception ex) {
                        ...
                    }
                    try {
                        if (o.isClosedAt.getTimeInMillis() <= cal.getTimeInMillis()) {
 
                           ...
 
                                } else {
                                    ...
                                }
                            }
                        }
                    } catch (Exception ex) {
                        ...
                    }
                } else if (o.isReadyForShipping && o.isDispatched) {
                 ...
                }

Isn’t it extreme hard to read and to understand? Martin Fowlers Book “Refactoring” shows how to handle that. Replace all these nested if…else with if-guards. It could lool like this:

1
2
3
4
if (order.isShipped && !isCancelled && !isClosed) archiveOrder();
if (!order.isShipped && order.isCancelled && order.isCancelledAt.getTimeInMillis() <= cal.getTimeInMillis()) moveReservationOnCancel();
if (!order.isShipped && order.isClosed && order.isClosedAt.getTimeInMillis() <= cal.getTimeInMillis()) moveReservationOnClosing(); 
...

What did we do here? We renamed the order object o into order, and put the actions into separate methods. To improve readability a bit more we can create a method for the boolean checks. See the next example:

1
2
3
4
5
6
7
8
9
10
11
12
13
if (isOrderShipped(order)) archiveOrder();
if (isOrderCanceled(order)) moveReservationOnCancel();
if (isOrderClosed(order)) moveReservationOnClosing(); 
...
private boolean isOrderShipped(OrderDetails order) {
        return order.isShipped && !order.isCancelled && !order.isClosed;
}
private boolean isOrderCancelled(OrderDetails order) {
        return !order.isShipped && order.isCancelled && order.isCancelledAt.getTimeInMillis() <= cal.getTimeInMillis();
}
private boolean isOrderClosed(OrderDetails order) {
        return !order.isShipped && order.isClosed && order.isClosedAt.getTimeInMillis() <= cal.getTimeInMillis();
}

Pretty readable isn’t it? You just need a few seconds to understand what is going on here. You have the main flow right in sight. When it is needed to go deeper into the code you can pick any method you like to inspect.

Tagged with:
Nov 27
I am glad that I could gain experience in a lot of CMS-Systems, Open Source CMS like Typo3 and Joomla as well as Licence CMS for example InterRed. Now I will come to my favorite Open-Source CMS, Typo3!
What if you like to create a “previous” – “next” navigation with typo3? Have a look at the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
lib.nav-referenzen = COA
lib.nav-referenzen {
  10 = HMENU
  10 {
   entryLevel = 3
   special = browse
   special  {
    items = prev
    items.prevnextToSection =  1
   }
   1 = TMENU
   1 {
    NO  {
    doNotLinkIt = 1
    stdWrap.cObject =  COA
    stdWrap.cObject {
     10 =  TEXT
     10 {
      field =  title
      typolink {
       parameter.field = uid
       returnLast =  url
      }
    wrap = <a title="{field:title}" href="|"></a>&amp;nbsp;&amp;nbsp;
    insertData =  1
    }
  }
 }
}
}
20 &lt; .10
20 {
special.items =  next
1.NO.stdWrap.cObject.10.wrap = &amp;nbsp;&amp;nbsp;<a title="{field:title}" href="|">next &amp;raquo;</a>
}
}
Now put this code into your template:

with automaketemplate e.g: subparts.bottom < lib.nav-referenzen

with templavoila e.g.: lib.prevnextnavigation < lib.nav-referenzen

subparts.bottom and lib.prevnextnavigation are only sample object names. Replace them with your own subpartname or templavoila lib name.

Tagged with: