Just listen to Alex

August 7, 2011

Java Swing: automatically resize table columns to their contents

Filed under: Uncategorized — Tags: , — bosmeeuw @ 4:45 pm

When using JTables in Swing, you will notice that by default, all columns have the same size. Either the user can resize the columns to better represent the data in the column (which they need to do every time they open the screen), or the programmer can decide to set a specific width on each column. Of course, the programmer might not always know what kind of data will show up in the table, and what width is required for each column.

The easiest solution to this problem, is to automically resize table columns based on the data in the table, like shown in the video below:

The way this works, is that we render the entire table (invisible), and check the maxium required width for each column. If the table is big enough to display all data, we size all columns to display everything. If the table is too small, for instance when one of the cells contains a very long string, we make the biggest column(s) smaller until the data does fit.

The code to execute the resize is very simple:

ColumnsAutoSizer.sizeColumnsToFit(table);

We can also hook up an event listener to automatically resize the columns every time data is added or changed in the table, like this:

table.getModel().addTableModelListener(new TableModelListener() {
	public void tableChanged(TableModelEvent e) {
		ColumnsAutoSizer.sizeColumnsToFit(table);
	}
});

You’ll find the source for ColumnsAutoSizer and the demo app below:

package be.alex.examples;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.FontMetrics;

public class ColumnsAutoSizer {

    public static void sizeColumnsToFit(JTable table) {
        sizeColumnsToFit(table, 5);
    }

    public static void sizeColumnsToFit(JTable table, int columnMargin) {
        JTableHeader tableHeader = table.getTableHeader();

        if(tableHeader == null) {
            // can't auto size a table without a header
            return;
        }

        FontMetrics headerFontMetrics = tableHeader.getFontMetrics(tableHeader.getFont());

        int[] minWidths = new int[table.getColumnCount()];
        int[] maxWidths = new int[table.getColumnCount()];

        for(int columnIndex = 0; columnIndex < table.getColumnCount(); columnIndex++) {
            int headerWidth = headerFontMetrics.stringWidth(table.getColumnName(columnIndex));

            minWidths[columnIndex] = headerWidth + columnMargin;

            int maxWidth = getMaximalRequiredColumnWidth(table, columnIndex, headerWidth);

            maxWidths[columnIndex] = Math.max(maxWidth, minWidths[columnIndex]) + columnMargin;
        }

        adjustMaximumWidths(table, minWidths, maxWidths);

        for(int i = 0; i < minWidths.length; i++) {
            if(minWidths[i] > 0) {
                table.getColumnModel().getColumn(i).setMinWidth(minWidths[i]);
            }

            if(maxWidths[i] > 0) {
                table.getColumnModel().getColumn(i).setMaxWidth(maxWidths[i]);

                table.getColumnModel().getColumn(i).setWidth(maxWidths[i]);
            }
        }
    }

    private static void adjustMaximumWidths(JTable table, int[] minWidths, int[] maxWidths) {
        if(table.getWidth() > 0) {
            // to prevent infinite loops in exceptional situations
            int breaker = 0;

            // keep stealing one pixel of the maximum width of the highest column until we can fit in the width of the table
            while(sum(maxWidths) > table.getWidth() && breaker < 10000) {
                int highestWidthIndex = findLargestIndex(maxWidths);

                maxWidths[highestWidthIndex] -= 1;

                maxWidths[highestWidthIndex] = Math.max(maxWidths[highestWidthIndex], minWidths[highestWidthIndex]);

                breaker++;
            }
        }
    }

    private static int getMaximalRequiredColumnWidth(JTable table, int columnIndex, int headerWidth) {
        int maxWidth = headerWidth;

        TableColumn column = table.getColumnModel().getColumn(columnIndex);

        TableCellRenderer cellRenderer = column.getCellRenderer();

        if(cellRenderer == null) {
            cellRenderer = new DefaultTableCellRenderer();
        }

        for(int row = 0; row < table.getModel().getRowCount(); row++) {
            Component rendererComponent = cellRenderer.getTableCellRendererComponent(table,
                table.getModel().getValueAt(row, columnIndex),
                false,
                false,
                row,
                columnIndex);

            double valueWidth = rendererComponent.getPreferredSize().getWidth();

            maxWidth = (int) Math.max(maxWidth, valueWidth);
        }

        return maxWidth;
    }

    private static int findLargestIndex(int[] widths) {
        int largestIndex = 0;
        int largestValue = 0;

        for(int i = 0; i < widths.length; i++) {
            if(widths[i] > largestValue) {
                largestIndex = i;
                largestValue = widths[i];
            }
        }

        return largestIndex;
    }

    private static int sum(int[] widths) {
        int sum = 0;

        for(int width : widths) {
            sum += width;
        }

        return sum;
    }

}

