public static final boolean acceptsXmlNeptuneFile(File file, URL schemaURL) {

    if (schemaURL == null) {
      schemaURL = schemas.get(0);
    }

    try (FileInputStream in = new FileInputStream(file)) {
      Source xmlFile = new StreamSource(in);
      try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaURL);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
        Main.info(xmlFile.getSystemId() + " is valid");
        return true;
      } catch (SAXException e) {
        Main.error(xmlFile.getSystemId() + " is NOT valid");
        Main.error("Reason: " + e.getLocalizedMessage());
      } catch (IOException e) {
        Main.error(xmlFile.getSystemId() + " is NOT valid");
        Main.error("Reason: " + e.getLocalizedMessage());
      }
    } catch (IOException e) {
      Main.error(e.getMessage());
    }

    return false;
  }
    protected void uploadLayers(List<SaveLayerInfo> toUpload) {
      for (final SaveLayerInfo layerInfo : toUpload) {
        AbstractModifiableLayer layer = layerInfo.getLayer();
        if (canceled) {
          model.setUploadState(layer, UploadOrSaveState.CANCELED);
          continue;
        }
        monitor.subTask(tr("Preparing layer ''{0}'' for upload ...", layerInfo.getName()));

        if (!UploadAction.checkPreUploadConditions(layer)) {
          model.setUploadState(layer, UploadOrSaveState.FAILED);
          continue;
        }

        AbstractUploadDialog dialog = layer.getUploadDialog();
        if (dialog != null) {
          dialog.setVisible(true);
          if (dialog.isCanceled()) {
            model.setUploadState(layer, UploadOrSaveState.CANCELED);
            continue;
          }
          dialog.rememberUserInput();
        }

        currentTask = layer.createUploadTask(monitor);
        if (currentTask == null) {
          model.setUploadState(layer, UploadOrSaveState.FAILED);
          continue;
        }
        currentFuture = worker.submit(currentTask);
        try {
          // wait for the asynchronous task to complete
          //
          currentFuture.get();
        } catch (CancellationException e) {
          Main.trace(e);
          model.setUploadState(layer, UploadOrSaveState.CANCELED);
        } catch (InterruptedException | ExecutionException e) {
          Main.error(e);
          model.setUploadState(layer, UploadOrSaveState.FAILED);
          ExceptionDialogUtil.explainException(e);
        }
        if (currentTask.isCanceled()) {
          model.setUploadState(layer, UploadOrSaveState.CANCELED);
        } else if (currentTask.isFailed()) {
          Main.error(currentTask.getLastException());
          ExceptionDialogUtil.explainException(currentTask.getLastException());
          model.setUploadState(layer, UploadOrSaveState.FAILED);
        } else {
          model.setUploadState(layer, UploadOrSaveState.OK);
        }
        currentTask = null;
        currentFuture = null;
      }
    }
