Thursday, January 31, 2008

How to create a temporary layer with proper CRS with new FeatureType

In the code examples of the udig sdk you can find a nice snippet explaining how to create a temporary resource layer. One of those nice things which a user can decide whether to keep and save to shapefile or just trash it.

Let's see the code:


List featuresList = this is my list subset of a leyer or whatever
String geomType = "MultiPolygon";
Object[][] ob = new Object[featuresList.size()][2];
for( int i = 0; i < featuresList.size(); i++ ) {

ob[i][0] = featuresList.get(i).getGeometry();
ob[i][1] = i;
}
FeatureType featureType = null;
String typeName = "Macrobacini";
try {
featureType = DataUtilities.createType(typeName, "geom:" + geomType
+ ",indice:java.lang.Integer");
featureType = DataUtilities.createSubType(featureType, null, ApplicationGIS.getActiveMap().getViewportModel().getCRS());
} catch (SchemaException e1) {
e1.printStackTrace();
}

JGrassCatalogUtilities.removeMemoryServiceByTypeName(typeName);

IGeoResource resource = CatalogPlugin.getDefault().getLocalCatalog()
.createTemporaryResource(featureType);
FeatureCollection coll = FeatureUtilities.createFeatures(featureType, ob);
try {
resource.resolve(FeatureStore.class, pm).addFeatures(coll);
} catch (IOException e) {
e.printStackTrace();
}
ApplicationGIS.addLayersToMap(ApplicationGIS.getActiveMap(), Collections
.singletonList(resource), -1);



I added the createsubtype part because beeing the featuretype created from scratch, the CRS was missing and it interpreted my coordinates as lat/long, and therefore out of the admitted degrees.

The removeMemoryService part is needed because no two memorydatastores of the same name are admitted in the same catalog service, and a nice:
java.lang.UnsupportedOperationException: Schema modification not supported
is thrown whenever you force it to try nevertheless.

Therefore the service has to be removed before going on, which is done like that:


public static synchronized void removeMemoryServiceByTypeName( String typeName ) {
MemoryServiceImpl service = null;
try {
List< ? extends IResolve> members = CatalogPlugin.getDefault().getLocalCatalog()
.members(new NullProgressMonitor());
for( IResolve resolve : members ) {
if (resolve instanceof MemoryServiceImpl) {
if (URLUtils.urlEquals(resolve.getIdentifier(), MemoryServiceExtensionImpl.URL,
true)) {
service = (MemoryServiceImpl) resolve;
break;
}
}
}
MemoryDataStore ds = service.resolve(MemoryDataStore.class, new NullProgressMonitor());
if (Arrays.asList(ds.getTypeNames()).contains(typeName)) {
CatalogPlugin.getDefault().getLocalCatalog().remove(service);
}
} catch (IOException e) {
CatalogPlugin.log("Error finding services", e); //$NON-NLS-1$
}
}






No comments: