Results 1 to 11 of 11
  1. #1
    filior is offline Member
    Join Date
    Aug 2014
    Posts
    8
    Rep Power
    0

    Default I can't find the NullPointerException in my Code - Help please

    Hey Guys,

    I am working with GeoNetwork opensource and want to implement an upload of a shapefile into a PostGIS database if a user selects a zip-file.
    So I first implemented an unzip of the zip which works correctly. After it i want to upload the shape features (like Coordinates) into the postGIS database but it does not work cause somewhere in my code there is a NullPointerException which I cant find as I am a Java beginner. Maybe someone can't find it and make me happy :-)
    The Exception should be caused somewhere between line 82 and 133. I hope the code looks not so complicated for you cause I used the GeoTools Toolkit and I think not all of you know this toolkit.

    Thank you very much for every advice!!
    filio

    PHP Code:
    public class UploadAndProcess implements Service {
        public void init(String appPath, ServiceConfig params) throws Exception {
        }
    
        public Element exec(Element params, ServiceContext context)
                throws Exception {
    
            GeonetContext gc = (GeonetContext) context
                    .getHandlerContext(Geonet.CONTEXT_NAME);
            DataManager dataMan = gc.getBean(DataManager.class);
    
            String uploadDir = context.getUploadDir();
    
            String id = Utils.getIdentifierFromParameters(params, context);
            String filename = Util.getParam(params, Params.FILENAME);
      
            String access = Util.getParam(params, Params.ACCESS, "private");
            String overwrite = Util.getParam(params, Params.OVERWRITE, "no");
    
            Lib.resource.checkEditPrivilege(context, id);
    
            // get info to log the upload
    
            UserSession session = context.getUserSession();
            String username = session.getUsername();
            if (username == null) 
                username = "unknown (this shouldn't happen?)";
    
            Element fnameElem = params.getChild("filename");
            String fname = fnameElem.getText();
            
            File dir = new File(Lib.resource.getDir(context, access, id));
            Upload.moveFile(context, uploadDir, fname, dir, overwrite);
    
            context.info("UPLOADED:" + fname + "," + id + ","
                    + context.getIpAddress() + "," + username);
            
            
    
            // Set parameter and process metadata to reference the uploaded file
            params.addContent(new Element("url").setText(filename));
            params.addContent(new Element("name").setText(filename));
            params.addContent(new Element("protocol")
                    .setText("WWW:DOWNLOAD-1.0-http--download"));
    
            String process = "onlinesrc-add";
            XslProcessingReport report = new XslProcessingReport(process);
            
            String shpname;
            String corrname; 
            if(filename.endsWith(".zip")) {
            	
            	try{        
                    ZipEntry entry;
                    ZipFile zipin = new ZipFile(dir.getAbsolutePath()+ "\\" + filename);
                    Enumeration entries = zipin.entries();
                    byte[] buffer = new byte[16384];
                    int len;
                    while (entries.hasMoreElements()) {
                        entry = (ZipEntry) entries.nextElement();
                        String entryFileName = entry.getName();                
                        if (entry.getName().endsWith(".shp") == true){
                            shpname = entryFileName;
                            corrname = entry.getName().substring(0,entry.getName().lastIndexOf('.'));
                        }
                        entryFileName = entry.getName().substring(entry.getName().lastIndexOf("/")+1);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(dir,entryFileName)));
                        BufferedInputStream bis = new BufferedInputStream(zipin.getInputStream(entry));
                        while ((len = bis.read(buffer)) >0) {
                            bos.write(buffer,0,len);
                        }
                    bos.flush();
                    bos.close();
                    bis.close();
                    }
                    zipin.close();
                    
                }catch(Exception exs){
                exs.printStackTrace();
                }
            	
            		String url = dir.getAbsolutePath()+"\\" + filename;
            		context.info(url);
            		File dirUpload = new File (url);
            		Map<Object, Serializable> shapeParams = new HashMap<Object, Serializable>();
            		shapeParams.put("url", dirUpload.toURI().toURL());
            		shapeParams.put("create spatial index",  true);
            		
            		DataStore dataStore = DataStoreFinder.getDataStore(shapeParams);
            		String[] typeNames = dataStore.getTypeNames();
            		String typeName = typeNames[0];
            		
            		SimpleFeatureType sft = dataStore.getSchema(typeName);
            		SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder();
            		sftb.setName(typeName);
            		sftb.setAttributes(sft.getAttributeDescriptors());
            		sftb.setCRS(sft.getCoordinateReferenceSystem());;
            		SimpleFeatureType newSchema = sftb.buildFeatureType();
          		
            		CoordinateReferenceSystem crs = sft.getCoordinateReferenceSystem();
            		Integer crsCode = CRS.lookupEpsgCode(crs, true);
            		Set<ReferenceIdentifier> refIds = sft.getCoordinateReferenceSystem().getIdentifiers();
            		if(((refIds == null) || (refIds.isEmpty())) && (crsCode == null)) {
            			CoordinateReferenceSystem crsEpsg = CRS.decode("EPSG:4326");
            			newSchema = SimpleFeatureTypeBuilder.retype(newSchema, crsEpsg);
            			
            		}
            		
            		Map param = new HashMap();
            		
            		param.put("dbtype", "postgis");
                    param.put("host", "localhost");
                    param.put("port", new Integer(5433));
                    param.put("database", "geonetwork");
                    param.put("user", "geonetwork");
                    param.put("passwd", "secret");
                    param.put("schema", "mydata");
                    
                    DataStore pgdataStore = DataStoreFinder.getDataStore(param);
                    pgdataStore.createSchema(newSchema);
    
                    FeatureSource<SimpleFeatureType, SimpleFeature> featureSource =
                        dataStore.getFeatureSource(typeName);
                    FeatureCollection<SimpleFeatureType, SimpleFeature> collection =
                        featureSource.getFeatures();
                    @SuppressWarnings("unchecked")
    				FeatureStore<SimpleFeatureType, SimpleFeature> featStore =
                        (FeatureStore<SimpleFeatureType, SimpleFeature>) pgdataStore.getFeatureSource(typeName);
                    featStore.addFeatures(collection);
            	
            }
            
            Element processedMetadata;
            try {
                processedMetadata = XslProcessing.process(id, process,
                        true, context.getAppPath(), params, context, report, true, dataMan.getSiteURL(context));
                if (processedMetadata == null) {
                    throw new BadParameterEx("Processing failed", "Not found:"
                            + report.getNotFoundMetadataCount() + ", Not owner:" + report.getNotEditableMetadataCount()
                            + ", No process found:" + report.getNoProcessFoundCount() + ".");
                }
            } catch (Exception e) {
                throw e;
            }
            // -- return the processed metadata id
            Element response = new Element(Jeeves.Elem.RESPONSE)
                    .addContent(new Element(Geonet.Elem.ID).setText(id));
    
            return response;
        }
    }
    Last edited by filior; 08-14-2014 at 08:59 PM.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default Re: I can't find the NullPointerException in my Code - Help please

    Can you post the full text of your stack trace? That should contain the exact line that's throwing the NPE. Then go to that line and list every variable used on that line. What are the values of each of those variables? Use a debugger or some print statements to figure out which one is null. Then step back though your code to figure out *why* it's null.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    filior is offline Member
    Join Date
    Aug 2014
    Posts
    8
    Rep Power
    0

    Default Re: I can't find the NullPointerException in my Code - Help please

    Quote Originally Posted by KevinWorkman View Post
    Can you post the full text of your stack trace? That should contain the exact line that's throwing the NPE. Then go to that line and list every variable used on that line. What are the values of each of those variables? Use a debugger or some print statements to figure out which one is null. Then step back though your code to figure out *why* it's null.
    Thanks for your answer!
    I use Maven in Elipse JaveEE and I see the NullPointerException in the Maven console but it shows no exact line. Do you know if debugging is possible there or how I can show extract the exact line? Then I can do it tomorrow, will have a look on it and reply here cause now I am at home, not at work :-)

    Thanks again!
    filior

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: I can't find the NullPointerException in my Code - Help please

    There should be a stack trace somewhere, usually in the Java console associated with Eclipse. Can you copy and paste that
    trace here?

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: I can't find the NullPointerException in my Code - Help please

    If you need help using the Eclipse debugger, I wrote a little article to explain how to use it with a mountain of screenshots:

    Java Enterprise Stuff: Debug java apps for beginners

    I just spotted a monumentally stupid typo in there though; it is 'visual cue', not 'visual queue'. That is going to annoy me for the rest of the day until I get home and fix it.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    filior is offline Member
    Join Date
    Aug 2014
    Posts
    8
    Rep Power
    0

    Default Re: I can't find the NullPointerException in my Code - Help please

    Quote Originally Posted by jim829 View Post
    There should be a stack trace somewhere, usually in the Java console associated with Eclipse. Can you copy and paste that
    trace here?

    Regards,
    Jim
    I startet the jetty server (which is a servlet container and webserver) with a Maven Build to access Geonetwork on http://localhost:8080/geonetwork. I ran the jetty server in Debug Output Mode.
    When I want to upload a file in Geonetwork, I receive the following Output in the Eclipse console:

    2014-08-15 10:21:42,013 INFO [jeeves.request] - ================================================== ========
    2014-08-15 10:21:42,013 INFO [jeeves.request] - HTML Request (from 0:0:0:0:0:0:0:1) : /geonetwork/srv/eng/resource.upload.and.link
    2014-08-15 10:21:42,014 INFO [jeeves.service] - Dispatching : resource.upload.and.link
    2014-08-15 10:21:42,014 INFO [jeeves.webapp.resource.upload.and.link] - dano.zip
    2014-08-15 10:21:42,014 INFO [jeeves.webapp.resource.upload.and.link] - dano.zipendet mit shp
    2014-08-15 10:21:42,024 INFO [jeeves.webapp.resource.upload.and.link] - Source : C:\Users\DPipjorke\git\geonetwork\web\src\main\web app\.\data\tmp\dano.zip
    2014-08-15 10:21:42,024 INFO [jeeves.webapp.resource.upload.and.link] - Destin : C:\Users\DPipjorke\git\geonetwork\web\src\main\web app\WEB-INF\data\data\metadata_data\00000-00099\43\private\dano.zip
    2014-08-15 10:21:42,024 WARN [jeeves.webapp.resource.upload.and.link] - Cannot move uploaded file
    2014-08-15 10:21:42,024 WARN [jeeves.webapp.resource.upload.and.link] - (C) Source : C:\Users\DPipjorke\git\geonetwork\web\src\main\web app\.\data\tmp\dano.zip
    2014-08-15 10:21:42,024 WARN [jeeves.webapp.resource.upload.and.link] - (C) Destin : C:\Users\DPipjorke\git\geonetwork\web\src\main\web app\WEB-INF\data\data\metadata_data\00000-00099\43\private\dano.zip
    2014-08-15 10:21:42,034 ERROR [jeeves.service] - Exception when executing service
    2014-08-15 10:21:42,034 ERROR [jeeves.service] - (C) Exc : java.lang.Exception: Unable to move uploaded file to destination directory
    2014-08-15 10:21:42,034 INFO [jeeves.service] - -> dispatching to error for : resource.upload.and.link
    2014-08-15 10:21:42,044 INFO [jeeves.service] - -> transforming with stylesheet : C:\Users\DPipjorke\git\geonetwork\web\src\main\web app\xsl/error-modal.xsl
    2014-08-15 10:21:42,054 INFO [jeeves.service] - -> end error transformation for : resource.upload.and.link
    2014-08-15 10:21:42,054 INFO [jeeves.service] - -> error ended for : resource.upload.and.link
    It does not help much cause it does not say where the exception was caused.

    I tried to add a try - catch Exception block between lines 81 and 130 to add stacktrace output but when I do this I receive the message that an "Exception is caught when exception is not thrown" when I run the project as a Maven install which sounds very odd to me.

    @gimbal 2: Thank you for the link. This is very useful for me. I think this only works with Eclipse SE? Cause in Eclipse EE I cant run the java file within Eclipse like I do it in Eclipse SE.

  7. #7
    filior is offline Member
    Join Date
    Aug 2014
    Posts
    8
    Rep Power
    0

    Default Re: I can't find the NullPointerException in my Code - Help please

    I finally found the line of the exception. I just had to take NullPointerException instead of Exception in the try - catch.

    This is the stacktrace output:

    java.lang.NullPointerException
    at org.fao.geonet.services.resources.UploadAndProcess .exec(UploadAndProcess.java:167)
    Line 167 is Line 90 in the code which I posted here yesterday.

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: I can't find the NullPointerException in my Code - Help please

    In other words: dataStore.getTypeNames() returns null. Time to check out the javadoc documentation of that method.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: I can't find the NullPointerException in my Code - Help please

    Quote Originally Posted by gimbal2 View Post
    In other words: dataStore.getTypeNames() returns null. Time to check out the javadoc documentation of that method.
    Actually, I think dataStore itself could be null. Line 90 is line 2 below.

    Java Code:
    DataStore dataStore = DataStoreFinder.getDataStore(shapeParams);
    String[] typeNames = dataStore.getTypeNames();
    String typeName = typeNames[0];
    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: I can't find the NullPointerException in my Code - Help please

    Yep, you're right. I misread the line numbers.

    At this point I also feel shame for not explaining the WHY: its a simple matter of looking at the line that the exception points at and wondering "hmmm, what in this line could be null?"

    There can only be one possibility. And having found the source, then it becomes possible to investigate the why: WHY does that variable contain a null-reference? That is answered by looking at where it is supposed to come from. In this case the line above it; DataStoreFinder.getDataStore() must return a null value.

    The next step is what I mentioned earlier; read the documentation of that method and figure out how it should be used properly so it won't return null.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  11. #11
    filior is offline Member
    Join Date
    Aug 2014
    Posts
    8
    Rep Power
    0

    Default Re: I can't find the NullPointerException in my Code - Help please

    Again thank you for your help!

    I wrote this code with help of some geotools guides and helps in the internet, for example this one: WFS Plugin — GeoTools 12-SNAPSHOT User Guide --> Step 3.
    I also found some same code fragments from users who are using geotools toolkit.
    Tomorrow I will have a look if the datastore is null and I hope I can find the source for it. I am new to the more complex Java and before I did only some exercises in Java Books. So i am a little helpless now

Similar Threads

  1. Replies: 2
    Last Post: 04-29-2013, 06:30 PM
  2. My code keeps giving me NullPointerException error
    By linx2001 in forum New To Java
    Replies: 4
    Last Post: 11-07-2012, 04:47 PM
  3. HELP!! Code won't compile - NullPointerException
    By JuliaDavies in forum NetBeans
    Replies: 10
    Last Post: 03-21-2012, 09:29 AM
  4. HELP!! NullPointerException - code won't compile
    By JuliaDavies in forum NetBeans
    Replies: 2
    Last Post: 03-19-2012, 06:40 PM
  5. Replies: 5
    Last Post: 04-21-2011, 09:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •