GeoTools : ConnectionTester

This is a great little program to help you figure out what is gonig on, and more importantly what is going wrong (smile)

To run this program:

java ConnectionTester connection.properties

If you need to just look at a single "FeatureType":

java ConnectionTester connection.properties typename

Your connection.properties is a normal java properties file with all the connection parameters mentioned by the DataStoreFactory.

For oracle I am using the following:

dbtype=oracle
host=roadrunner
port=1521
user=sens
passwd=sens
instance=bstdb

For shapefile I would use this:

url=file:///C:/Temp/shapefile.shp

You could also just mention any of the file formats diretly on the command line, and the program would make up a propreties map:

java ConnectionTester C:\Temp\shapefile.shp

It does not work!

Are your correction parameters correct? Check the javadocs for each factory ...

What does the error message say? If it is something like NullPointerException you may have found a bug. However look at the stacktrace, if it is a null pointer exception when looking for an SRID in oracle you probably have just not set up oracle correctly...however send the bug anyways cause it should have a better error message.

Remember to step through with the debugger to learn how things work (and when submitting bug reports to the module maintainer). Note you can figure out who to send the bug report to by checking in the project.xml file (look under developers):

  • Shapefile: Jesse
  • Postgis: Justin
  • Oracle: Marc

Now for the Program

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.DefaultQuery;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.feature.AttributeType;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureType;
import org.geotools.filter.Filter;

public class ConnectionTester {
	public static void main(String args[]) {
		if (args.length != 1 && args.length != 2) {
			System.exit(1);
		}
		try {
			URL url = url( args[0] );
			Map params = params( url );
			DataStore ds = DataStoreFinder.getDataStore(params);
			if (ds == null) {
				System.err.println("Could not connect! (" + args[0] + ")");
				System.exit(1);
			}
			String types[] = ds.getTypeNames();
			Arrays.sort( types );
			
			System.out.println("Connected!");
			System.out.println(" found " + Arrays.asList(types));
			if( args.length == 2 ){
				if( Arrays.binarySearch( types, args[1] ) != -1 ){
					types = new String[]{ args[1] };
				}
				else {
					System.err.println("Could not locate the type "+args[1] );
					System.exit(1);
				}
			}
			for (String typeName : types) {
				try {
					FeatureSource featureSource = ds.getFeatureSource(typeName);
					FeatureType featureType = featureSource.getSchema();

					describeSchema(featureType);
					showSummary(featureSource);
					showData(featureSource);
				}
				catch (Exception eek){
					eek.printStackTrace();
					System.out.println("\n Could not use'"+typeName+"':"+eek);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	private static void showSummary(FeatureSource featureSource) {
		System.out.println("METADATA:");
		try {
			System.out.println(" count=" + featureSource.getCount(Query.ALL));
			System.out.println(" bounds=" + featureSource.getBounds());
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	private static void showData(FeatureSource featureSource) {
		System.out.println("DATA:");
		Query query = new DefaultQuery(featureSource.getSchema().getTypeName(),
				null, Filter.NONE, 5, Query.ALL_NAMES,
				"get first five features");
		try {
			FeatureCollection features = featureSource.getFeatures(query);
			Iterator iterator = features.iterator();
			try {
				for (int i = 0; iterator.hasNext(); i++) {
					Feature feature = (Feature) iterator.next();
					System.out.print("[" + i + "]");
					System.out.print(" fid=" + feature.getID());
					for (int j = 0; j < feature.getNumberOfAttributes(); j++) {
						Object attribute = feature.getAttribute(j);
						System.out.println("\t" + attribute);
					}
					System.out.println();
				}
			} finally {
				features.close(iterator);
			}
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	private static void describeSchema(FeatureType featureType) {
		System.out.println("SCHEMA:");
		System.out.println(" typeName:" + featureType.getTypeName());
		System.out.println("namespace:" + featureType.getNamespace());
		int i = 0;
		for (AttributeType type : featureType.getAttributeTypes()) {
			System.out.print("[" + i + "]");
			System.out.print(type.getName());
			System.out.print("\t");
			System.out.print("("+type.getMinOccurs() + ":" + type.getMaxOccurs()
					+ ")");
			System.out.print(type.getClass().getName());
			System.out.println();
			//System.out.println(type.getRestriction()); //TODO: REPORT AS BUG AGAINST FILTER
			i++;
		}
	}

	/** Make a good URL out of the target */
	private static URL url(String target) throws IOException {
		if (target.startsWith("http:") || target.startsWith("file:")) {
			try {
				return new URL(target);
			} catch (MalformedURLException e) {
				throw (IOException) new IOException(
						"Invalid target for shapefile").initCause(e);
			}
		} else {
			File file = new File(target);
			if( !file.exists() ){
				throw new FileNotFoundException( target );
			}
			return file.toURL();
		}
	}

	static public final Map params(URL url) throws IOException {
		if (url.toExternalForm().endsWith(".properties")) {
			InputStream input = url.openStream();
			Properties params = new Properties();
			params.load(input);
	
			return params;
		}	
		if( "http".equals( url.getProtocol() ) || "file".equals( url.getProtocol() )){
			Map params = new HashMap();
			params.put("url", url );
			return params;			
		}		
		throw new IllegalArgumentException("Properties or url only");
	}
}