Exemple #3
0
 /** Detect starting elements. */
 @Override
 public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
     throws SAXException {
   depth++;
   try {
     if ("searchresults".equals(qName)) {
       // do nothing
     } else if ("named".equals(qName) && (depth == 2)) {
       currentResult = new PlaceSelection.SearchResult();
       currentResult.name = atts.getValue("name");
       currentResult.info = atts.getValue("info");
       if (currentResult.info != null) {
         currentResult.info = tr(currentResult.info);
       }
       currentResult.lat = Double.parseDouble(atts.getValue("lat"));
       currentResult.lon = Double.parseDouble(atts.getValue("lon"));
       currentResult.zoom = Integer.parseInt(atts.getValue("zoom"));
       data.add(currentResult);
     } else if ("description".equals(qName) && (depth == 3)) {
       description = new StringBuilder();
     } else if ("named".equals(qName) && (depth == 4)) {
       // this is a "named" place in the nearest places list.
       String info = atts.getValue("info");
       if ("city".equals(info) || "town".equals(info) || "village".equals(info)) {
         currentResult.nearestPlace = atts.getValue("name");
       }
     } else if ("place".equals(qName) && atts.getValue("lat") != null) {
       currentResult = new PlaceSelection.SearchResult();
       currentResult.name = atts.getValue("display_name");
       currentResult.description = currentResult.name;
       currentResult.info = atts.getValue("class");
       if (currentResult.info != null) {
         currentResult.info = tr(currentResult.info);
       }
       currentResult.nearestPlace = tr(atts.getValue("type"));
       currentResult.lat = Double.parseDouble(atts.getValue("lat"));
       currentResult.lon = Double.parseDouble(atts.getValue("lon"));
       String[] bbox = atts.getValue("boundingbox").split(",");
       currentResult.bounds =
           new Bounds(
               Double.parseDouble(bbox[0]), Double.parseDouble(bbox[2]),
               Double.parseDouble(bbox[1]), Double.parseDouble(bbox[3]));
       data.add(currentResult);
     }
   } catch (NumberFormatException x) {
     Main.error(x); // SAXException does not chain correctly
     throw new SAXException(x.getMessage(), x);
   } catch (NullPointerException x) {
     Main.error(x); // SAXException does not chain correctly
     throw new SAXException(tr("Null pointer exception, possibly some missing tags."), x);
   }
 }
 @Override
 public synchronized void loadingFinished(
     CacheEntry data, CacheEntryAttributes attributes, LoadResult result) {
   try {
     synchronized (this.getClass()) {
       this.queue.put(ImageIO.read(new ByteArrayInputStream(data.getContent())));
       this.queueImages.put(this.image);
     }
   } catch (InterruptedException e) {
     Main.error(e);
   } catch (IOException e) {
     Main.error(e);
   }
 }
 private synchronized void waitNotification() {
   try {
     wait();
   } catch (InterruptedException e) {
     Main.error(e);
   }
 }
    @Override
    protected void parse(HeaderBlock header) {

      for (String requiredFeature : header.getRequiredFeaturesList()) {
        switch (requiredFeature) {
          case "OsmSchema-V0.6":
            ds.setVersion("0.6");
            break;
          case "DenseNodes":
            break;
          default:
            throw new UnsupportedOperationException("Unsupported feature: " + requiredFeature);
        }
      }

      HeaderBBox bbox = header.getBbox();
      if (bbox != null) {
        double minlat = parseRawDegrees(bbox.getBottom());
        double minlon = parseRawDegrees(bbox.getLeft());
        double maxlat = parseRawDegrees(bbox.getTop());
        double maxlon = parseRawDegrees(bbox.getRight());
        Bounds b = new Bounds(minlat, minlon, maxlat, maxlon);
        if (!b.isCollapsed() && areCoordinatesValid(minlat, minlon, maxlat, maxlon)) {
          ds.dataSources.add(new DataSource(b, header.getSource()));
        } else {
          Main.error("Invalid Bounds: " + b);
        }
      }
    }
    protected void saveLayers(List<SaveLayerInfo> toSave) {
      for (final SaveLayerInfo layerInfo : toSave) {
        if (canceled) {
          model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.CANCELED);
          continue;
        }
        // Check save preconditions earlier to avoid a blocking reentring call to EDT (see #10086)
        if (layerInfo.isDoCheckSaveConditions()) {
          if (!layerInfo.getLayer().checkSaveConditions()) {
            continue;
          }
          layerInfo.setDoCheckSaveConditions(false);
        }
        currentTask = new SaveLayerTask(layerInfo, monitor);
        currentFuture = worker.submit(currentTask);

        try {
          // wait for the asynchronous task to complete
          //
          currentFuture.get();
        } catch (CancellationException e) {
          Main.trace(e);
          model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.CANCELED);
        } catch (InterruptedException | ExecutionException e) {
          Main.error(e);
          model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.FAILED);
          ExceptionDialogUtil.explainException(e);
        }
        if (currentTask.isCanceled()) {
          model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.CANCELED);
        } else if (currentTask.isFailed()) {
          if (currentTask.getLastException() != null) {
            Main.error(currentTask.getLastException());
            ExceptionDialogUtil.explainException(currentTask.getLastException());
          }
          model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.FAILED);
        } else {
          model.setSaveState(layerInfo.getLayer(), UploadOrSaveState.OK);
        }
        this.currentTask = null;
        this.currentFuture = null;
      }
    }
  public void actionPerformed(GpsActionEvent event) {
    String markerTitle = getParameters().get(0);
    Object source = event.getSource();
    if (source instanceof JToggleButton) {
      if (((JToggleButton) source).isSelected()) {
        markerTitle = tr("{0} start", markerTitle);
      } else {
        markerTitle = tr("{0} end", markerTitle);
      }
    }

    String iconName = getParameters().size() > 1 ? getParameters().get(1).trim() : null;

    long timeout = DialogClosingThread.DEFAULT_TIMEOUT;
    if (getParameters().size() > 2) {
      try {
        timeout = Integer.parseInt(getParameters().get(2));
      } catch (NumberFormatException e) {
        Main.error(e.getMessage());
      }
    }

    String markerText = markerTitle;

    if (timeout > 0) {
      if (dialog == null) {
        dialog = new WaypointDialog();
      }

      String inputText =
          dialog.openDialog(
              SurveyorPlugin.getSurveyorFrame(), tr("Waypoint Description"), timeout * 1000);
      if (inputText != null && inputText.length() > 0) {
        inputText = inputText.replaceAll("<", "_"); // otherwise the gpx file is ruined
        markerText = markerText + " " + inputText;
      }
    }

    // add the waypoint to the marker layer AND to the gpx layer
    // (easy export of data + waypoints):
    MarkerLayer layer = getMarkerLayer();
    GpxLayer gpsLayer = getGpxLayer();
    WayPoint waypoint = new WayPoint(event.getCoordinates());
    waypoint.attr.put("name", markerText);
    if (iconName != null && !iconName.isEmpty()) waypoint.attr.put("sym", iconName);
    synchronized (SurveyorLock.class) {
      layer.data.add(new Marker(event.getCoordinates(), markerText, iconName, null, -1.0, 0.0));
      if (gpsLayer != null) {
        gpsLayer.data.waypoints.add(waypoint);
      }
    }

    Main.map.repaint();
  }
  public void selectFeatures(int x, int y) {
    int pixelDelta = 2;
    LatLon clickUL = Main.map.mapView.getLatLon(x - pixelDelta, y - pixelDelta);
    LatLon clickLR = Main.map.mapView.getLatLon(x + pixelDelta, y + pixelDelta);

    Envelope envelope =
        new Envelope(
            Math.min(clickUL.lon(), clickLR.lon()),
            Math.max(clickUL.lon(), clickLR.lon()),
            Math.min(clickUL.lat(), clickLR.lat()),
            Math.max(clickUL.lat(), clickLR.lat()));

    ReferencedEnvelope mapArea = new ReferencedEnvelope(envelope, crsOSMI);

    Intersects filter = ff.intersects(ff.property("msGeometry"), ff.literal(mapArea));
    //
    // Select features in all layers
    //
    content.layers().clear();

    // Iterate through features and build a list that intersects the above
    // envelope
    for (int idx = 0; idx < arrFeatures.size(); ++idx) {
      OSMIFeatureTracker tracker = arrFeatures.get(idx);
      FeatureCollection<SimpleFeatureType, SimpleFeature> features = tracker.getFeatures();

      SimpleFeatureSource tempfs = DataUtilities.source(features);
      FeatureCollection<SimpleFeatureType, SimpleFeature> selectedFeatures;

      try {
        selectedFeatures = tempfs.getFeatures(filter);
        Set<FeatureId> IDs = new HashSet<>();

        try (FeatureIterator<SimpleFeature> iter = selectedFeatures.features()) {

          Main.info("Selected features " + selectedFeatures.size());

          while (iter.hasNext()) {
            SimpleFeature feature = iter.next();
            IDs.add(feature.getIdentifier());
          }
        }

        geometryType = selectGeomType.get(idx + layerOffset);
        Style style = createDefaultStyle(idx + layerOffset, IDs);
        content.addLayer(new FeatureLayer(features, style));
      } catch (IOException e) {
        Main.error(e);
      }
    }

    bIsChanged = true;
  }
 private static Class<?> loadRendererClass(String className) {
   for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
     try {
       return Class.forName(className, true, cl);
     } catch (final NoClassDefFoundError | ClassNotFoundException e) {
       Main.trace(e.getMessage());
     }
   }
   Main.error(
       tr("Failed to load map renderer class ''{0}''. The class wasn''t found.", className));
   return null;
 }
 private void activateMapRenderer(String rendererClassName) {
   Class<?> c = loadRendererClass(rendererClassName);
   if (c == null) {
     Main.error(
         tr(
             "Can''t activate map renderer class ''{0}'', because the class wasn''t found.",
             rendererClassName));
     Main.error(tr("Activating the standard map renderer instead."));
     activateDefault();
   } else if (!AbstractMapRenderer.class.isAssignableFrom(c)) {
     Main.error(
         tr(
             "Can''t activate map renderer class ''{0}'', because it isn''t a subclass of ''{1}''.",
             rendererClassName, AbstractMapRenderer.class.getName()));
     Main.error(tr("Activating the standard map renderer instead."));
     activateDefault();
   } else {
     Class<? extends AbstractMapRenderer> renderer = c.asSubclass(AbstractMapRenderer.class);
     if (!isRegistered(renderer)) {
       Main.error(
           tr(
               "Can''t activate map renderer class ''{0}'', because it isn''t registered as map renderer.",
               rendererClassName));
       Main.error(tr("Activating the standard map renderer instead."));
       activateDefault();
     } else {
       activate(renderer);
     }
   }
 }
