Hey all,

code that was working last week now doesn't. Did someone change the code
in WorldImageReader recently that would explain this?

My code is attached as: GridPtLayerOp.java

The three generated files are attached as gridfile.* 

When the gridfiles are added to a running uDig (e.g. by drag-and-drop),
I get an error message in the log that begins:


!ENTRY net.refractions.udig.catalog 2 0 2006-03-25 12:48:10.736
!MESSAGE !WorldImageGeoResource.error.layer.bounds!
!STACK 0
java.lang.IllegalArgumentException: The input argument(s) may not be
null.
        at javax.media.jai.ParameterBlockJAI.<init>(ParameterBlockJAI.java:208)
        at javax.media.jai.ParameterBlockJAI.<init>(ParameterBlockJAI.java:250)
        at
org.geotools.gce.image.WorldImageReader.readSourceImage(WorldImageReader.java:464)
        at
org.geotools.gce.image.WorldImageReader.read(WorldImageReader.java:301)
        at
net.refractions.udig.catalog.rasterings.AbstractRasterGeoResource.findResource(Unknown
 Source)
        at
net.refractions.udig.catalog.internal.worldimage.WorldImageGeoResourceImpl$IGeoResourceWorldImageInfo.getBounds(Unknown
 Source)
        at
net.refractions.udig.catalog.internal.worldimage.WorldImageGeoResourceImpl$IGeoResourceWorldImageInfo.<init>(Unknown
 Source)
        at
net.refractions.udig.catalog.internal.worldimage.WorldImageGeoResourceImpl.getInfo(Unknown
 Source)
        at net.refractions.udig.catalog.ui.workflow.ConnectionState.run(Unknown
Source)

Any ideas?

thanks,
adrian


package an.oread.operationsPlugin;



import java.util.Iterator;
import java.io.File;


import net.refractions.udig.catalog.IGeoResource;
import net.refractions.udig.project.ILayer;
//import net.refractions.udig.project.internal.Project;
//import net.refractions.udig.project.ui.ApplicationGIS;
import net.refractions.udig.ui.operations.IOp;

import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.data.FeatureSource;
import org.geotools.gce.image.WorldImageWriter;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.geometry.GeneralEnvelope;

import org.opengis.referencing.crs.CoordinateReferenceSystem;

import com.vividsolutions.jts.geom.Envelope;



public class GridPtLayerOp implements IOp {

