Search in sources :

Example 1 with UserDataDTO

use of au.org.ala.spatial.dto.UserDataDTO in project spatial-portal by AtlasOfLivingAustralia.

the class SpeciesAutoComplete method loadUserPoints.

private String loadUserPoints(String val) {
    Map<String, UserDataDTO> htUserSpecies = (Map<String, UserDataDTO>) Sessions.getCurrent().getAttribute(StringConstants.USERPOINTS);
    String userPoints = "";
    String lVal = val.toLowerCase();
    try {
        if (htUserSpecies != null && !htUserSpecies.isEmpty()) {
            StringBuilder sbup = new StringBuilder();
            for (Map.Entry<String, UserDataDTO> e : htUserSpecies.entrySet()) {
                String k = e.getKey();
                UserDataDTO ud = e.getValue();
                if ("user".contains(lVal) || ud.getName().toLowerCase().contains(lVal) || ud.getDescription().toLowerCase().contains(lVal)) {
                    sbup.append(ud.getName());
                    sbup.append(" |");
                    sbup.append(k);
                    sbup.append("|");
                    sbup.append("user");
                    sbup.append("|");
                    sbup.append(ud.getFeatureCount());
                    sbup.append("\n");
                }
            }
            userPoints = sbup.toString();
        }
    } catch (Exception e) {
        LOGGER.error("Unable to load user points into Species Auto Complete", e);
    }
    return userPoints;
}
Also used : UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) Map(java.util.Map) WrongValueException(org.zkoss.zk.ui.WrongValueException)

Example 2 with UserDataDTO

use of au.org.ala.spatial.dto.UserDataDTO in project spatial-portal by AtlasOfLivingAustralia.

the class MapComposer method deactiveLayer.

public void deactiveLayer(MapLayer itemToRemove, boolean updateMapAndLayerControls, boolean recursive, boolean updateOnly) {
    if (itemToRemove != null) {
        Query q = itemToRemove.getSpeciesQuery();
        if (q instanceof UserDataQuery) {
            String pid = q.getQ();
            Map<String, UserDataDTO> htUserSpecies = (Map) getMapComposer().getSession().getAttribute(StringConstants.USERPOINTS);
            if (htUserSpecies != null) {
                htUserSpecies.remove(pid);
            }
        }
        // update the active layers list
        List<MapLayer> activeLayers = getPortalSession().getActiveLayers();
        if (activeLayers != null) {
            LOGGER.debug("obtained activelayers arraylist from session, count: " + activeLayers.size());
            if (!activeLayers.isEmpty()) {
                ListModelList listmodel = (ListModelList) activeLayersList.getModel();
                if (listmodel != null) {
                    listmodel.remove(itemToRemove);
                    if (activeLayers.isEmpty()) {
                        lblSelectedLayer.setValue("No layers added");
                    }
                }
            } else {
                LOGGER.debug("active layers list is empty, so not updating it");
            }
        }
        if (updateMapAndLayerControls) {
            if (!updateOnly) {
                // tell openlayers to kill the layer
                openLayersJavascript.removeMapLayerNow(itemToRemove);
            }
            updateLayerControls();
            removeFromSession(itemToRemove.getName());
        }
        // descend children if we were called recursively
        if (recursive && itemToRemove.hasChildren()) {
            for (MapLayer child : itemToRemove.getChildren()) {
                deactiveLayer(child, updateMapAndLayerControls, true);
            }
        }
    }
    refreshContextualMenu();
}
Also used : HasMapLayer(au.org.emii.portal.menu.HasMapLayer) MapLayer(au.org.emii.portal.menu.MapLayer) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) RemoteMap(au.org.emii.portal.util.RemoteMap)

Example 3 with UserDataDTO

use of au.org.ala.spatial.dto.UserDataDTO in project spatial-portal by AtlasOfLivingAustralia.

the class ToolComposer method onUpload$fileUpload.

public void onUpload$fileUpload(Event event) {
    UploadEvent ue = null;
    UserDataDTO ud = null;
    if (event instanceof UploadEvent) {
        ue = (UploadEvent) event;
    } else if (event instanceof ForwardEvent) {
        ue = (UploadEvent) ((ForwardEvent) event).getOrigin();
    }
    Media m = ue.getMedia();
    if (ud == null) {
        ud = new UserDataDTO(m.getName());
    }
    if (ud.getName().trim().isEmpty()) {
        ud.setName(m.getName());
    }
    ud.setFilename(m.getName());
    if (ud.getName() == null || ud.getName().length() == 0) {
        ud.setName(m.getName());
    }
    if (ud.getDescription() == null || ud.getDescription().length() == 0) {
        ud.setDescription(m.getName());
    }
    ud.setUploadedTimeInMs(System.currentTimeMillis());
    UploadSpeciesController usc = (UploadSpeciesController) Executions.createComponents("WEB-INF/zul/input/UploadSpecies.zul", this, null);
    usc.setAddToMap(false);
    if (rgSpeciesBk != null) {
        if (rgSpeciesBk.getSelectedItem() == rSpeciesUploadLSIDBk) {
            usc.setUploadType(StringConstants.ASSEMBLAGE_BK);
        } else if (rgSpeciesBk.getSelectedItem() == rSpeciesUploadSpeciesBk) {
            usc.setUploadType("bk");
        }
    }
    usc.setVisible(false);
    usc.doOverlapped();
    usc.doFileUpload(ud, event);
    usc.detach();
}
Also used : UploadSpeciesController(au.org.ala.spatial.composer.input.UploadSpeciesController) Media(org.zkoss.util.media.Media) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO)

