Search in sources :

Example 6 with UserDataDTO

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

the class UploadSpeciesController method doFileUpload.

public void doFileUpload(UserDataDTO ud, Event event) {
    UploadEvent ue = null;
    if (event instanceof UploadEvent) {
        ue = (UploadEvent) event;
    } else if (event instanceof ForwardEvent) {
        ue = (UploadEvent) ((ForwardEvent) event).getOrigin();
    }
    if (ue == null) {
        LOGGER.debug("unable to upload file");
        return;
    } else {
        LOGGER.debug("fileUploaded()");
    }
    try {
        Media m = ue.getMedia();
        UserDataDTO u = ud;
        if (u == null) {
            u = new UserDataDTO(m.getName());
        }
        if (u.getName().trim().isEmpty()) {
            u.setName(m.getName());
        }
        u.setFilename(m.getName());
        if (u.getName() == null || u.getName().length() == 0) {
            u.setName(m.getName());
        }
        if (u.getDescription() == null || u.getDescription().length() == 0) {
            u.setDescription(m.getName());
        }
        u.setUploadedTimeInMs(System.currentTimeMillis());
        LOGGER.debug("Got file '" + u.getName() + "' with type '" + m.getContentType() + "'");
        //forget content types, do 'try'
        boolean loaded = false;
        try {
            loadUserPoints(u, m.getReaderData(), addToMap, tbName.getText(), tbDesc.getText(), getMapComposer(), eventListener);
            loaded = true;
            LOGGER.debug("read type " + m.getContentType() + " with getReaderData");
        } catch (Exception e) {
        //failed to read uploaded data, will try another method
        }
        if (!loaded) {
            try {
                loadUserPoints(u, new StringReader(new String(m.getByteData())), addToMap, tbName.getText(), tbDesc.getText(), getMapComposer(), eventListener);
                loaded = true;
                LOGGER.debug("read type " + m.getContentType() + " with getByteData");
            } catch (Exception e) {
            //failed to read uploaded data, will try another method
            }
        }
        if (!loaded) {
            try {
                loadUserPoints(u, new InputStreamReader(m.getStreamData()), addToMap, tbName.getText(), tbDesc.getText(), getMapComposer(), eventListener);
                loaded = true;
                LOGGER.debug("read type " + m.getContentType() + " with getStreamData");
            } catch (Exception e) {
            //failed to read uploaded data, will try another method
            }
        }
        if (!loaded) {
            try {
                loadUserPoints(u, new StringReader(m.getStringData()), addToMap, tbName.getText(), tbDesc.getText(), getMapComposer(), eventListener);
                LOGGER.debug("read type " + m.getContentType() + " with getStringData");
            } catch (Exception e) {
                //last one, report error
                getMapComposer().showMessage("Unable to load your file. Please try again.");
                LOGGER.error("unable to load user points: ", e);
            }
        }
        //call reset window on caller to perform refresh'
        if (callback != null) {
            try {
                callback.onEvent(new ForwardEvent("", null, null, new String[] { uploadLSID, uploadType }));
            } catch (Exception e) {
                LOGGER.error("failed to cancel species points upload", e);
            }
        }
    } catch (Exception ex) {
        LOGGER.error("unable to load user points", ex);
    }
}
Also used : ForwardEvent(org.zkoss.zk.ui.event.ForwardEvent) InputStreamReader(java.io.InputStreamReader) Media(org.zkoss.util.media.Media) StringReader(java.io.StringReader) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) WrongValueException(org.zkoss.zk.ui.WrongValueException) UploadEvent(org.zkoss.zk.ui.event.UploadEvent)

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

Example 8 with UserDataDTO

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

the class PointGenerationComposer method onFinish.

