Archive for January, 2009

Collections in Java (0)

January 30th, 2009 by Frank Niedermann, under Java.

Collections in Java enable grouping of Objects and therefore help to manage data.

collection

Definition:

  • List: Sequence and identification with Int-keys (0, 1, 2, 3, …), duplicate values possible
  • Set: No duplicates allowed
  • Map: Key-Value assignment, duplicate values possible (not for keys)
  • Queue: Ordered data, Insertion/Extraction from Beginning/End

Some useful methods with Lists and Sets:

  • int size()
  • boolean isEmpty()
  • boolean add(Object o)
  • boolean remove(Object o)
  • int indexOf(Object o)
  • int lastIndexOf(Object o)
  • void clear()

Some useful methods with Maps:

  • Object get(Object key)
  • Object put(Object key, Object value)
  • Object remove(Object key)
  • int size()
  • Set keySet() -> Set with all keys (no duplicates)

List example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
list.remove(1);
list.add("four");
list.add(0, "zero");
 
for (int i=0; i<list.size(); i++) {
	System.out.println(list.get(i));
}
 
Iterator<String> listItr = list.iterator();
while (listItr.hasNext()) {
	System.out.println(listItr.next());
}
 
// last element
list.get(list.size()-1);

Set example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(2); // duplicate -> will be ignored
 
Iterator<Integer> setItr = set.iterator();
while (setItr.hasNext()) {
	System.out.println(setItr.next());
}
 
SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("Gamma");
sortedSet.add("Alpha");
sortedSet.add("Beta");
 
Iterator<String> sortedSetItr = sortedSet.iterator();
while (sortedSetItr.hasNext()) {
	System.out.println(sortedSetItr.next());
}

Map 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
HashMap<String, String> map = new HashMap<String, String>();
map.put("stable", "Etch");
map.put("testing", "Lenny");
map.put("unstable", "Sid");
 
for (String key : map.keySet()) {
	System.out.println(key + " is " + map.get(key));
}
 
Iterator<String> mapItr = map.keySet().iterator();
while (mapItr.hasNext()) {
	String key = (String) mapItr.next();
	System.out.println(key + " is " + (String)map.get(key));
}
 
// Sorted Map
TreeMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("8.04", "Hardy Heron");
sortedMap.put("7.10", "Gutsy Gibbon");
sortedMap.put("9.04", "Jaunty Jackalope");
sortedMap.put("8.10", "Intrepid Ibex");
 
Iterator<String> sortedMapItr = sortedMap.keySet().iterator();
while (sortedMapItr.hasNext()) {
	String key = (String) sortedMapItr.next();
	System.out.println(key + " xis " + (String)sortedMap.get(key));
}

Tagged with , , , , .

This simple example shows how to read XML-files in Java with JDOM. Useful with configuration files for example.

There are many ways to use XML with Java, some of them are:

  • SAX (Simple API for XML): event-driven parser
  • DOM (Document Object Model): parser reads the entire document and creates a tree of the nodes
  • JDOM (Java Document Object Model): special development for Java using Collection API

To use JDOM the jdom.jar has to be included in the classpath of the application.

First, the XML-file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8" ?>
<library>
  <book price="5.0">
  	<author>James Dean</author>
  	<type>Softcover</type>
  </book>
  <book price="8.0">
  	<author>Billy the Kid</author>
  	<type>Hardcover</type>
  </book>
  <book price="3.0">
  	<author>Tom Jones</author>
  	<type>Softcover</type>
  </book>
</library>

Second, the Java code to read this XML-file:

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
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
 
public class ReadXml {
 
  public static void main(String[] args) throws Exception {
 
    String filename = "library.xml";
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new File(filename));
 
    // get root element
    Element root = doc.getRootElement();
 
    // get child elements
    List books = root.getChildren("book");
    System.out.println("This library has " + books.size() + " books:");
 
    Iterator i = books.iterator();
    while (i.hasNext()) {
      Element book = (Element) i.next();
      System.out.println(
        book.getChildText("author") + " (" + 
        book.getChildText("type") + ")" + ": " +
        book.getAttributeValue("price") + " €);
    }
  }
}

Tagged with , , , .

Using Transactions in MQL (0)

January 15th, 2009 by Frank Niedermann, under Matrix.

It’s often a good idea to use Transactions in MQL, this is how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// start a transaction
start transaction update;
 
... MQL commands ...
 
// create savepoint
set transaction savepoint saveOne;
 
... MQL commands ...
 