	/**
	 * @see net.refractions.udig.ui.operations.IOp#op(org.eclipse.swt.widgets.Display,
         * java.lang.Object, org.eclipse.core.runtime.IProgressMonitor)
	 */
	public void op(final Display display, Object target, IProgressMonitor monitor) throws Exception {
		
		// TODO: remove me
		// A check to see that we are running our code, even when all else breaks.
		System.out.println("\nGot to start of operation: Grid a point layer.");
//		System.out.println("AfterBreakpoint?");
		
		

		// In our plugin.xml, we defined our target to be an ILayer 
		// so we cast our target from Object to that.
		// TODO: add a check isInstanceOf
		final ILayer myLayer = (ILayer) target;
//		final Project myProject = (Project) ApplicationGIS.getActiveProject();
		CoordinateReferenceSystem theCoordRefSys = null;
		
		
		// TODO This should obviously be user settable and in real world units.
		// TODO This will depend on the image extent/pixel size since this approach
		//      involves non-squre pixels---an interesting difficulty.
		// The final matrix will have the width of the internal value and 
		// vertical length (or 'height') of the leftmost value. The grid starts 
		// in the top left corner as theMatrix[0][0].
		final int IMAGE_WIDTH = 40;
		final int IMAGE_LENGTH = 60;
		float [][] theMatrix = new float [IMAGE_LENGTH][IMAGE_WIDTH];
        
        	
        	
////// STEP 1: Get access to the target's features
		// TODO Convert to use expressions. This code accesses the feature 
		// contents directly which works as of uDig 1.1M4 and Geotools 2.2.pre0
		// but is not guaranteed to work forever.
        final IGeoResource myIGR = myLayer.getGeoResource(FeatureSource.class);
        FeatureSource myFS = null;
    	if (myIGR.canResolve(FeatureSource.class)) {
    	   	try {
    	   			
    	   		myFS = myIGR.resolve(FeatureSource.class, monitor);
    	   			
    	   	} catch (Exception e) {
    	   		bailOut(display,
    	   				"Error resolving the IGeoResource",
    	   				"Resolving the IGeoResource failed with exception "+e);
    	   		// TODO: re-emit the exception, bail from the operation.
    	   	}
    	}
    	FeatureCollection myFC = myFS.getFeatures();
//        System.out.println("My FeatureCollection has "+myFC.size()+" elements");
        // TODO: remove me
        System.out.println("Got to access the target's features.");
        
        
        
        
        
////// STEP 2: Validate       TODO
        	//  1) all features share a common CRS (for we check they are from shapefile)
        	//  2) not too many (for now assume the shapefile is reasonable)

		
		
////// STEP 3: Calculate the matrix from the geometries
        Iterator myFCIter = null; 		//Always close it after use!
        
       	try {
    		myFCIter = myFC.iterator();
    		Feature f = (Feature) myFCIter.next();
    		// TODO Add the crs info to the feature:
    		// (1) Get the CRS, add it during GeomAttributeType creation
    		theCoordRefSys = f.getFeatureType().getDefaultGeometry().getCoordinateSystem();
    		
//        	while (  myFCIter.hasNext()){ 
//    			f = (Feature) myFCIter.next();
//        	}
    	
    	}
    	finally {
    		myFC.close( myFCIter );
    	}
    	
    	//For now make the values arbitrary. 
    	// The scale factor is also arbitrary.
        for (int i=0; i<IMAGE_LENGTH; i++){
        	for (int j=0; j<IMAGE_WIDTH; j++){
        		theMatrix[i][j] = i*j*100.0F;
        	}
        }
        System.out.println("Got to make the matrix");

        	

//////  STEP 4: Make a GridCoverage2D of the right size.
        GridCoverageFactory myGCFact = new GridCoverageFactory();
		GridCoverage2D myGC2D = null;
		Envelope theJTSEnvelope = myFC.getBounds();
		GeneralEnvelope theGeneralEnvelope = null;

		double [] min = {theJTSEnvelope.getMinX(),theJTSEnvelope.getMinY()};
		double [] max = {theJTSEnvelope.getMaxX(),theJTSEnvelope.getMaxY()};
		theGeneralEnvelope = new GeneralEnvelope(min,max);
		theGeneralEnvelope.setCoordinateReferenceSystem(theCoordRefSys);
		try{
		    myGC2D = myGCFact.create((CharSequence)"ResultGrid", theMatrix, theGeneralEnvelope);
		}catch(Exception e){
        	System.out.println("hit "+ e.getMessage()+"\n"+e);
        }
        //System.out.println("The grid is: "+myGC2D);
        System.out.println("Got to create the Grid");
        
        
        
        
        
//////  STEP 5: Write the Grid out to a file
        //TODO: check for overwrite
        File myFile = new File(Platform.getLocation().toString()+"/gridfile.ext");
        //System.out.println("My File is :"+myFile);
        WorldImageWriter myWIW = new WorldImageWriter(myFile);
//        System.out.println("My WorldImageWriter "+myWIW);
		try{
            myWIW.write(myGC2D,null);
		}catch(Exception e){
        	System.out.println("hit "+ e.getMessage());
        }
        

        System.out.println("Got to write the File.");
        
 
/*
////// STEP 5: Turn the Geotools Grid into a uDig Layer
           
        //Create a GridCoverageExchange via a service.u
        //1) create MemoryServiceExtensionImpl instance and 
        //2) use it to get an IService (which is actually MemoryServiceImpl.
        //3) from MemoryServiceImpl you can get MemoryGeoResourceImpl
        //4) use it to add a layer, or create a map, whatever.
      
        
        GridCoverageExchange myGCE = 
			service.resolve(GridCoverageExchange.class,
					new NullProgressMonitor());
        
        
        //Create a MemoryGeoResourceImpl
        //1) create MemoryServiceExtensionImpl instance and 
        //2) use it to get an IService (which is actually MemoryServiceImpl.
        //3) from MemoryServiceImpl you can get MemoryGeoResourceImpl
        //4) use it to add a layer, or create a map, whatever.

        
//        MemoryDataStore myMDS = new MemoryDataStore();
//        myMDS.addFeature(myBufferF);
        
        //MemoryServiceImpl myMSI = new MemoryServiceImpl(new URL ("an.other.org/local/"));
        //myMSI.ds = myMDS;
        //MemoryGeoResourceImpl myMGRI = new MemoryGeoResourceImpl("abuffertype",myMSI);
        
        //MemoryServiceExtensionImpl myMSEI = new MemoryServiceExtensionImpl();
        
        
//        NewServiceConnectionFactory factory = new NewServiceConnectionFactory();
//        Map<String, Serializable> params = factory.createConnectionParameters(null);
        
        MemoryServiceImpl service = new MemoryServiceImpl(MemoryService.URL);
        
        // This uses the MemoryServiceImpl to get a dataStore. The MSImpl 
        // creates an empty dataStore and registers it with the Catalog.
        GridCoverageExchange myGCE = 
			service.resolve(GridCoverageExchange.class,
					new NullProgressMonitor());
        
        AnotherMemoryDataStore dataStore =
        			service.resolve(AnotherMemoryDataStore.class,
        							new NullProgressMonitor());
        dataStore.createSchema(myBufferFT);
        dataStore.addFeature(myBufferF);
        myGCE.
//        System.out.println("Datastore: "+dataStore);
//        try {
//        		System.out.println("Schema: "+dataStore.getSchema("New_Type_0"));
//        } catch (java.io.IOException ioEx){
//        		System.out.println("Hit an IO exception"+ ioEx);	
//        }
//        
//        try {
//    			System.out.println("Schema: "+dataStore.getSchema("oreadbufferedPointsTYPE"));
//        } catch (java.io.IOException ioEx){
//        		System.out.println("Hit an IO exception"+ ioEx);	
//        }

        List<? extends IGeoResource>  geoResourceList =  	
        			(List<? extends IGeoResource>)service.resolve(
        										List.class,
        										new NullProgressMonitor());

        List<IGeoResource>  geoResourceList2 =  	
			(List<IGeoResource>)service.resolve(
										List.class,
										new NullProgressMonitor());

//        System.out.println("..."+geoResourceList);
//        	System.out.println("The List is of size "+geoResourceList.size());
        
        	//For some reason, creating the Layer is what adds it to the catalog!
        LayerFactoryImpl myLF = LayerFactoryImpl.create();
        Layer lyr = myLF.createLayer(geoResourceList2.get(0));
//        System.out.println("The layer is: " + lyr );
//        System.out.println("The layer's CRS is: "+ lyr.getCRS(null) );
        System.out.println("Got to create the layer.");
        
        //Make a List<GeoResource>
        List<IGeoResource> myGRList = new ArrayList ();
        myGRList.add(geoResourceList2.get(0));
      
        
        
        
        
        
////// STEP 6: Add the layer to a Map
        
//////// Step 6a: Add the layer to the current map.
      // NOTA BENE This requires that we sort out the coordinate reference system.
      // TODO Add the buffer under the buffered layer (getLayer z order, call with int.
        ApplicationGIS.addLayersToMap(myLayer.getMap(),geoResourceList2,myLayer.getZorder(),myProject);
//        AddLayerCommand myALC = new AddLayerCommand(lyr);
//        Map sourceMap = (Map) myLayer.getMap();
//        sourceMap.sendSync(myALC);
        
//////// Step 6b: Add the layer to a new map.
//		CreateMapCommand cmCommand = new CreateMapCommand(null, geoResourceList, myProject);
//		myProject.sendSync(cmCommand);
       
//////// Step 6c: Add the layer to the state map.
        // Needs a newer SDK, nightly after March 1 2006 i.e. 1.1M5 or better.
//		ApplicationGIS.addLayerstoMap(myLayer.getMap(),(List<IGeoResource>)geoResourceList,0,(Project)ApplicationGIS.getActiveProject());


        System.out.println("Got to end of commands");
        
        
        
        
        
        // Here we output a confirmation dialog to say the operation is done.
        // TODO: remove this, it's a waste.
//        display.asyncExec(new Runnable(){
//               public void run() {
//            	   
//            	   
//                   MessageDialog.openInformation(display.getActiveShell(), 
//                		   "Done with Operation on layer: "+ myLayer.getName(), 
//                		   "Finished the Operation");
//               }
//           });
           */

        System.out.println("Got to end of the operation.");
	}