Exemple #12
0
 /**
  * Determines if all conditions match the given environment.
  *
  * @param env The environment to check
  * @return {@code true} if all conditions apply, false otherwise.
  */
 @Override
 public boolean matches(Environment env) {
   if (conds == null) return true;
   for (Condition c : conds) {
     try {
       if (!c.applies(env)) return false;
     } catch (PatternSyntaxException e) {
       Main.error("PatternSyntaxException while applying condition" + c + ": " + e.getMessage());
       return false;
     }
   }
   return true;
 }
Exemple #13
0
 private static Node parseModel(Reader r) {
   StreamTokenizer st = new StreamTokenizer(r);
   try {
     Split root = new Split();
     parseSplit(st, root);
     return root.getChildren().get(0);
   } catch (Exception e) {
     Main.error(e);
   } finally {
     Utils.close(r);
   }
   return null;
 }
Exemple #14
0
 /**
  * FOR PLATFORMHOOK USE ONLY.
  *
  * <p>This registers a system shortcut. See PlatformHook for details.
  *
  * @param shortText an ID. re-use a {@code "system:*"} ID if possible, else use something unique.
  * @param longText this will be displayed in the shortcut preferences dialog. Better use something
  *     the user will recognize...
  * @param key the key. Use a {@link KeyEvent KeyEvent.VK_*} constant here.
  * @param modifier the modifier. Use a {@link KeyEvent KeyEvent.*_MASK} constant here.
  * @return the system shortcut
  */
 public static Shortcut registerSystemShortcut(
     String shortText, String longText, int key, int modifier) {
   if (shortcuts.containsKey(shortText)) return shortcuts.get(shortText);
   Shortcut potentialShortcut = findShortcut(key, modifier);
   if (potentialShortcut != null) {
     // this always is a logic error in the hook
     Main.error("CONFLICT WITH SYSTEM KEY " + shortText);
     return null;
   }
   potentialShortcut =
       new Shortcut(shortText, longText, key, RESERVED, key, modifier, true, false);
   shortcuts.put(shortText, potentialShortcut);
   return potentialShortcut;
 }