// create savepoint
set transaction savepoint saveTwo;
 
// rollback until savepoint saveOne
abort transaction saveOne;
 
... MQL commands ...
 
// commit the MQL commands
commit transaction;
 
// abort (rollback) the MQL commands
abort transaction;

Tagged with , .

Eclipse looks clumsy and a lot of space is wasted with the default themes in Gnome on Ubuntu:
eclipse-Clumsy

This can be improved with some gtk-theme magic:

gtk-icon-sizes="panel-menu=16,16 : gtk-menu=16,16 : gtk-button=16,16 :
gtk-small-toolbar=16,16 : gtk-large-toolbar=16,16 : gtk-dialog=32,32 : gtk-dnd=32,32"
 
style "compact" {
font_name="Sans 8"
GtkButton::default_border={0,0,0,0}
GtkButton::default_outside_border={0,0,0,0}
GtkButtonBox::child_min_width=0
GtkButtonBox::child_min_heigth=0
GtkButtonBox::child_internal_pad_x=0
GtkButtonBox::child_internal_pad_y=0
GtkMenu::vertical-padding=1
GtkMenuBar::internal_padding=0
GtkMenuItem::horizontal_padding=4
GtkToolbar::internal-padding=0
GtkToolbar::space-size=0
GtkOptionMenu::indicator_size=0
GtkOptionMenu::indicator_spacing=0
GtkPaned::handle_size=4
GtkRange::trough_border=0
GtkRange::stepper_spacing=0
GtkScale::value_spacing=0
GtkScrolledWindow::scrollbar_spacing=0
GtkExpander::expander_size=10
GtkExpander::expander_spacing=0
GtkTreeView::vertical-separator=0
GtkTreeView::horizontal-separator=0
GtkTreeView::expander-size=8
GtkTreeView::fixed-height-mode=TRUE
GtkWidget::focus_padding=0
xthickness=0
ythickness=0
}
class "GtkWidget" style "compact"
 
style "compact2" {
xthickness=1
ythickness=1
}
 
class "GtkButton" style "compact2"
class "GtkToolbar" style "compact2"
class "GtkPaned" style "compact2"

I saved those lines into my eclipse directory as gtkrc-compact. Then I created another file, which is executeable and used to start eclipse:

#!/bin/sh
#GTKRCFILE=Clearlooks
GTK2_RC_FILES=gtkrc-compact ./eclipse

Now it looks much nicer:
eclipse-Thin

Tagged with , , .

This is one way to send a mail in a Java application:

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
  private String mailSmtpServer = new String("mailserver.tld");
  private String mailFrom = new String("from@example.com");
  private String mailTo = new String("to@example.com");
  private String mailSubject = new String("Example Mail");
  private String mailText = new String("This is just an example.");
 
  Properties p = new Properties();
  p.put("mail.smtp.host", this.mailSmtpServer);
  Session s = Session.getDefaultInstance(p);
  while (true) {
    try {
      Message msg = new MimeMessage(s);
      msg.setFrom(new InternetAddress(this.mailFrom));
      msg.setRecipient(Message.RecipientType.TO, new InternetAddress(this.mailTo));
      msg.setRecipient(Message.RecipientType.CC, new InternetAddress(this.mailCc));
      msg.setSubject(this.mailSubject);
      msg.setContent(this.mailText, "text/plain");
      msg.setHeader("APPLICATION", "MccImporter");
      msg.setSentDate(new Date());
      Transport.send(msg);
      break;
    } catch (Exception e) {
      logger.error("Unable to send Mail to " + this.mailTo + " with subject " + this.mailSubject + " using server " + this.mailSmtpServer + ": " + e.getMessage());
      logger.error("New Try in 30 minutes");
      try {
        // wait 30 minutes until next try to send mail
        Thread.sleep(1000 * 60 * 30);
      } catch (InterruptedException el) { }
    }

Java Random (0)

January 8th, 2009 by Frank Niedermann, under Java.

Using Random to generate random int (float, boolean, …) values and random passwords:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Random;
...
Random rand = new Random()
 
// random int between 1 and 6
int dice = rand.nextInt(5)+1
 
// random password generation
String values = "abcdefghijklmnopqrstuvwxyz" ;
values= values + values.toUpperCase() ;
values = values + "1234567890" ;
String password = "";
int j = 0;
while ( j<digits )
{
  password = password + choices.charAt( rand.nextInt( choices.length() ) );
  j = j + 1;
}

Tagged with , , .