Example 4 with UserDataDTO

use of au.org.ala.spatial.dto.UserDataDTO in project spatial-portal by AtlasOfLivingAustralia.

the class AreaUploadShapefileWizardController method loadOnMap.

private void loadOnMap(Set<FeatureId> ids, String filename) {
    try {
        final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
        Filter filter = ff.id(ids);
        // set up the math transform used to process the data
        SimpleFeatureType schema = features.getSchema();
        CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
        CoordinateReferenceSystem wgsCRS = DefaultGeographicCRS.WGS84;
        // allow for some error due to different datums
        boolean lenient = true;
        if (dataCRS == null) {
            // attempt to parse prj
            try {
                File prjFile = new File(filename.substring(0, filename.length() - 3) + "prj");
                if (prjFile.exists()) {
                    String prj = FileUtils.readFileToString(prjFile);
                    if (prj.equals("PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0]]")) {
                        // support for arcgis online default shp exports
                        dataCRS = CRS.decode("EPSG:3857");
                    } else {
                        dataCRS = CRS.parseWKT(FileUtils.readFileToString(prjFile));
                    }
                }
            } catch (Exception e) {
                LOGGER.error("failed to read prj for " + filename);
            }
            if (dataCRS == null) {
                dataCRS = DefaultGeographicCRS.WGS84;
            }
        }
        MathTransform transform = CRS.findMathTransform(dataCRS, wgsCRS, lenient);
        SimpleFeatureCollection sff = source.getFeatures(filter);
        SimpleFeatureIterator fif = sff.features();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbGeometryCollection = new StringBuilder();
        boolean isGeometryCollection = false;
        List<Geometry> geoms = new ArrayList<Geometry>();
        while (fif.hasNext()) {
            SimpleFeature f = fif.next();
            LOGGER.debug("Selected Feature: " + f.getID() + " -> " + f.getAttribute("ECOREGION"));
            Geometry geom = (Geometry) f.getDefaultGeometry();
            geom = JTS.transform(geom, transform);
            String wktString = geom.toText();
            wktString = wktString.replaceAll(", ", ",");
            boolean valid = true;
            boolean multipolygon = false;
            boolean polygon = false;
            boolean geometrycollection = false;
            if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
                wktString = wktString.substring((StringConstants.MULTIPOLYGON + " ").length(), wktString.length() - 1);
                multipolygon = true;
            } else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
                wktString = wktString.substring((StringConstants.POLYGON + " ").length());
                polygon = true;
            } else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
                wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
                geometrycollection = true;
                isGeometryCollection = true;
            } else {
                valid = false;
            }
            if (valid) {
                if (sb.length() > 0) {
                    sb.append(",");
                    sbGeometryCollection.append(",");
                }
                sb.append(wktString);
                if (multipolygon) {
                    sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
                    if (!wktString.endsWith(")))")) {
                        sbGeometryCollection.append(")");
                    }
                } else if (polygon) {
                    sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
                } else if (geometrycollection) {
                    sbGeometryCollection.append(wktString);
                }
            }
        }
        String wkt;
        if (!isGeometryCollection) {
            if (!sb.toString().contains(")))")) {
                sb.append(")");
            }
            wkt = StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "((");
        } else {
            sbGeometryCollection.append(")");
            wkt = StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection.toString();
            getMapComposer().showMessage("Shape is invalid: " + "GEOMETRYCOLLECTION not supported.");
        }
        GeometryFactory gf = new GeometryFactory();
        gf.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
        String msg = "";
        boolean invalid = false;
        try {
            WKTReader wktReader = new WKTReader();
            com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
            // NC 20130319: Ensure that the WKT is valid according to the WKT standards.
            IsValidOp op = new IsValidOp(g);
            if (!op.isValid()) {
                // this will fix some issues
                g = g.buffer(0);
                op = new IsValidOp(g);
            }
            if (!op.isValid()) {
                invalid = true;
                LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
                msg = op.getValidationError().getMessage();
            // TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
            } else if (g.isRectangle()) {
                // NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
                // get the new WKT for the rectangle will possibly need to change the order.
                com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
                String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
                if (!wkt.equals(wkt2)) {
                    LOGGER.debug("NEW WKT for Rectangle: " + wkt);
                    msg = CommonData.lang("error_wkt_anticlockwise");
                    invalid = true;
                }
            }
            if (!invalid) {
                invalid = !op.isValid();
            }
        } catch (ParseException parseException) {
            LOGGER.error("error testing validity of uploaded shape file wkt", parseException);
        }
        if (invalid) {
            getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
        } else {
            MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layername, layername);
            UserDataDTO ud = new UserDataDTO(layername);
            ud.setFilename(media.getName());
            ud.setUploadedTimeInMs(System.currentTimeMillis());
            ud.setType("shapefile");
            String metadata = "";
            metadata += "User uploaded Shapefile \n";
            metadata += "Name: " + ud.getName() + " <br />\n";
            metadata += "Filename: " + ud.getFilename() + " <br />\n";
            metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
            metadata += "Selected polygons (fid): <br />\n";
            metadata += "<ul>";
            metadata += "</ul>";
            mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
            getMapComposer().replaceWKTwithWMS(mapLayer);
        }
    } catch (IOException e) {
        LOGGER.debug("IO Error retrieving geometry", e);
    } catch (Exception e) {
        LOGGER.debug("Generic Error retrieving geometry", e);
    }
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) MathTransform(org.opengis.referencing.operation.MathTransform) MapLayer(au.org.emii.portal.menu.MapLayer) WKTReader(com.vividsolutions.jts.io.WKTReader) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) FilterFactory(org.opengis.filter.FilterFactory) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) IOException(java.io.IOException) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Filter(org.opengis.filter.Filter) IsValidOp(com.vividsolutions.jts.operation.valid.IsValidOp) ParseException(com.vividsolutions.jts.io.ParseException) File(java.io.File)