Exemple #15
0
  @Override
  public void importData(File file, ProgressMonitor progressMonitor) throws IOException {
    final String fileName = file.getName();

    try (InputStream is = Compression.getUncompressedFileInputStream(file)) {
      GpxReader r = new GpxReader(is);
      boolean parsedProperly = r.parse(true);
      r.getGpxData().storageFile = file;
      addLayers(
          loadLayers(r.getGpxData(), parsedProperly, fileName, tr("Markers from {0}", fileName)));
    } catch (SAXException e) {
      Main.error(e);
      throw new IOException(tr("Parsing data for layer ''{0}'' failed", fileName), e);
    }
  }
Exemple #16
0
 public static GpxImporterData loadLayers(
     InputStream is,
     final File associatedFile,
     final String gpxLayerName,
     String markerLayerName,
     ProgressMonitor progressMonitor)
     throws IOException {
   try {
     final GpxReader r = new GpxReader(is);
     final boolean parsedProperly = r.parse(true);
     r.getGpxData().storageFile = associatedFile;
     return loadLayers(r.getGpxData(), parsedProperly, gpxLayerName, markerLayerName);
   } catch (SAXException e) {
     Main.error(e);
     throw new IOException(tr("Parsing data for layer ''{0}'' failed", gpxLayerName), e);
   }
 }
Exemple #17
0
    private void addRecursiveFiles(Collection<File> files, Collection<File> sel) {
      boolean nullFile = false;

      for (File f : sel) {

        if (canceled) {
          break;
        }

        if (f == null) {
          nullFile = true;

        } else if (f.isDirectory()) {
          String canonical = null;
          try {
            canonical = f.getCanonicalPath();
          } catch (IOException e) {
            Main.error(e);
            rememberError(
                tr("Unable to get canonical path for directory {0}\n", f.getAbsolutePath()));
          }

          if (canonical == null || loadedDirectories.contains(canonical)) {
            continue;
          } else {
            loadedDirectories.add(canonical);
          }

          File[] children = f.listFiles(JpgImporter.FILE_FILTER_WITH_FOLDERS);
          if (children != null) {
            progressMonitor.subTask(tr("Scanning directory {0}", f.getPath()));
            addRecursiveFiles(files, Arrays.asList(children));
          } else {
            rememberError(tr("Error while getting files from directory {0}\n", f.getPath()));
          }

        } else {
          files.add(f);
        }
      }

      if (nullFile) {
        throw new IllegalStateException(tr("One of the selected files was null"));
      }
    }
 /**
  * When the pictures are returned from the cache, they are set in the {@link
  * MapillaryImageDisplay} object.
  */
 @Override
 public void loadingFinished(
     final CacheEntry data, final CacheEntryAttributes attributes, final LoadResult result) {
   if (!SwingUtilities.isEventDispatchThread()) {
     SwingUtilities.invokeLater(() -> loadingFinished(data, attributes, result));
   } else if (data != null && result == LoadResult.SUCCESS) {
     try {
       BufferedImage img = ImageIO.read(new ByteArrayInputStream(data.getContent()));
       if (img == null) {
         return;
       }
       if (mapillaryImageDisplay.getImage() == null
           || img.getHeight() > this.mapillaryImageDisplay.getImage().getHeight()) {
         this.mapillaryImageDisplay.setImage(img);
       }
     } catch (IOException e) {
       Main.error(e);
     }
   }
 }
Exemple #19
0
 /**
  * Builds the style sheet used in the internal help browser
  *
  * @return the style sheet
  */
 protected StyleSheet buildStyleSheet() {
   StyleSheet ss = new StyleSheet();
   BufferedReader reader =
       new BufferedReader(
           new InputStreamReader(getClass().getResourceAsStream("/data/help-browser.css")));
   StringBuffer css = new StringBuffer();
   try {
     String line = null;
     while ((line = reader.readLine()) != null) {
       css.append(line);
       css.append("\n");
     }
   } catch (Exception e) {
     Main.error(
         tr("Failed to read CSS file ''help-browser.css''. Exception is: {0}", e.toString()));
     e.printStackTrace();
     return ss;
   } finally {
     Utils.close(reader);
   }
   ss.addRule(css.toString());
   return ss;
 }