	/**
	 * This method is called to bail out of the Operation by displaying a 
	 * dialog explaining where we hit a snag.
	 * 
	 * @param display		The eclipse display object from the Operation.
	 * @param errorTitle		A java String for the title of the error dialog.
	 * @param errorMessage 	A java String with the text to display.
	 */
	private void bailOut (	final Display display, 
							final String errorTitle, 
							final String errorMessage){
		
        display.asyncExec(new Runnable(){
            public void run() {
         	   
                MessageDialog.openError(display.getActiveShell(), 
                		errorTitle, 
                		errorMessage);
            }
        });
	}
}
472.03696975353523
0.0
0.0
-305.8076173909358
215362.80386139057
1261971.8070494558

Attachment: gridfile.png
Description: PNG image

PROJCS["NAD83 / UTM zone 37N", 
  GEOGCS["NAD83", 
    DATUM["North_American_Datum_1983", 
      SPHEROID["GRS 1980", 6378137.0, 298.257222101, AUTHORITY["EPSG","7019"]], 
      AUTHORITY["EPSG","6269"]], 
    PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]], 
    UNIT["degree", 0.017453292519943295], 
    AXIS["Lon", EAST], 
    AXIS["Lat", NORTH], 
    AUTHORITY["EPSG","4269"]], 
  PROJECTION["Transverse_Mercator"], 
  PARAMETER["central_meridian", 39.0], 
  PARAMETER["latitude_of_origin", 0.0], 
  PARAMETER["scale_factor", 0.9996], 
  PARAMETER["false_easting", 500000.0], 
  PARAMETER["false_northing", 0.0], 
  UNIT["m", 1.0], 
  AXIS["x", EAST], 
  AXIS["y", NORTH], 
  AUTHORITY["EPSG","26910"]]
_______________________________________________
User-friendly Desktop Internet GIS (uDig)
http://udig.refractions.net
http://lists.refractions.net/mailman/listinfo/udig-devel

Reply via email to