Hello,

I want to upload the features of a shp into postGIS and I found a 
helpful solution here: 
http://sourceforge.net/p/geotools/mailman/geotools-gt2-users/thread/738a79f755e34812bcca697156397...@gmail.com/

I created an unzip function to unzip the .shp and then added most parts 
of the code of the postGIS-upload solution into it but it does not seem 
to work. I implemented it into the UploadAndProcess.java. I am not sure 
if I have to implement it into the Upload.java?

Another question I have:
The paramters in the solution are static. So I think (if it finally 
works) everyone can see database name, user and pw? How can I prevent it 
and keep it more dynamic?

Thanks for any help. I am very new into geonetwork


Here is the edited code of UploadAndProcess.java

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 protocolElem = params.getChild("protocol");
         String proname = protocolElem.getText();
         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);

         // check protocol and if necessary upload in postgis db

     if (proname.equals("PostGIS database table")) {
             String shpname = null;
             String corrname = null;

             // unzip shapefile

             try {
                 ZipEntry entry;
                 ZipFile zipin = new ZipFile(dir.getAbsolutePath() + "\\"
                         + fname);
                 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();
             }

             // upload file to postgis db


                 File dirUpload = new File(dir.getAbsolutePath() + "\\"
                         + shpname);
                 Map<Object, Serializable> connectParameters = new 
HashMap<Object, Serializable>();
                 connectParameters.put("url", dirUpload.toURI().toURL());
                 connectParameters.put("create spatial index", true);

                 DataStore dataStore = DataStoreFinder
                         .getDataStore(connectParameters);
                 String[] typeNames = dataStore.getTypeNames();
                 String typeName = typeNames[0];

                 SimpleFeatureType ft = dataStore.getSchema(typeName);
                 SimpleFeatureTypeBuilder builder = new 
SimpleFeatureTypeBuilder();
                 builder.setName(typeName);
                 builder.setAttributes(ft.getAttributeDescriptors());
                 builder.setCRS(ft.getCoordinateReferenceSystem());
                 SimpleFeatureType newSchema = builder.buildFeatureType();

                 // Problem (but work)
                 CoordinateReferenceSystem crs = ft
                         .getCoordinateReferenceSystem();
                 Integer crsCode = CRS.lookupEpsgCode(crs, true);
                 Set<ReferenceIdentifier> refIds = ft
.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(5432));
                 param.put("database", "geonetwork");
                 param.put("user", "geonetwork");
                 param.put("passwd", "secr");
                 param.put("schema", "test");

                 DataStore pgdataStore = 
DataStoreFinder.getDataStore(param);
                 pgdataStore.createSchema(newSchema);

                 FeatureSource<SimpleFeatureType, SimpleFeature> 
featureSource = dataStore
                         .getFeatureSource(typeName);
                 FeatureCollection<SimpleFeatureType, SimpleFeature> 
collection = featureSource
                         .getFeatures();
                 FeatureStore<SimpleFeatureType, SimpleFeature> 
featStore = (FeatureStore<SimpleFeatureType, SimpleFeature>) pgdataStore
                         .getFeatureSource(typeName);
                 featStore.addFeatures(collection);




             context.info("UPLOADED:" + fname + "," + id + ","
                     + context.getIpAddress() + "," + username);

             // Set parameter and process metadata to reference the 
uploaded file

             params.addContent(new Element("url")
.setText("jdbc:postgresql_postGIS://localhost:5432/geonetwork:secret@geonetwork"));
             params.addContent(new Element("name").setText(corrname));
             params.addContent(new 
Element("protocol").setText("DB:POSTGIS"));

     } else {

             context.info("UPLOADED:" + fname + "," + id + ","
                     + context.getIpAddress() + "," + username);

             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);

         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;
     }
}

------------------------------------------------------------------------------
_______________________________________________
GeoTools-GT2-Users mailing list
GeoTools-GT2-Users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/geotools-gt2-users

Reply via email to