Exemple #20
0
 private Iterable<Object> start(final Reader in, final ContentHandler contentHandler)
     throws SAXException, IOException {
   try {
     SAXParserFactory parserFactory = SAXParserFactory.newInstance();
     parserFactory.setNamespaceAware(true);
     SAXParser saxParser = parserFactory.newSAXParser();
     XMLReader reader = saxParser.getXMLReader();
     reader.setContentHandler(contentHandler);
     try {
       // Do not load external DTDs (fix #8191)
       reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (SAXException e) {
       // Exception very unlikely to happen, so no need to translate this
       Main.error("Cannot disable 'load-external-dtd' feature: " + e.getMessage());
     }
     reader.parse(new InputSource(in));
     queueIterator = queue.iterator();
     return this;
   } catch (ParserConfigurationException e) {
     // This should never happen ;-)
     throw new RuntimeException(e);
   }
 }
 private final void linkTridentObjectToOsmPrimitive(TridentObjectType object, OsmPrimitive p) {
   p.put("ref:neptune", object.getObjectId());
   if (tridentObjects.put(object.getObjectId(), p) != null) {
     Main.error("Trident object duplicated !!! : " + object.getObjectId());
   }
 }
Exemple #22
0
  @Override
  public void paint(Graphics2D g, MapView mv, Bounds box) {
    final int iconHeight = ImageProvider.ImageSizes.SMALLICON.getAdjustedHeight();
    final int iconWidth = ImageProvider.ImageSizes.SMALLICON.getAdjustedWidth();

    for (Note note : noteData.getNotes()) {
      Point p = mv.getPoint(note.getLatLon());

      ImageIcon icon;
      if (note.getId() < 0) {
        icon = ImageProvider.get("dialogs/notes", "note_new", ImageProvider.ImageSizes.SMALLICON);
      } else if (note.getState() == State.CLOSED) {
        icon =
            ImageProvider.get("dialogs/notes", "note_closed", ImageProvider.ImageSizes.SMALLICON);
      } else {
        icon = ImageProvider.get("dialogs/notes", "note_open", ImageProvider.ImageSizes.SMALLICON);
      }
      int width = icon.getIconWidth();
      int height = icon.getIconHeight();
      g.drawImage(icon.getImage(), p.x - (width / 2), p.y - height, Main.map.mapView);
    }
    if (noteData.getSelectedNote() != null) {
      StringBuilder sb = new StringBuilder("<html>");
      sb.append(tr("Note")).append(' ').append(noteData.getSelectedNote().getId());
      for (NoteComment comment : noteData.getSelectedNote().getComments()) {
        String commentText = comment.getText();
        // closing a note creates an empty comment that we don't want to show
        if (commentText != null && !commentText.trim().isEmpty()) {
          sb.append("<hr/>");
          String userName = XmlWriter.encode(comment.getUser().getName());
          if (userName == null || userName.trim().isEmpty()) {
            userName = "******";
          }
          sb.append(userName);
          sb.append(" on ");
          sb.append(
              DateUtils.getDateFormat(DateFormat.MEDIUM).format(comment.getCommentTimestamp()));
          sb.append(":<br/>");
          String htmlText = XmlWriter.encode(comment.getText(), true);
          htmlText =
              htmlText.replace(
                  "&#xA;", "<br/>"); // encode method leaves us with entity instead of \n
          htmlText =
              htmlText.replace("/", "/\u200b"); // zero width space to wrap long URLs (see #10864)
          sb.append(htmlText);
        }
      }
      sb.append("</html>");
      JToolTip toolTip = new JToolTip();
      toolTip.setTipText(sb.toString());
      Point p = mv.getPoint(noteData.getSelectedNote().getLatLon());

      g.setColor(ColorHelper.html2color(Main.pref.get("color.selected")));
      g.drawRect(p.x - (iconWidth / 2), p.y - iconHeight, iconWidth - 1, iconHeight - 1);

      int tx = p.x + (iconWidth / 2) + 5;
      int ty = p.y - iconHeight - 1;
      g.translate(tx, ty);

      // Carried over from the OSB plugin. Not entirely sure why it is needed
      // but without it, the tooltip doesn't get sized correctly
      for (int x = 0; x < 2; x++) {
        Dimension d = toolTip.getUI().getPreferredSize(toolTip);
        d.width = Math.min(d.width, mv.getWidth() / 2);
        if (d.width > 0 && d.height > 0) {
          toolTip.setSize(d);
          try {
            toolTip.paint(g);
          } catch (IllegalArgumentException e) {
            // See #11123 - https://bugs.openjdk.java.net/browse/JDK-6719550
            // Ignore the exception, as Netbeans does:
            // http://hg.netbeans.org/main-silver/rev/c96f4d5fbd20
            Main.error(e, false);
          }
        }
      }
      g.translate(-tx, -ty);
    }
  }
Exemple #23
0
 /**
  * Explains an exception with a generic message dialog
  *
  * @param e the exception
  */
 public static void explainGeneric(Exception e) {
   Main.error(e);
   BugReportExceptionHandler.handleException(e);
 }
 @Override
 public void run() {
   for (; ; ) {
     while (getImagesToGrabSize() > 0) {
       lockImagesToGrag.lock();
       lockCurrentGrabImage.lock();
       currentGrabImage = imagesToGrab.get(0);
       lockCurrentGrabImage.unlock();
       imagesToGrab.remove(0);
       lockImagesToGrag.unlock();
       if (canceled) {
         break;
       } else {
         GeorefImage newImage;
         try {
           Main.map.repaint(); // paint the current grab box
           newImage = grabber.grab(wmsLayer, currentGrabImage.min, currentGrabImage.max);
         } catch (IOException e) {
           Main.warn("Download action canceled by user or server did not respond");
           setCanceled(true);
           break;
         } catch (OsmTransferException e) {
           Main.error("OSM transfer failed");
           setCanceled(true);
           break;
         }
         if (grabber.getWmsInterface().downloadCanceled) {
           Main.info("Download action canceled by user");
           setCanceled(true);
           break;
         }
         try {
           if (CadastrePlugin.backgroundTransparent) {
             wmsLayer.imagesLock.lock();
             for (GeorefImage img : wmsLayer.getImages()) {
               if (img.overlap(newImage))
                 // mask overlapping zone in already grabbed image
                 img.withdraw(newImage);
               else
                 // mask overlapping zone in new image only when new image covers completely the
                 // existing image
                 newImage.withdraw(img);
             }
             wmsLayer.imagesLock.unlock();
           }
           wmsLayer.addImage(newImage);
           Main.map.mapView.repaint();
           saveToCache(newImage);
         } catch (NullPointerException e) {
           Main.info("Layer destroyed. Cancel grab thread");
           setCanceled(true);
         }
       }
     }
     Main.info("grab thread list empty");
     lockCurrentGrabImage.lock();
     currentGrabImage = null;
     lockCurrentGrabImage.unlock();
     if (canceled) {
       clearImagesToGrab();
       canceled = false;
     }
     if (wmsLayer.isRaster()) {
       notifyWaiter();
     }
     waitNotification();
   }
 }
  protected void infoAsync(Point clickPoint) {
    cancel = false;
    /** Positional data */
    final LatLon pos = Main.map.mapView.getLatLon(clickPoint.x, clickPoint.y);

    try {
      PleaseWaitRunnable infoTask =
          new PleaseWaitRunnable(tr("Connecting server")) {
            @Override
            protected void realRun() throws SAXException {
              infoSync(pos, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, true));
            }

            @Override
            protected void finish() {}

            @Override
            protected void afterFinish() {
              if (htmlText.length() > 0) {
                // Show result
                JEditorPane msgLabel = new JEditorPane("text/html", htmlText);
                msgLabel.setEditable(false);
                msgLabel.setOpaque(false);
                msgLabel.addHyperlinkListener(
                    hle -> {
                      if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
                        if (hle.getURL() == null || hle.getURL().toString().isEmpty()) {
                          return;
                        }
                        System.out.println("URL: " + hle.getURL());
                        if (!hle.getURL().toString().startsWith("http")) {
                          mRuian.performAction(hle.getURL().toString());
                        } else {
                          String ret = OpenBrowser.displayUrl(hle.getURL().toString());
                          if (ret != null) {
                            PointInfoUtils.showNotification(ret, "error");
                          }
                        }
                      }
                    });
                JScrollPane scrollPane = new JScrollPane(msgLabel);
                Object[] objects = {scrollPane};
                final ImageIcon icon =
                    new ImageIcon(getClass().getResource("/images/dialogs/info-sml.png"));
                JOptionPane.showMessageDialog(
                    null,
                    objects,
                    tr("PointInfo") + " " + coordinatesText,
                    JOptionPane.PLAIN_MESSAGE,
                    icon);
              }
            }

            @Override
            protected void cancel() {
              PointInfoAction.this.cancel();
            }
          };
      new Thread(infoTask).start();
    } catch (Exception e) {
      Main.error(e);
    }
  }
    @Override
    public void actionPerformed(ActionEvent arg0) {
      FileFilter filter =
          new FileFilter() {
            @Override
            public boolean accept(File f) {
              return f.isDirectory() || Utils.hasExtension(f, "gpx", "gpx.gz");
            }

            @Override
            public String getDescription() {
              return tr("GPX Files (*.gpx *.gpx.gz)");
            }
          };
      AbstractFileChooser fc =
          DiskAccessAction.createAndOpenFileChooser(
              true, false, null, filter, JFileChooser.FILES_ONLY, null);
      if (fc == null) return;
      File sel = fc.getSelectedFile();

      try {
        outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        for (int i = gpxLst.size() - 1; i >= 0; i--) {
          GpxDataWrapper wrapper = gpxLst.get(i);
          if (wrapper.file != null && sel.equals(wrapper.file)) {
            cbGpx.setSelectedIndex(i);
            if (!sel.getName().equals(wrapper.name)) {
              JOptionPane.showMessageDialog(
                  Main.parent,
                  tr("File {0} is loaded yet under the name \"{1}\"", sel.getName(), wrapper.name),
                  tr("Error"),
                  JOptionPane.ERROR_MESSAGE);
            }
            return;
          }
        }
        GpxData data = null;
        try (InputStream iStream = createInputStream(sel)) {
          GpxReader reader = new GpxReader(iStream);
          reader.parse(false);
          data = reader.getGpxData();
          data.storageFile = sel;

        } catch (SAXException x) {
          Main.error(x);
          JOptionPane.showMessageDialog(
              Main.parent,
              tr("Error while parsing {0}", sel.getName()) + ": " + x.getMessage(),
              tr("Error"),
              JOptionPane.ERROR_MESSAGE);
          return;
        } catch (IOException x) {
          Main.error(x);
          JOptionPane.showMessageDialog(
              Main.parent,
              tr("Could not read \"{0}\"", sel.getName()) + '\n' + x.getMessage(),
              tr("Error"),
              JOptionPane.ERROR_MESSAGE);
          return;
        }

        loadedGpxData.add(data);
        if (gpxLst.get(0).file == null) {
          gpxLst.remove(0);
        }
        gpxLst.add(new GpxDataWrapper(sel.getName(), data, sel));
        cbGpx.setSelectedIndex(cbGpx.getItemCount() - 1);
      } finally {
        outerPanel.setCursor(Cursor.getDefaultCursor());
      }
    }
  @Override
  protected void realRun() {
    try {
      uploadloop:
      while (true) {
        try {
          getProgressMonitor()
              .subTask(
                  trn(
                      "Uploading {0} object...",
                      "Uploading {0} objects...", toUpload.getSize(), toUpload.getSize()));
          synchronized (this) {
            writer = new OsmServerWriter();
          }
          writer.uploadOsm(
              strategy,
              toUpload.getPrimitives(),
              changeset,
              getProgressMonitor().createSubTaskMonitor(1, false));

          // if we get here we've successfully uploaded the data. Exit the loop.
          //
          break;
        } catch (OsmTransferCanceledException e) {
          Main.error(e);
          uploadCanceled = true;
          break uploadloop;
        } catch (OsmApiPrimitiveGoneException e) {
          // try to recover from  410 Gone
          //
          recoverFromGoneOnServer(e, getProgressMonitor());
        } catch (ChangesetClosedException e) {
          if (writer != null) {
            processedPrimitives.addAll(
                writer.getProcessedPrimitives()); // OsmPrimitive in => OsmPrimitive out
          }
          changeset.setOpen(false);
          switch (e.getSource()) {
            case UNSPECIFIED:
              throw e;
            case UPDATE_CHANGESET:
              // The changeset was closed when we tried to update it. Probably, our
              // local list of open changesets got out of sync with the server state.
              // The user will have to select another open changeset.
              // Rethrow exception - this will be handled later.
              //
              throw e;
            case UPLOAD_DATA:
              // Most likely the changeset is full. Try to recover and continue
              // with a new changeset, but let the user decide first (see
              // recoverFromChangesetFullException)
              //
              if (recoverFromChangesetFullException()) {
                continue;
              }
              lastException = e;
              break uploadloop;
          }
        } finally {
          if (writer != null) {
            processedPrimitives.addAll(writer.getProcessedPrimitives());
          }
          synchronized (this) {
            writer = null;
          }
        }
      }
      // if required close the changeset
      //
      if (strategy.isCloseChangesetAfterUpload()
          && changeset != null
          && !changeset.isNew()
          && changeset.isOpen()) {
        OsmApi.getOsmApi()
            .closeChangeset(changeset, progressMonitor.createSubTaskMonitor(0, false));
      }
    } catch (OsmTransferException e) {
      if (uploadCanceled) {
        Main.info(
            tr(
                "Ignoring caught exception because upload is canceled. Exception is: {0}",
                e.toString()));
      } else {
        lastException = e;
      }
    }
    if (uploadCanceled && processedPrimitives.isEmpty()) return;
    cleanupAfterUpload();
  }