Demo app:

package be.alex.examples;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ResizeColumnsDemo extends JPanel {
    public ResizeColumnsDemo() {
        super(new FlowLayout());

        String[] columnNames = {"First Name",
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};

        Object[][] data = {
	    {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
	    {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
	    {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
	    {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)},
	    {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)}
        };

        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        // automatically resize the columns whenever the data in the table changes
        table.getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                ColumnsAutoSizer.sizeColumnsToFit(table);
            }
        });

        JButton autoSizeButton = new JButton("Auto-size columns");

        // resize the columns when the user clicks the button
        autoSizeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ColumnsAutoSizer.sizeColumnsToFit(table);
            }
        });


        JButton setLongNameButton = new JButton("Set longer name");

        // set a longer name to test automatic resizing after value changes
        setLongNameButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.getModel().setValueAt("Kathy Kathy Kathy", 0, 0);
            }
        });

        JButton setVeryLongNameButton = new JButton("Set very long name");

        // set a longer name to test automatic resizing after value changes
        setVeryLongNameButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.getModel().setValueAt("Kathy Kathy Kathy Kathy Kathy Kathy Kathy Kathy Kathy Kathy Kathy", 0, 0);
            }
        });

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        //Add the scroll pane to this panel.
        add(scrollPane);

        add(autoSizeButton);

        add(setLongNameButton);

        add(setVeryLongNameButton);
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("SimpleTableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        ResizeColumnsDemo newContentPane = new ResizeColumnsDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.setSize(600, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

July 22, 2010

Hibernate data import, big sessions and slow flushing

Filed under: programming — Tags: , — bosmeeuw @ 8:03 pm

Have you ever done something like this with JPA/Hibernate?

for(Map<String,String> line : someCsvDataSource) {
	em.persist(createSomeDataObjectFromLine(line));
	em.flush();
}

If you’re creating more than a few hundred lines that way, you’ll soon see a drastic slowdown, with Hibernate eventually taking more than a second per line to do its work. The reason for this is that the Hibernate session becomes larger and larger as you persist more objects. This, in turn will cause the em().flush() to become really slow.

The fix for this is clearing your session every once in a while, like this:

int index = 0;

for(Map<String,String> line : someCsvDataSource) {
	em.persist(createSomeDataObjectFromLine(line));
	em.flush();
	
	index++;
	
	if(index % 100 == 0) {
		em.clear();
	}
}

Of course, this will “detach” any persistent objects you might have kept a reference to. Also note you absolutely need to do a manual flush before you clear your persistence context, else your data will be plain lost.

By the way: don’t use FlushMode.AUTO, it’s way too slow for practical use. You’ll be mad at yourself for having relied on it when you need to get rid of it to save your server’s performance.

July 1, 2009

Fake Java properties and how they improve JPA

Filed under: programming — Tags: , — bosmeeuw @ 5:52 pm

It doesn’t look like Java will be getting real property support in our lifetimes. This is too bad, because being able to refer to properties of an object in a type-safe way is really valuable when developing applications with a large domain. Take a gander a this JavaBean:

@Entity
public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Let’s say I’ve developed a 50.000 class, 10 million lines of code application using this JavaBean as my domain model. I’m of course using JPA. My business logic is riddled with heavily complex JPQL statements such as this one:

Person leaderOfTheFreeWorld = em.createQuery(
  "FROM Person p WHERE p.name = :name"
).setParameter("name", "Barack Obama").getSingleResult();

Now the users demand the impossible, and tell me they want to keep the first name and last name of people in seperate fields. After adding a “firstName” field to my JavaBean and maybe migrating the data, I need to change my heavily complex JPQL query to this:

Person leaderOfTheFreeWorld = em.createQuery(
   "FROM Person p WHERE p.name = :name AND p.firstName = :firstName"
).setParameter("name", "Obama").setParameter("firstName", "Barack").getSingleResult();

That’s fine really, but remember I have 50.000 classes with 10 million lines of code, and I need to make sure all queries that use the “name” field are updated. What do I do? A text search for “name”? I’m guessing a lot of hits are coming my way. How do I make sure I’ve covered all references to the name field? The answer is, of course: fake properties!

Let’s change the original JavaBean to this:

public class Person {
    
    private String name;
    public static final String NAME = "name";
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Notice the public static final reference to my field. Now look at this type safe way to refer to my model in JPQL:

em.createQuery(
   "FROM " + Person.class.getName()  + " p WHERE p." + Person.NAME + " = :name"
).setParameter("name", "Barack Obama").getSingleResult();

What does that get you?

  1. Autocompletion: Your IDE autocompletes the “Person.class” and “Person.NAME” parts of the query. No having to look at the model class to remember if the field was called “name” or “birthGivenPersonalDiscriminator”
  2. Navigability: you can jump to the declaration of the Person from within your query
  3. Refactor safety: you can rename the Person class, and the name field. Of course for the name field, you will need to modify your static reference as well. But it’s right there under your field declaration, so it’s very hard to forget this
  4. Traceability: you can ask your IDE to show you all instances where the “Person.NAME” property is accessed and make sure you have seen all usages if you need to do some refactoring or just need to know where something is used.
  5. Compile time safety: delete the name field on person (and the static reference), and your compiler will show you were this will cause problems
  6. You can use the property reference for other things, such as form field binding, i18n for field labels, ..

What are the downsides to this approach?

  1. The query looks uglier / harder to read. Of course, if you were using Hibernate Criteria or some kind of JPQL builder to avoid messy string concatenation, the property access would blend in much better and be easier on your fingers.
  2. You will have a static field for every field in your models, which is a little bit cluttering when reading the source code. If this bothers you, you can put the property references in a seperate class like PersonProps.
  3. You need to add the static fields for every field, which is a bit of extra typing and you’re lazy. I’m also lazy, so I made a little eclipse template to automate this somewhat:

eclipse-propref

You can add this to eclipse by going to Java >> Editor >> Templates, and adding a template named “propref” for context “Java” with this pattern:

${line_selection};

public static final String ${newName} = "${word_selection}"

Now when you’re in your model, select the field declaration, press control space, and select “propref”.

Yes, this method is complete overkill for a one-bean application, it’s just an example.

December 22, 2008

Finding out exactly which entities are causing a ConstraintViolationException (JPA)

Filed under: programming — Tags: , , — bosmeeuw @ 8:27 pm

Say you have an application using JPA. Your users can use and administrate lists of entities. They probably have the ability to permanently delete entities from the database.

If the entity the user wants to delete is used on another entity, the database should throw you a nice ConstraintViolationException, which JPA will (curiously) wrap in an EntityExistsException. You can catch this exception and display a nice informational message saying “You can’t delete this item because it’s already been used!”. This is better than just showing them the error the database spat out.

But what if you have a many entities, which have many relations between eachother? The user might want to find out just where their item is being used. And you might not feel like writing code to scan all your tables to find the item refering to the entity that’s being deleted. Below, I will explain how you can find out which entities are blocking the deletion of an arbitrary entity using some Reflection and ClassPath scanning.

Let’s say you have a service method like this:

public void deleteUser(long id) {
	User entity = em.find(User.class, id);
	em.remove(entity);
}

First, you’ll need to catch the Runtime Exception JPA will throw when encountering a constraint violation. Your service method will throw a YourApplicationException, which you will handle upstream and display as a nice error message.

public void deleteUser(long id) throws YourApplicationException {
	try {
		User entity = em.find(User.class, id);
		em.remove(entity);
	}
	catch (EntityExistsException e) {
		throw new YourApplicationException("You tried to delete an item which is in use.", e);
	}
}

To find out which entities are refering to the item we are deleting, we will inspect the database error message and extract the table name of the refering entity. Note the datbase message is specific to the DBMS you are using. I’m using PostgreSQL, if you are using a different DBMS you will probably need to tweak the pattern to match the message your DBMS is spitting out. Once we have the tablename, we will match it to an entity class by scanning the classpath. After that, we fill find out which field on the target class is of the same type as the entity being deleted (using reflection). We then make a query using JPA to fetch the referening entities. We put these entities in the exception, so it can be caught upstream and the entities can be displayed in a list.

Here’s the code for all of this:

public void delete(long id) throws YourConstraintViolationException {
	try {
		User entity = em.find(User.class, id);
		em.remove(entity);
	}
	catch (EntityExistsException e) {
		//need to rollback the transaction because we'll be doing a query later on
		em.getTransaction().rollback();
		em.getTransaction().begin();
		
		List<Object> linkedEntities = null;
		
		linkedEntities = findLinkedEntitiesFromContraintViolation(User.class, id, (ConstraintViolationException) e.getCause());
		
		throw new YourConstraintViolationException(linkedEntities, e);
	}
}

@SuppressWarnings("unchecked")
private List<Object> findLinkedEntitiesFromContraintViolation(Class<?> deletedEntityClass, long deletedEntityId, ConstraintViolationException e) {
	//unravel the exception so we have the SQLException
	BatchUpdateException batchUpdateException = (BatchUpdateException) e.getCause();
	SQLException sqlException = batchUpdateException.getNextException();
	
	List<Object> entities = new ArrayList<Object>();
	
	//match the database error message to find out the refering table name
	Matcher matcher = Pattern.compile("referenced from table \"(.*?)\"").matcher(sqlException.getMessage());
	if(matcher.find()) {
		String tableName = matcher.group(1);
		
		//we need to specify the base package all our entities reside under (possibly in sub-packages), and pass the ClassLoader of one of the entity classes to make the classpath scanning easier
		Class<?> entityClass = ClassUtils.findClassByCaseInsensitiveName(User.class.getClassLoader(), "your.entities.package",tableName);
		
		//check out which fields could possibly refer to the deleted class
		for(Field field : ClassUtils.getAllDeclaredFields(entityClass)) {
			if(field.getType().isAssignableFrom(deletedEntityClass)) {
				//fetch the refering entities using a JPA query and add them to the result
				String query = "FROM " + entityClass.getSimpleName() + " obj WHERE obj." + field.getName() + ".id = :deleted_id";
				List resultList = em.createQuery(query).setParameter("deleted_id",deletedEntityId).setMaxResults(10).getResultList();
				
				entities.addAll(resultList);
			}
		}
	}
	
	return entities;
}

The YourConstraintViolationException could look something like this:

public class YourConstraintViolationException extends Exception {
    
    private List<Object> linkedEntities;

    public YourConstraintViolationException(List<Object> linkedEntities, Throwable cause) {
        super(cause);
        
        this.linkedEntities = linkedEntities;
    }

    public List<Object> getLinkedEntities() {
        return linkedEntities;
    }

}

The code calling your service method might look this this:

try {
	userService.delete(someUserId);
}
catch(YourConstraintViolationException e) {
	out.write("<b>There was an error deleting the user. The user is in use on these items:</b>");
	
	out.write("<ul>");
	for(Object linkedEntity : e.getLinkedEntities()) {
		out.write("<li>" + linkedEntity.toString() + "</li>");
	}
	out.write("</ul>");
}

The actual classpath scanning is going on inside ClassUtils. This class will do its work both when your entities are normal .class files on disk, and when they’re packaged inside a jar. Here’s the code for ClassUtils.java:

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClassUtils {

    public static Class<?> findClassByCaseInsensitiveName(ClassLoader classLoader, String basePackage, String className) throws ClassNotFoundException, IOException, URISyntaxException {
	    URL packageUrl = classLoader.getResource(basePackage.replace(".","/"));
	    
	    Matcher matcher = Pattern.compile("(file:/.*?.jar)!(.*)").matcher(packageUrl.getFile());
        
	    if(matcher.find()) {
	        String jarFileUrl = matcher.group(1);
	        
	        return findClassByCaseInsentiveNameInJar(basePackage, new File(new URI(jarFileUrl)), className);
	    }
	    else {
    	    File packageFolder = new File(packageUrl.getFile());
    	    
    	    return findClassByCaseInsentiveNameInDirectory(basePackage, packageFolder, className);
	    }
	}

    private static Class<?> findClassByCaseInsentiveNameInJar(String basePackage, File jarFilePath, String className) throws IOException, ClassNotFoundException {
        JarFile jarFile = new JarFile(jarFilePath);
        
        String packagePath = basePackage.replace(".","/");
        
        String patternString = Pattern.quote(packagePath) + ".*/" + className + "\\.class";
        
        Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
        
        ArrayList<JarEntry> entries = Collections.list(jarFile.entries());
        
        for(JarEntry entry : entries) {
            Matcher matcher = pattern.matcher(entry.getName());
            
            if(matcher.matches()) {
                String fullClassName = entry.getName().replace("/",".").replace(".class","");
                
                return Class.forName(fullClassName);
            }
        }        
        
        return null;
    }

    private static Class<?> findClassByCaseInsentiveNameInDirectory(String packageName, File packageFolder, String className) throws ClassNotFoundException {
        for(File file : packageFolder.listFiles()) {



            if(file.getName().toLowerCase().equals(className + ".class")) {
                String fullClassName = packageName + "." + file.getName().replace(".class","");
                return Class.forName(fullClassName);
            }
            
            if(file.isDirectory()) {
                String subPackageName = packageName + "." + file.getName();
                Class<?> foundClass = findClassByCaseInsentiveNameInDirectory(subPackageName, file, className);
                
                if(foundClass != null) {
                    return foundClass;
                }
            }
        }
        
        return null;
    }

    public static List<Field> getAllDeclaredFields(Class<?> className) {
        List<Field> fields = new ArrayList<Field>();
        
        Class<?> superClass = className;
        
        do {
            for(Field field : superClass.getDeclaredFields()) {
                fields.add(field);
            }
            
            superClass = superClass.getSuperclass();
        }
        while(superClass != null);
        
        return fields;
    }
}

Blog at WordPress.com.