Example 5 with UserDataDTO

use of au.org.ala.spatial.dto.UserDataDTO in project spatial-portal by AtlasOfLivingAustralia.

the class UploadSpeciesController method afterCompose.

@Override
public void afterCompose() {
    super.afterCompose();
    setTbInstructions("3. Select file (text file, one LSID or name per line)");
    Map m = Executions.getCurrent().getArg();
    if (m != null) {
        for (Object o : m.entrySet()) {
            if (((Map.Entry) o).getKey() instanceof String && "setTbInstructions".equals(((Map.Entry) o).getKey())) {
                setTbInstructions((String) ((Map.Entry) o).getValue());
            }
            if (((Map.Entry) o).getKey() instanceof String && "addToMap".equals(((Map.Entry) o).getKey())) {
                addToMap = true;
            }
        }
    }
    tbName.setConstraint(new Constraint() {

        @Override
        public void validate(Component comp, Object value) {
            String val = (String) value;
            Map htUserSpecies = (Map) getMapComposer().getSession().getAttribute(StringConstants.USERPOINTS);
            if (htUserSpecies != null && !htUserSpecies.isEmpty()) {
                for (Object o : htUserSpecies.values()) {
                    if (((UserDataDTO) o).getName().equalsIgnoreCase(val.trim())) {
                        throw new WrongValueException(comp, "User dataset named '" + val + "' already exists. Please enter another name for your dataset.");
                    }
                }
            }
        }
    });
    fileUpload.addEventListener("onUpload", new EventListener() {

        public void onEvent(Event event) throws Exception {
            UserDataDTO ud = new UserDataDTO(tbName.getValue(), tbDesc.getValue(), "points");
            addToMap = true;
            defineArea = true;
            doFileUpload(ud, event);
            onClick$btnCancel(null);
        }
    });
}
Also used : Event(org.zkoss.zk.ui.event.Event) ForwardEvent(org.zkoss.zk.ui.event.ForwardEvent) UploadEvent(org.zkoss.zk.ui.event.UploadEvent) JSONObject(org.json.simple.JSONObject) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) EventListener(org.zkoss.zk.ui.event.EventListener) Component(org.zkoss.zk.ui.Component) Map(java.util.Map) WrongValueException(org.zkoss.zk.ui.WrongValueException) WrongValueException(org.zkoss.zk.ui.WrongValueException)

Aggregations

UserDataDTO (au.org.ala.spatial.dto.UserDataDTO)8 MapLayer (au.org.emii.portal.menu.MapLayer)3 Geometry (com.vividsolutions.jts.geom.Geometry)3 Map (java.util.Map)3 Media (org.zkoss.util.media.Media)3 WrongValueException (org.zkoss.zk.ui.WrongValueException)3 UploadEvent (org.zkoss.zk.ui.event.UploadEvent)3 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)2 ParseException (com.vividsolutions.jts.io.ParseException)2 WKTReader (com.vividsolutions.jts.io.WKTReader)2 IsValidOp (com.vividsolutions.jts.operation.valid.IsValidOp)2 File (java.io.File)2 StringReader (java.io.StringReader)2 SimpleFeature (org.opengis.feature.simple.SimpleFeature)2 ForwardEvent (org.zkoss.zk.ui.event.ForwardEvent)2 Facet (au.org.ala.legend.Facet)1 UploadSpeciesController (au.org.ala.spatial.composer.input.UploadSpeciesController)1 HasMapLayer (au.org.emii.portal.menu.HasMapLayer)1 SelectedArea (au.org.emii.portal.menu.SelectedArea)1 RemoteMap (au.org.emii.portal.util.RemoteMap)1