Exemple #28
0
    @Override
    protected void realRun() throws SAXException, IOException, OsmTransferException {
      if (files == null || files.isEmpty()) return;

      /** Find the importer with the chosen file filter */
      FileImporter chosenImporter = null;
      for (FileImporter importer : ExtensionFileFilter.importers) {
        if (fileFilter == importer.filter) {
          chosenImporter = importer;
        }
      }
      /**
       * If the filter hasn't been changed in the dialog, chosenImporter is null now. When the
       * filter has been set explicitly to AllFormatsImporter, treat this the same.
       */
      if (chosenImporter instanceof AllFormatsImporter) {
        chosenImporter = null;
      }
      getProgressMonitor().setTicksCount(files.size());

      if (chosenImporter != null) {
        // The importer was explicitly chosen, so use it.
        List<File> filesNotMatchingWithImporter = new LinkedList<File>();
        List<File> filesMatchingWithImporter = new LinkedList<File>();
        for (final File f : files) {
          if (!chosenImporter.acceptFile(f)) {
            if (f.isDirectory()) {
              SwingUtilities.invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      JOptionPane.showMessageDialog(
                          Main.parent,
                          tr(
                              "<html>Cannot open directory ''{0}''.<br>Please select a file.</html>",
                              f.getAbsolutePath()),
                          tr("Open file"),
                          JOptionPane.ERROR_MESSAGE);
                    }
                  });
              // TODO when changing to Java 6: Don't cancel the
              // task here but use different modality. (Currently 2 dialogs
              // would block each other.)
              return;
            } else {
              filesNotMatchingWithImporter.add(f);
            }
          } else {
            filesMatchingWithImporter.add(f);
          }
        }

        if (!filesNotMatchingWithImporter.isEmpty()) {
          alertFilesNotMatchingWithImporter(filesNotMatchingWithImporter, chosenImporter);
        }
        if (!filesMatchingWithImporter.isEmpty()) {
          importData(chosenImporter, filesMatchingWithImporter);
        }
      } else {
        // find appropriate importer
        MultiMap<FileImporter, File> importerMap = new MultiMap<FileImporter, File>();
        List<File> filesWithUnknownImporter = new LinkedList<File>();
        List<File> urlFiles = new LinkedList<File>();
        FILES:
        for (File f : files) {
          for (FileImporter importer : ExtensionFileFilter.importers) {
            if (importer.acceptFile(f)) {
              importerMap.put(importer, f);
              continue FILES;
            }
          }
          if (urlFileFilter.accept(f)) {
            urlFiles.add(f);
          } else {
            filesWithUnknownImporter.add(f);
          }
        }
        if (!filesWithUnknownImporter.isEmpty()) {
          alertFilesWithUnknownImporter(filesWithUnknownImporter);
        }
        List<FileImporter> importers = new ArrayList<FileImporter>(importerMap.keySet());
        Collections.sort(importers);
        Collections.reverse(importers);

        Set<String> fileHistory = new LinkedHashSet<String>();
        Set<String> failedAll = new HashSet<String>();

        for (FileImporter importer : importers) {
          List<File> files = new ArrayList<File>(importerMap.get(importer));
          importData(importer, files);
          // suppose all files will fail to load
          List<File> failedFiles = new ArrayList<File>(files);

          if (recordHistory && !importer.isBatchImporter()) {
            // remove the files which didn't fail to load from the failed list
            failedFiles.removeAll(successfullyOpenedFiles);
            for (File f : successfullyOpenedFiles) {
              fileHistory.add(f.getCanonicalPath());
            }
            for (File f : failedFiles) {
              failedAll.add(f.getCanonicalPath());
            }
          }
        }

        for (File urlFile : urlFiles) {
          try {
            BufferedReader reader = new BufferedReader(new FileReader(urlFile));
            String line;
            while ((line = reader.readLine()) != null) {
              Matcher m = Pattern.compile(".*(http://.*)").matcher(line);
              if (m.matches()) {
                String url = m.group(1);
                Main.main.menu.openLocation.openUrl(false, url);
              }
            }
            Utils.close(reader);
          } catch (Exception e) {
            Main.error(e);
          }
        }

        if (recordHistory) {
          Collection<String> oldFileHistory = Main.pref.getCollection("file-open.history");
          fileHistory.addAll(oldFileHistory);
          // remove the files which failed to load from the list
          fileHistory.removeAll(failedAll);
          int maxsize = Math.max(0, Main.pref.getInteger("file-open.history.max-size", 15));
          Main.pref.putCollectionBounded("file-open.history", maxsize, fileHistory);
        }
      }
    }
  /**
   * Downloads the picture of the selected MapillaryImage and sets in the MapillaryImageDisplay
   * object.
   *
   * @param fullQuality If the full quality picture must be downloaded or just the thumbnail.
   */
  public synchronized void updateImage(boolean fullQuality) {
    if (!SwingUtilities.isEventDispatchThread()) {
      SwingUtilities.invokeLater(this::updateImage);
    } else {
      if (!MapillaryLayer.hasInstance()) {
        return;
      }
      if (this.image == null) {
        this.mapillaryImageDisplay.setImage(null);
        setTitle(tr(BASE_TITLE));
        disableAllButtons();
        return;
      }
      // Enables/disables next/previous buttons
      this.nextButton.setEnabled(false);
      this.previousButton.setEnabled(false);
      if (this.image.getSequence() != null) {
        MapillaryAbstractImage tempImage = this.image;
        while (tempImage.next() != null) {
          tempImage = tempImage.next();
          if (tempImage.isVisible()) {
            this.nextButton.setEnabled(true);
            break;
          }
        }
      }
      if (this.image.getSequence() != null) {
        MapillaryAbstractImage tempImage = this.image;
        while (tempImage.previous() != null) {
          tempImage = tempImage.previous();
          if (tempImage.isVisible()) {
            this.previousButton.setEnabled(true);
            break;
          }
        }
      }
      if (this.image instanceof MapillaryImage) {
        this.mapillaryImageDisplay.hyperlink.setVisible(true);
        MapillaryImage mapillaryImage = (MapillaryImage) this.image;
        this.mapillaryImageDisplay.hyperlink.setURL(mapillaryImage.getKey());
        // Downloads the thumbnail.
        this.mapillaryImageDisplay.setImage(null);
        if (this.thumbnailCache != null) this.thumbnailCache.cancelOutstandingTasks();
        this.thumbnailCache =
            new MapillaryCache(mapillaryImage.getKey(), MapillaryCache.Type.THUMBNAIL);
        try {
          this.thumbnailCache.submit(this, false);
        } catch (IOException e) {
          Main.error(e);
        }

        // Downloads the full resolution image.
        if (fullQuality
            || new MapillaryCache(mapillaryImage.getKey(), MapillaryCache.Type.FULL_IMAGE).get()
                != null) {
          if (this.imageCache != null) this.imageCache.cancelOutstandingTasks();
          this.imageCache =
              new MapillaryCache(mapillaryImage.getKey(), MapillaryCache.Type.FULL_IMAGE);
          try {
            this.imageCache.submit(this, false);
          } catch (IOException e) {
            Main.error(e);
          }
        }
      } else if (this.image instanceof MapillaryImportedImage) {
        this.mapillaryImageDisplay.hyperlink.setVisible(false);
        this.mapillaryImageDisplay.hyperlink.setURL(null);
        MapillaryImportedImage mapillaryImage = (MapillaryImportedImage) this.image;
        try {
          this.mapillaryImageDisplay.setImage(mapillaryImage.getImage());
        } catch (IOException e) {
          Main.error(e);
        }
      }
      updateTitle();
    }
  }