@Override
public boolean onFinish() {
    SelectedArea sa = getSelectedArea();
    double[][] bbox = null;
    if (sa.getMapLayer() != null && sa.getMapLayer().getMapLayerMetadata() != null) {
        List<Double> bb = sa.getMapLayer().getMapLayerMetadata().getBbox();
        bbox = new double[2][2];
        bbox[0][0] = bb.get(0);
        bbox[0][1] = bb.get(1);
        bbox[1][0] = bb.get(2);
        bbox[1][1] = bb.get(3);
    } else {
        List<Double> bb = Util.getBoundingBox(sa.getWkt());
        bbox = new double[][] { { bb.get(0), bb.get(1) }, { bb.get(2), bb.get(3) } };
    }
    //with bounding box, cut points
    try {
        String wkt = (sa.getMapLayer() != null ? sa.getMapLayer().getWKT() : sa.getWkt());
        StringBuilder sb = new StringBuilder();
        sb.append("longitude,latitude");
        int count = 0;
        int width = (int) Math.ceil((bbox[1][0] - bbox[0][0]) / resolution.getValue());
        int height = (int) Math.ceil((bbox[1][1] - bbox[0][1]) / resolution.getValue());
        double startx = Math.floor(bbox[0][0] / resolution.getValue()) * resolution.getValue();
        double starty = Math.floor(bbox[0][1] / resolution.getValue()) * resolution.getValue();
        if (wkt == null) {
            if (sa.getFacets() != null) {
                double[][] points = new double[(width + 1) * (height + 1)][2];
                int pos = 0;
                for (int i = 0; i <= width; i++) {
                    for (int j = 0; j <= height; j++) {
                        double lng = startx + i * resolution.getValue();
                        double lat = starty + j * resolution.getValue();
                        points[pos][0] = lng;
                        points[pos][1] = lat;
                        pos = pos + 1;
                    }
                }
                List<String> fields = new ArrayList<String>();
                for (Facet f : sa.getFacets()) {
                    fields.add(f.getFields()[0]);
                }
                List<String[]> result = Sampling.sampling(fields, points);
                for (int i = 0; i < result.size(); i++) {
                    Facet f = sa.getFacets().get(i);
                    String[] intersection = result.get(i);
                    for (int j = 0; j < intersection.length; j++) {
                        if (f.isValid("\"" + intersection[j] + "\"")) {
                            sb.append("\n");
                            sb.append(points[j][0]).append(",").append(points[j][1]);
                            count++;
                        }
                    }
                }
            } else {
                LOGGER.error("invalid area selected for point generation");
                getMapComposer().showMessage("Unsupported area selected for point generation. Choose a different area.");
                return false;
            }
        } else {
            //write temporary shapefile
            File tmp = File.createTempFile("tmp", ".shp");
            ShapefileUtils.saveShapefile(tmp, wkt, "tmp");
            FileDataStore store = FileDataStoreFinder.getDataStore(tmp);
            FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
            FeatureCollection featureCollection = featureSource.getFeatures();
            GeometryFactory gf = new GeometryFactory();
            List<Geometry> geometry = new ArrayList<Geometry>();
            FeatureIterator it = featureCollection.features();
            while (it.hasNext()) {
                SimpleFeature feature = (SimpleFeature) it.next();
                geometry.add((Geometry) feature.getDefaultGeometry());
            }
            try {
                it.close();
            } catch (Exception e) {
            }
            for (int i = 0; i <= width; i++) {
                for (int j = 0; j <= height; j++) {
                    double lng = startx + i * resolution.getValue();
                    double lat = starty + j * resolution.getValue();
                    Coordinate c = new Coordinate(lng, lat);
                    Geometry point = gf.createPoint(c);
                    for (Geometry geom : geometry) {
                        if (geom.contains(point)) {
                            sb.append("\n");
                            sb.append(lng).append(",").append(lat);
                            count++;
                        }
                    }
                }
            }
            //close tmp file
            try {
                store.dispose();
            } catch (Exception e) {
            }
            //delete tmp files
            try {
                FileUtils.deleteQuietly(tmp);
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".shx")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".fix")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".dbf")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".prj")));
            } catch (Exception e) {
            }
        }
        if (count <= 0) {
            getMapComposer().showMessage("No points generated. Try again with a smaller resolution or larger area.");
        } else if (count > Integer.parseInt(CommonData.getSettings().getProperty("max_record_count_upload"))) {
            getMapComposer().showMessage(count + " points generated. Maximum is " + CommonData.getSettings().getProperty("generated_points_max") + ".\n" + "Try again with a larger resolution or smaller area.");
        } else {
            String name = tToolName.getValue();
            try {
                UploadSpeciesController.loadUserPoints(new UserDataDTO(name), new StringReader(sb.toString()), true, name, "points in " + getSelectedAreaDisplayName() + " on " + resolution.getValue() + " degree resolution grid.", getMapComposer(), null);
                detach();
                return true;
            } catch (Exception e) {
                LOGGER.error("failed to upload points");
            }
        }
    } catch (Exception e) {
    }
    return false;
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) SelectedArea(au.org.emii.portal.menu.SelectedArea) ArrayList(java.util.ArrayList) FeatureIterator(org.geotools.feature.FeatureIterator) StringReader(java.io.StringReader) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) FileDataStore(org.geotools.data.FileDataStore) Facet(au.org.ala.legend.Facet) FeatureSource(org.geotools.data.FeatureSource) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(com.vividsolutions.jts.geom.Geometry) FeatureCollection(org.geotools.feature.FeatureCollection) Coordinate(com.vividsolutions.jts.geom.Coordinate) File(java.io.File)

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